Completed
Branch back-compat-edtr-taxes (752e0e)
by
unknown
12:08 queued 09:43
created
core/CPTs/CptQueryModifier.php 2 patches
Indentation   +578 added lines, -578 removed lines patch added patch discarded remove patch
@@ -30,582 +30,582 @@
 block discarded – undo
30 30
  */
31 31
 class CptQueryModifier
32 32
 {
33
-    /**
34
-     * @var CurrentPage $current_page
35
-     */
36
-    protected $current_page;
37
-
38
-    /**
39
-     * @var string $post_type
40
-     */
41
-    protected $post_type = '';
42
-
43
-    /**
44
-     * CPT details from CustomPostTypeDefinitions for specific post type
45
-     *
46
-     * @var array $cpt_details
47
-     */
48
-    protected $cpt_details = array();
49
-
50
-    /**
51
-     * @var EE_Table_Base[] $model_tables
52
-     */
53
-    protected $model_tables = array();
54
-
55
-    /**
56
-     * @var array $taxonomies
57
-     */
58
-    protected $taxonomies = array();
59
-
60
-    /**
61
-     * meta table for the related CPT
62
-     *
63
-     * @var EE_Secondary_Table $meta_table
64
-     */
65
-    protected $meta_table;
66
-
67
-    /**
68
-     * EEM_CPT_Base model for the related CPT
69
-     *
70
-     * @var EEM_CPT_Base $model
71
-     */
72
-    protected $model;
73
-
74
-    /**
75
-     * @var EE_Request_Handler $request_handler
76
-     */
77
-    protected $request_handler;
78
-
79
-    /**
80
-     * @var WP_Query $wp_query
81
-     */
82
-    protected $wp_query;
83
-
84
-    /**
85
-     * @var LoaderInterface $loader
86
-     */
87
-    protected $loader;
88
-
89
-    /**
90
-     * @var RequestInterface $request
91
-     */
92
-    protected $request;
93
-
94
-
95
-    /**
96
-     * CptQueryModifier constructor
97
-     *
98
-     * @param string             $post_type
99
-     * @param array              $cpt_details
100
-     * @param WP_Query           $WP_Query
101
-     * @param CurrentPage $current_page
102
-     * @param RequestInterface   $request
103
-     * @param LoaderInterface    $loader
104
-     * @throws EE_Error
105
-     */
106
-    public function __construct(
107
-        $post_type,
108
-        array $cpt_details,
109
-        WP_Query $WP_Query,
110
-        CurrentPage $current_page,
111
-        RequestInterface $request,
112
-        LoaderInterface $loader
113
-    ) {
114
-        $this->loader = $loader;
115
-        $this->request = $request;
116
-        $this->current_page = $current_page;
117
-        $this->setWpQuery($WP_Query);
118
-        $this->setPostType($post_type);
119
-        $this->setCptDetails($cpt_details);
120
-        $this->init();
121
-    }
122
-
123
-
124
-    /**
125
-     * @return string
126
-     */
127
-    public function postType()
128
-    {
129
-        return $this->post_type;
130
-    }
131
-
132
-
133
-    /**
134
-     * @param string $post_type
135
-     */
136
-    protected function setPostType($post_type)
137
-    {
138
-        $this->post_type = $post_type;
139
-    }
140
-
141
-
142
-    /**
143
-     * @return array
144
-     */
145
-    public function cptDetails()
146
-    {
147
-        return $this->cpt_details;
148
-    }
149
-
150
-
151
-    /**
152
-     * @param array $cpt_details
153
-     */
154
-    protected function setCptDetails($cpt_details)
155
-    {
156
-        $this->cpt_details = $cpt_details;
157
-    }
158
-
159
-
160
-    /**
161
-     * @return EE_Table_Base[]
162
-     */
163
-    public function modelTables()
164
-    {
165
-        return $this->model_tables;
166
-    }
167
-
168
-
169
-    /**
170
-     * @param EE_Table_Base[] $model_tables
171
-     */
172
-    protected function setModelTables($model_tables)
173
-    {
174
-        $this->model_tables = $model_tables;
175
-    }
176
-
177
-
178
-    /**
179
-     * @return array
180
-     * @throws InvalidArgumentException
181
-     * @throws InvalidDataTypeException
182
-     * @throws InvalidInterfaceException
183
-     */
184
-    public function taxonomies()
185
-    {
186
-        if (empty($this->taxonomies)) {
187
-            $this->initializeTaxonomies();
188
-        }
189
-        return $this->taxonomies;
190
-    }
191
-
192
-
193
-    /**
194
-     * @param array $taxonomies
195
-     */
196
-    protected function setTaxonomies(array $taxonomies)
197
-    {
198
-        $this->taxonomies = $taxonomies;
199
-    }
200
-
201
-
202
-    /**
203
-     * @return EE_Secondary_Table
204
-     */
205
-    public function metaTable()
206
-    {
207
-        return $this->meta_table;
208
-    }
209
-
210
-
211
-    /**
212
-     * @param EE_Secondary_Table $meta_table
213
-     */
214
-    public function setMetaTable(EE_Secondary_Table $meta_table)
215
-    {
216
-        $this->meta_table = $meta_table;
217
-    }
218
-
219
-
220
-    /**
221
-     * @return EEM_Base
222
-     */
223
-    public function model()
224
-    {
225
-        return $this->model;
226
-    }
227
-
228
-
229
-    /**
230
-     * @param EEM_Base $CPT_model
231
-     */
232
-    protected function setModel(EEM_Base $CPT_model)
233
-    {
234
-        $this->model = $CPT_model;
235
-    }
236
-
237
-
238
-    /**
239
-     * @deprecated 4.9.63.p
240
-     * @return EE_Request_Handler
241
-     */
242
-    public function request()
243
-    {
244
-        if (! $this->request_handler instanceof EE_Request_Handler) {
245
-            $this->request_handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
246
-        }
247
-        return $this->request_handler;
248
-    }
249
-
250
-
251
-
252
-    // phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
253
-
254
-
255
-    /**
256
-     * @return WP_Query
257
-     */
258
-    public function WpQuery()
259
-    {
260
-        return $this->wp_query;
261
-    }
262
-    // phpcs:enable
263
-
264
-
265
-    /**
266
-     * @param WP_Query $wp_query
267
-     */
268
-    public function setWpQuery(WP_Query $wp_query)
269
-    {
270
-        $this->wp_query = $wp_query;
271
-    }
272
-
273
-
274
-    /**
275
-     * @return void
276
-     * @throws InvalidDataTypeException
277
-     * @throws InvalidInterfaceException
278
-     * @throws InvalidArgumentException
279
-     */
280
-    protected function initializeTaxonomies()
281
-    {
282
-        // check if taxonomies have already been set and that this CPT has taxonomies registered for it
283
-        if (
284
-            empty($this->taxonomies)
285
-            && isset($this->cpt_details['args']['taxonomies'])
286
-        ) {
287
-            // if so then grab them, but we want the taxonomy name as the key
288
-            $taxonomies = array_flip($this->cpt_details['args']['taxonomies']);
289
-            // then grab the list of ALL taxonomies
290
-            /** @var CustomTaxonomyDefinitions
291
-             * $taxonomy_definitions
292
-             */
293
-            $taxonomy_definitions = $this->loader->getShared(
294
-                'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions'
295
-            );
296
-            $all_taxonomies = $taxonomy_definitions->getCustomTaxonomyDefinitions();
297
-            foreach ($taxonomies as $taxonomy => &$details) {
298
-                // add details to our taxonomies if they exist
299
-                $details = isset($all_taxonomies[ $taxonomy ])
300
-                    ? $all_taxonomies[ $taxonomy ]
301
-                    : array();
302
-            }
303
-            // ALWAYS unset() variables that were passed by reference
304
-            unset($details);
305
-            $this->setTaxonomies($taxonomies);
306
-        }
307
-    }
308
-
309
-
310
-    /**
311
-     * @since 4.9.63.p
312
-     * @throws EE_Error
313
-     */
314
-    protected function init()
315
-    {
316
-        $this->setAdditionalCptDetails();
317
-        $this->setRequestVarsIfCpt();
318
-        // convert post_type to model name
319
-        $model_name = str_replace('EE_', '', $this->cpt_details['class_name']);
320
-        // load all tables related to CPT
321
-        $this->setupModelsAndTables($model_name);
322
-        // load and instantiate CPT_*_Strategy
323
-        $CPT_Strategy = $this->cptStrategyClass($model_name);
324
-        // !!!!!!!!!!  IMPORTANT !!!!!!!!!!!!
325
-        // here's the list of available filters in the WP_Query object
326
-        // 'posts_where_paged'
327
-        // 'posts_groupby'
328
-        // 'posts_join_paged'
329
-        // 'posts_orderby'
330
-        // 'posts_distinct'
331
-        // 'post_limits'
332
-        // 'posts_fields'
333
-        // 'posts_join'
334
-        add_filter('posts_fields', array($this, 'postsFields'));
335
-        add_filter('posts_join', array($this, 'postsJoin'));
336
-        add_filter(
337
-            'get_' . $this->post_type . '_metadata',
338
-            array($CPT_Strategy, 'get_EE_post_type_metadata'),
339
-            1,
340
-            4
341
-        );
342
-        add_filter('the_posts', array($this, 'thePosts'), 1, 1);
343
-        if ($this->wp_query->is_main_query()) {
344
-            add_filter('get_edit_post_link', array($this, 'getEditPostLink'), 10, 2);
345
-            $this->addTemplateFilters();
346
-        }
347
-    }
348
-
349
-
350
-    /**
351
-     * sets some basic query vars that pertain to the CPT
352
-     *
353
-     * @access protected
354
-     * @return void
355
-     */
356
-    protected function setAdditionalCptDetails()
357
-    {
358
-        // the post or category or term that is triggering EE
359
-        $this->cpt_details['espresso_page'] = $this->current_page->isEspressoPage();
360
-        // requested post name
361
-        $this->cpt_details['post_name'] = $this->request->getRequestParam('post_name');
362
-        // add support for viewing 'private', 'draft', or 'pending' posts
363
-        if (
364
-            isset($this->wp_query->query_vars['p'])
365
-            && $this->wp_query->query_vars['p'] !== 0
366
-            && is_user_logged_in()
367
-            && current_user_can('edit_post', $this->wp_query->query_vars['p'])
368
-        ) {
369
-            // we can just inject directly into the WP_Query object
370
-            $this->wp_query->query['post_status'] = array('publish', 'private', 'draft', 'pending');
371
-            // now set the main 'ee' request var so that the appropriate module can load the appropriate template(s)
372
-            $this->request->setRequestParam('ee', $this->cpt_details['singular_slug']);
373
-        }
374
-    }
375
-
376
-
377
-    /**
378
-     * Checks if we're on a EE-CPT archive-or-single page, and if we've never set the EE request var.
379
-     * If so, sets the 'ee' request variable
380
-     * so other parts of EE can know what CPT is getting queried.
381
-     * To Mike's knowledge, this must be called from during or after the pre_get_posts hook
382
-     * in order for is_archive() and is_single() methods to work properly.
383
-     *
384
-     * @return void
385
-     */
386
-    public function setRequestVarsIfCpt()
387
-    {
388
-        // check if ee action var has been set
389
-        if (! $this->request->requestParamIsSet('ee')) {
390
-            // check that route exists for CPT archive slug
391
-            if (is_archive() && EE_Config::get_route($this->cpt_details['plural_slug'])) {
392
-                // ie: set "ee" to "events"
393
-                $this->request->setRequestParam('ee', $this->cpt_details['plural_slug']);
394
-                // or does it match a single page CPT like /event/
395
-            } elseif (is_single() && EE_Config::get_route($this->cpt_details['singular_slug'])) {
396
-                // ie: set "ee" to "event"
397
-                $this->request->setRequestParam('ee', $this->cpt_details['singular_slug']);
398
-            }
399
-        }
400
-    }
401
-
402
-
403
-    /**
404
-     * setupModelsAndTables
405
-     *
406
-     * @access protected
407
-     * @param string $model_name
408
-     * @throws EE_Error
409
-     */
410
-    protected function setupModelsAndTables($model_name)
411
-    {
412
-        // get CPT table data via CPT Model
413
-        $full_model_name = strpos($model_name, 'EEM_') !== 0
414
-            ? 'EEM_' . $model_name
415
-            : $model_name;
416
-        $model = $this->loader->getShared($full_model_name);
417
-        if (! $model instanceof EEM_Base) {
418
-            throw new EE_Error(
419
-                sprintf(
420
-                    esc_html__(
421
-                        'The "%1$s" model could not be loaded.',
422
-                        'event_espresso'
423
-                    ),
424
-                    $full_model_name
425
-                )
426
-            );
427
-        }
428
-        $this->setModel($model);
429
-        $this->setModelTables($this->model->get_tables());
430
-        $meta_model = $model_name . '_Meta';
431
-        // is there a Meta Table for this CPT?
432
-        if (
433
-            isset($this->cpt_details['tables'][ $meta_model ])
434
-            && $this->cpt_details['tables'][ $meta_model ] instanceof EE_Secondary_Table
435
-        ) {
436
-            $this->setMetaTable($this->cpt_details['tables'][ $meta_model ]);
437
-        }
438
-    }
439
-
440
-
441
-    /**
442
-     * cptStrategyClass
443
-     *
444
-     * @access protected
445
-     * @param  string $model_name
446
-     * @return string
447
-     */
448
-    protected function cptStrategyClass($model_name)
449
-    {
450
-        // creates classname like:  CPT_Event_Strategy
451
-        $CPT_Strategy_class_name = 'EE_CPT_' . $model_name . '_Strategy';
452
-        // load and instantiate
453
-        $CPT_Strategy = $this->loader->getShared(
454
-            $CPT_Strategy_class_name,
455
-            array('WP_Query' => $this->wp_query, 'CPT' => $this->cpt_details)
456
-        );
457
-        if ($CPT_Strategy === null) {
458
-            $CPT_Strategy = $this->loader->getShared(
459
-                'EE_CPT_Default_Strategy',
460
-                array('WP_Query' => $this->wp_query, 'CPT' => $this->cpt_details)
461
-            );
462
-        }
463
-        return $CPT_Strategy;
464
-    }
465
-
466
-
467
-    /**
468
-     * postsFields
469
-     *
470
-     * @access public
471
-     * @param  $SQL
472
-     * @return string
473
-     */
474
-    public function postsFields($SQL)
475
-    {
476
-        // does this CPT have a meta table ?
477
-        if ($this->meta_table instanceof EE_Secondary_Table) {
478
-            // adds something like ", wp_esp_event_meta.* " to WP Query SELECT statement
479
-            $SQL .= ', ' . $this->meta_table->get_table_name() . '.* ';
480
-        }
481
-        remove_filter('posts_fields', array($this, 'postsFields'));
482
-        return $SQL;
483
-    }
484
-
485
-
486
-    /**
487
-     * postsJoin
488
-     *
489
-     * @access public
490
-     * @param  $SQL
491
-     * @return string
492
-     */
493
-    public function postsJoin($SQL)
494
-    {
495
-        // does this CPT have a meta table ?
496
-        if ($this->meta_table instanceof EE_Secondary_Table) {
497
-            global $wpdb;
498
-            // adds something like " LEFT JOIN wp_esp_event_meta ON ( wp_esp_event_meta.EVT_ID = wp_posts.ID ) " to WP Query JOIN statement
499
-            $SQL .= ' LEFT JOIN '
500
-                    . $this->meta_table->get_table_name()
501
-                    . ' ON ( '
502
-                    . $this->meta_table->get_table_name()
503
-                    . '.'
504
-                    . $this->meta_table->get_fk_on_table()
505
-                    . ' = '
506
-                    . $wpdb->posts
507
-                    . '.ID ) ';
508
-        }
509
-        remove_filter('posts_join', array($this, 'postsJoin'));
510
-        return $SQL;
511
-    }
512
-
513
-
514
-    /**
515
-     * thePosts
516
-     *
517
-     * @access public
518
-     * @param  WP_Post[] $posts
519
-     * @return WP_Post[]
520
-     */
521
-    public function thePosts($posts)
522
-    {
523
-        $CPT_class = $this->cpt_details['class_name'];
524
-        // loop thru posts
525
-        if (is_array($posts) && $this->model instanceof EEM_CPT_Base) {
526
-            foreach ($posts as $post) {
527
-                if ($post->post_type === $this->post_type) {
528
-                    $post->{$CPT_class} = $this->model->instantiate_class_from_post_object($post);
529
-                }
530
-            }
531
-        }
532
-        remove_filter('the_posts', array($this, 'thePosts'), 1);
533
-        return $posts;
534
-    }
535
-
536
-
537
-    /**
538
-     * @param $url
539
-     * @param $ID
540
-     * @return string
541
-     */
542
-    public function getEditPostLink($url, $ID)
543
-    {
544
-        // need to make sure we only edit links if our cpt
545
-        global $post;
546
-        // notice if the cpt is registered with `show_ee_ui` set to false, we take that to mean that the WordPress core ui
547
-        // for interacting with the CPT is desired and there is no EE UI for interacting with the CPT in the admin.
548
-        if (
549
-            ! $post instanceof WP_Post
550
-            || $post->post_type !== $this->post_type
551
-            || (
552
-                isset($this->cpt_details['args']['show_ee_ui'])
553
-                && ! $this->cpt_details['args']['show_ee_ui']
554
-            )
555
-        ) {
556
-            return $url;
557
-        }
558
-        // k made it here so all is good.
559
-        return wp_nonce_url(
560
-            add_query_arg(
561
-                array('page' => $this->post_type, 'post' => $ID, 'action' => 'edit'),
562
-                admin_url('admin.php')
563
-            ),
564
-            'edit',
565
-            'edit_nonce'
566
-        );
567
-    }
568
-
569
-
570
-    /**
571
-     * Execute any template filters.
572
-     * This method is only called if in main query.
573
-     *
574
-     * @return void
575
-     */
576
-    public function addTemplateFilters()
577
-    {
578
-        // if requested cpt supports page_templates and it's the main query
579
-        if (! empty($this->cpt_details['args']['page_templates']) && $this->wp_query->is_main_query()) {
580
-            // then let's hook into the appropriate query_template hook
581
-            add_filter('single_template', array($this, 'singleCptTemplate'));
582
-        }
583
-    }
584
-
585
-
586
-    /**
587
-     * Callback for single_template wp filter.
588
-     * This is used to load the set page_template for a single ee cpt if its set.  If "default" then we load the normal
589
-     * hierarchy.
590
-     *
591
-     * @access public
592
-     * @param string $current_template Existing default template path derived for this page call.
593
-     * @return string the path to the full template file.
594
-     */
595
-    public function singleCptTemplate($current_template)
596
-    {
597
-        $object = get_queried_object();
598
-        // does this called object HAVE a page template set that is something other than the default.
599
-        $template = get_post_meta($object->ID, '_wp_page_template', true);
600
-        // exit early if default or not set or invalid path (accounts for theme changes)
601
-        if (
602
-            $template === 'default'
603
-            || empty($template)
604
-            || ! is_readable(get_stylesheet_directory() . '/' . $template)
605
-        ) {
606
-            return $current_template;
607
-        }
608
-        // made it here so we SHOULD be able to just locate the template and then return it.
609
-        return locate_template(array($template));
610
-    }
33
+	/**
34
+	 * @var CurrentPage $current_page
35
+	 */
36
+	protected $current_page;
37
+
38
+	/**
39
+	 * @var string $post_type
40
+	 */
41
+	protected $post_type = '';
42
+
43
+	/**
44
+	 * CPT details from CustomPostTypeDefinitions for specific post type
45
+	 *
46
+	 * @var array $cpt_details
47
+	 */
48
+	protected $cpt_details = array();
49
+
50
+	/**
51
+	 * @var EE_Table_Base[] $model_tables
52
+	 */
53
+	protected $model_tables = array();
54
+
55
+	/**
56
+	 * @var array $taxonomies
57
+	 */
58
+	protected $taxonomies = array();
59
+
60
+	/**
61
+	 * meta table for the related CPT
62
+	 *
63
+	 * @var EE_Secondary_Table $meta_table
64
+	 */
65
+	protected $meta_table;
66
+
67
+	/**
68
+	 * EEM_CPT_Base model for the related CPT
69
+	 *
70
+	 * @var EEM_CPT_Base $model
71
+	 */
72
+	protected $model;
73
+
74
+	/**
75
+	 * @var EE_Request_Handler $request_handler
76
+	 */
77
+	protected $request_handler;
78
+
79
+	/**
80
+	 * @var WP_Query $wp_query
81
+	 */
82
+	protected $wp_query;
83
+
84
+	/**
85
+	 * @var LoaderInterface $loader
86
+	 */
87
+	protected $loader;
88
+
89
+	/**
90
+	 * @var RequestInterface $request
91
+	 */
92
+	protected $request;
93
+
94
+
95
+	/**
96
+	 * CptQueryModifier constructor
97
+	 *
98
+	 * @param string             $post_type
99
+	 * @param array              $cpt_details
100
+	 * @param WP_Query           $WP_Query
101
+	 * @param CurrentPage $current_page
102
+	 * @param RequestInterface   $request
103
+	 * @param LoaderInterface    $loader
104
+	 * @throws EE_Error
105
+	 */
106
+	public function __construct(
107
+		$post_type,
108
+		array $cpt_details,
109
+		WP_Query $WP_Query,
110
+		CurrentPage $current_page,
111
+		RequestInterface $request,
112
+		LoaderInterface $loader
113
+	) {
114
+		$this->loader = $loader;
115
+		$this->request = $request;
116
+		$this->current_page = $current_page;
117
+		$this->setWpQuery($WP_Query);
118
+		$this->setPostType($post_type);
119
+		$this->setCptDetails($cpt_details);
120
+		$this->init();
121
+	}
122
+
123
+
124
+	/**
125
+	 * @return string
126
+	 */
127
+	public function postType()
128
+	{
129
+		return $this->post_type;
130
+	}
131
+
132
+
133
+	/**
134
+	 * @param string $post_type
135
+	 */
136
+	protected function setPostType($post_type)
137
+	{
138
+		$this->post_type = $post_type;
139
+	}
140
+
141
+
142
+	/**
143
+	 * @return array
144
+	 */
145
+	public function cptDetails()
146
+	{
147
+		return $this->cpt_details;
148
+	}
149
+
150
+
151
+	/**
152
+	 * @param array $cpt_details
153
+	 */
154
+	protected function setCptDetails($cpt_details)
155
+	{
156
+		$this->cpt_details = $cpt_details;
157
+	}
158
+
159
+
160
+	/**
161
+	 * @return EE_Table_Base[]
162
+	 */
163
+	public function modelTables()
164
+	{
165
+		return $this->model_tables;
166
+	}
167
+
168
+
169
+	/**
170
+	 * @param EE_Table_Base[] $model_tables
171
+	 */
172
+	protected function setModelTables($model_tables)
173
+	{
174
+		$this->model_tables = $model_tables;
175
+	}
176
+
177
+
178
+	/**
179
+	 * @return array
180
+	 * @throws InvalidArgumentException
181
+	 * @throws InvalidDataTypeException
182
+	 * @throws InvalidInterfaceException
183
+	 */
184
+	public function taxonomies()
185
+	{
186
+		if (empty($this->taxonomies)) {
187
+			$this->initializeTaxonomies();
188
+		}
189
+		return $this->taxonomies;
190
+	}
191
+
192
+
193
+	/**
194
+	 * @param array $taxonomies
195
+	 */
196
+	protected function setTaxonomies(array $taxonomies)
197
+	{
198
+		$this->taxonomies = $taxonomies;
199
+	}
200
+
201
+
202
+	/**
203
+	 * @return EE_Secondary_Table
204
+	 */
205
+	public function metaTable()
206
+	{
207
+		return $this->meta_table;
208
+	}
209
+
210
+
211
+	/**
212
+	 * @param EE_Secondary_Table $meta_table
213
+	 */
214
+	public function setMetaTable(EE_Secondary_Table $meta_table)
215
+	{
216
+		$this->meta_table = $meta_table;
217
+	}
218
+
219
+
220
+	/**
221
+	 * @return EEM_Base
222
+	 */
223
+	public function model()
224
+	{
225
+		return $this->model;
226
+	}
227
+
228
+
229
+	/**
230
+	 * @param EEM_Base $CPT_model
231
+	 */
232
+	protected function setModel(EEM_Base $CPT_model)
233
+	{
234
+		$this->model = $CPT_model;
235
+	}
236
+
237
+
238
+	/**
239
+	 * @deprecated 4.9.63.p
240
+	 * @return EE_Request_Handler
241
+	 */
242
+	public function request()
243
+	{
244
+		if (! $this->request_handler instanceof EE_Request_Handler) {
245
+			$this->request_handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
246
+		}
247
+		return $this->request_handler;
248
+	}
249
+
250
+
251
+
252
+	// phpcs:disable PSR1.Methods.CamelCapsMethodName.NotCamelCaps
253
+
254
+
255
+	/**
256
+	 * @return WP_Query
257
+	 */
258
+	public function WpQuery()
259
+	{
260
+		return $this->wp_query;
261
+	}
262
+	// phpcs:enable
263
+
264
+
265
+	/**
266
+	 * @param WP_Query $wp_query
267
+	 */
268
+	public function setWpQuery(WP_Query $wp_query)
269
+	{
270
+		$this->wp_query = $wp_query;
271
+	}
272
+
273
+
274
+	/**
275
+	 * @return void
276
+	 * @throws InvalidDataTypeException
277
+	 * @throws InvalidInterfaceException
278
+	 * @throws InvalidArgumentException
279
+	 */
280
+	protected function initializeTaxonomies()
281
+	{
282
+		// check if taxonomies have already been set and that this CPT has taxonomies registered for it
283
+		if (
284
+			empty($this->taxonomies)
285
+			&& isset($this->cpt_details['args']['taxonomies'])
286
+		) {
287
+			// if so then grab them, but we want the taxonomy name as the key
288
+			$taxonomies = array_flip($this->cpt_details['args']['taxonomies']);
289
+			// then grab the list of ALL taxonomies
290
+			/** @var CustomTaxonomyDefinitions
291
+			 * $taxonomy_definitions
292
+			 */
293
+			$taxonomy_definitions = $this->loader->getShared(
294
+				'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions'
295
+			);
296
+			$all_taxonomies = $taxonomy_definitions->getCustomTaxonomyDefinitions();
297
+			foreach ($taxonomies as $taxonomy => &$details) {
298
+				// add details to our taxonomies if they exist
299
+				$details = isset($all_taxonomies[ $taxonomy ])
300
+					? $all_taxonomies[ $taxonomy ]
301
+					: array();
302
+			}
303
+			// ALWAYS unset() variables that were passed by reference
304
+			unset($details);
305
+			$this->setTaxonomies($taxonomies);
306
+		}
307
+	}
308
+
309
+
310
+	/**
311
+	 * @since 4.9.63.p
312
+	 * @throws EE_Error
313
+	 */
314
+	protected function init()
315
+	{
316
+		$this->setAdditionalCptDetails();
317
+		$this->setRequestVarsIfCpt();
318
+		// convert post_type to model name
319
+		$model_name = str_replace('EE_', '', $this->cpt_details['class_name']);
320
+		// load all tables related to CPT
321
+		$this->setupModelsAndTables($model_name);
322
+		// load and instantiate CPT_*_Strategy
323
+		$CPT_Strategy = $this->cptStrategyClass($model_name);
324
+		// !!!!!!!!!!  IMPORTANT !!!!!!!!!!!!
325
+		// here's the list of available filters in the WP_Query object
326
+		// 'posts_where_paged'
327
+		// 'posts_groupby'
328
+		// 'posts_join_paged'
329
+		// 'posts_orderby'
330
+		// 'posts_distinct'
331
+		// 'post_limits'
332
+		// 'posts_fields'
333
+		// 'posts_join'
334
+		add_filter('posts_fields', array($this, 'postsFields'));
335
+		add_filter('posts_join', array($this, 'postsJoin'));
336
+		add_filter(
337
+			'get_' . $this->post_type . '_metadata',
338
+			array($CPT_Strategy, 'get_EE_post_type_metadata'),
339
+			1,
340
+			4
341
+		);
342
+		add_filter('the_posts', array($this, 'thePosts'), 1, 1);
343
+		if ($this->wp_query->is_main_query()) {
344
+			add_filter('get_edit_post_link', array($this, 'getEditPostLink'), 10, 2);
345
+			$this->addTemplateFilters();
346
+		}
347
+	}
348
+
349
+
350
+	/**
351
+	 * sets some basic query vars that pertain to the CPT
352
+	 *
353
+	 * @access protected
354
+	 * @return void
355
+	 */
356
+	protected function setAdditionalCptDetails()
357
+	{
358
+		// the post or category or term that is triggering EE
359
+		$this->cpt_details['espresso_page'] = $this->current_page->isEspressoPage();
360
+		// requested post name
361
+		$this->cpt_details['post_name'] = $this->request->getRequestParam('post_name');
362
+		// add support for viewing 'private', 'draft', or 'pending' posts
363
+		if (
364
+			isset($this->wp_query->query_vars['p'])
365
+			&& $this->wp_query->query_vars['p'] !== 0
366
+			&& is_user_logged_in()
367
+			&& current_user_can('edit_post', $this->wp_query->query_vars['p'])
368
+		) {
369
+			// we can just inject directly into the WP_Query object
370
+			$this->wp_query->query['post_status'] = array('publish', 'private', 'draft', 'pending');
371
+			// now set the main 'ee' request var so that the appropriate module can load the appropriate template(s)
372
+			$this->request->setRequestParam('ee', $this->cpt_details['singular_slug']);
373
+		}
374
+	}
375
+
376
+
377
+	/**
378
+	 * Checks if we're on a EE-CPT archive-or-single page, and if we've never set the EE request var.
379
+	 * If so, sets the 'ee' request variable
380
+	 * so other parts of EE can know what CPT is getting queried.
381
+	 * To Mike's knowledge, this must be called from during or after the pre_get_posts hook
382
+	 * in order for is_archive() and is_single() methods to work properly.
383
+	 *
384
+	 * @return void
385
+	 */
386
+	public function setRequestVarsIfCpt()
387
+	{
388
+		// check if ee action var has been set
389
+		if (! $this->request->requestParamIsSet('ee')) {
390
+			// check that route exists for CPT archive slug
391
+			if (is_archive() && EE_Config::get_route($this->cpt_details['plural_slug'])) {
392
+				// ie: set "ee" to "events"
393
+				$this->request->setRequestParam('ee', $this->cpt_details['plural_slug']);
394
+				// or does it match a single page CPT like /event/
395
+			} elseif (is_single() && EE_Config::get_route($this->cpt_details['singular_slug'])) {
396
+				// ie: set "ee" to "event"
397
+				$this->request->setRequestParam('ee', $this->cpt_details['singular_slug']);
398
+			}
399
+		}
400
+	}
401
+
402
+
403
+	/**
404
+	 * setupModelsAndTables
405
+	 *
406
+	 * @access protected
407
+	 * @param string $model_name
408
+	 * @throws EE_Error
409
+	 */
410
+	protected function setupModelsAndTables($model_name)
411
+	{
412
+		// get CPT table data via CPT Model
413
+		$full_model_name = strpos($model_name, 'EEM_') !== 0
414
+			? 'EEM_' . $model_name
415
+			: $model_name;
416
+		$model = $this->loader->getShared($full_model_name);
417
+		if (! $model instanceof EEM_Base) {
418
+			throw new EE_Error(
419
+				sprintf(
420
+					esc_html__(
421
+						'The "%1$s" model could not be loaded.',
422
+						'event_espresso'
423
+					),
424
+					$full_model_name
425
+				)
426
+			);
427
+		}
428
+		$this->setModel($model);
429
+		$this->setModelTables($this->model->get_tables());
430
+		$meta_model = $model_name . '_Meta';
431
+		// is there a Meta Table for this CPT?
432
+		if (
433
+			isset($this->cpt_details['tables'][ $meta_model ])
434
+			&& $this->cpt_details['tables'][ $meta_model ] instanceof EE_Secondary_Table
435
+		) {
436
+			$this->setMetaTable($this->cpt_details['tables'][ $meta_model ]);
437
+		}
438
+	}
439
+
440
+
441
+	/**
442
+	 * cptStrategyClass
443
+	 *
444
+	 * @access protected
445
+	 * @param  string $model_name
446
+	 * @return string
447
+	 */
448
+	protected function cptStrategyClass($model_name)
449
+	{
450
+		// creates classname like:  CPT_Event_Strategy
451
+		$CPT_Strategy_class_name = 'EE_CPT_' . $model_name . '_Strategy';
452
+		// load and instantiate
453
+		$CPT_Strategy = $this->loader->getShared(
454
+			$CPT_Strategy_class_name,
455
+			array('WP_Query' => $this->wp_query, 'CPT' => $this->cpt_details)
456
+		);
457
+		if ($CPT_Strategy === null) {
458
+			$CPT_Strategy = $this->loader->getShared(
459
+				'EE_CPT_Default_Strategy',
460
+				array('WP_Query' => $this->wp_query, 'CPT' => $this->cpt_details)
461
+			);
462
+		}
463
+		return $CPT_Strategy;
464
+	}
465
+
466
+
467
+	/**
468
+	 * postsFields
469
+	 *
470
+	 * @access public
471
+	 * @param  $SQL
472
+	 * @return string
473
+	 */
474
+	public function postsFields($SQL)
475
+	{
476
+		// does this CPT have a meta table ?
477
+		if ($this->meta_table instanceof EE_Secondary_Table) {
478
+			// adds something like ", wp_esp_event_meta.* " to WP Query SELECT statement
479
+			$SQL .= ', ' . $this->meta_table->get_table_name() . '.* ';
480
+		}
481
+		remove_filter('posts_fields', array($this, 'postsFields'));
482
+		return $SQL;
483
+	}
484
+
485
+
486
+	/**
487
+	 * postsJoin
488
+	 *
489
+	 * @access public
490
+	 * @param  $SQL
491
+	 * @return string
492
+	 */
493
+	public function postsJoin($SQL)
494
+	{
495
+		// does this CPT have a meta table ?
496
+		if ($this->meta_table instanceof EE_Secondary_Table) {
497
+			global $wpdb;
498
+			// adds something like " LEFT JOIN wp_esp_event_meta ON ( wp_esp_event_meta.EVT_ID = wp_posts.ID ) " to WP Query JOIN statement
499
+			$SQL .= ' LEFT JOIN '
500
+					. $this->meta_table->get_table_name()
501
+					. ' ON ( '
502
+					. $this->meta_table->get_table_name()
503
+					. '.'
504
+					. $this->meta_table->get_fk_on_table()
505
+					. ' = '
506
+					. $wpdb->posts
507
+					. '.ID ) ';
508
+		}
509
+		remove_filter('posts_join', array($this, 'postsJoin'));
510
+		return $SQL;
511
+	}
512
+
513
+
514
+	/**
515
+	 * thePosts
516
+	 *
517
+	 * @access public
518
+	 * @param  WP_Post[] $posts
519
+	 * @return WP_Post[]
520
+	 */
521
+	public function thePosts($posts)
522
+	{
523
+		$CPT_class = $this->cpt_details['class_name'];
524
+		// loop thru posts
525
+		if (is_array($posts) && $this->model instanceof EEM_CPT_Base) {
526
+			foreach ($posts as $post) {
527
+				if ($post->post_type === $this->post_type) {
528
+					$post->{$CPT_class} = $this->model->instantiate_class_from_post_object($post);
529
+				}
530
+			}
531
+		}
532
+		remove_filter('the_posts', array($this, 'thePosts'), 1);
533
+		return $posts;
534
+	}
535
+
536
+
537
+	/**
538
+	 * @param $url
539
+	 * @param $ID
540
+	 * @return string
541
+	 */
542
+	public function getEditPostLink($url, $ID)
543
+	{
544
+		// need to make sure we only edit links if our cpt
545
+		global $post;
546
+		// notice if the cpt is registered with `show_ee_ui` set to false, we take that to mean that the WordPress core ui
547
+		// for interacting with the CPT is desired and there is no EE UI for interacting with the CPT in the admin.
548
+		if (
549
+			! $post instanceof WP_Post
550
+			|| $post->post_type !== $this->post_type
551
+			|| (
552
+				isset($this->cpt_details['args']['show_ee_ui'])
553
+				&& ! $this->cpt_details['args']['show_ee_ui']
554
+			)
555
+		) {
556
+			return $url;
557
+		}
558
+		// k made it here so all is good.
559
+		return wp_nonce_url(
560
+			add_query_arg(
561
+				array('page' => $this->post_type, 'post' => $ID, 'action' => 'edit'),
562
+				admin_url('admin.php')
563
+			),
564
+			'edit',
565
+			'edit_nonce'
566
+		);
567
+	}
568
+
569
+
570
+	/**
571
+	 * Execute any template filters.
572
+	 * This method is only called if in main query.
573
+	 *
574
+	 * @return void
575
+	 */
576
+	public function addTemplateFilters()
577
+	{
578
+		// if requested cpt supports page_templates and it's the main query
579
+		if (! empty($this->cpt_details['args']['page_templates']) && $this->wp_query->is_main_query()) {
580
+			// then let's hook into the appropriate query_template hook
581
+			add_filter('single_template', array($this, 'singleCptTemplate'));
582
+		}
583
+	}
584
+
585
+
586
+	/**
587
+	 * Callback for single_template wp filter.
588
+	 * This is used to load the set page_template for a single ee cpt if its set.  If "default" then we load the normal
589
+	 * hierarchy.
590
+	 *
591
+	 * @access public
592
+	 * @param string $current_template Existing default template path derived for this page call.
593
+	 * @return string the path to the full template file.
594
+	 */
595
+	public function singleCptTemplate($current_template)
596
+	{
597
+		$object = get_queried_object();
598
+		// does this called object HAVE a page template set that is something other than the default.
599
+		$template = get_post_meta($object->ID, '_wp_page_template', true);
600
+		// exit early if default or not set or invalid path (accounts for theme changes)
601
+		if (
602
+			$template === 'default'
603
+			|| empty($template)
604
+			|| ! is_readable(get_stylesheet_directory() . '/' . $template)
605
+		) {
606
+			return $current_template;
607
+		}
608
+		// made it here so we SHOULD be able to just locate the template and then return it.
609
+		return locate_template(array($template));
610
+	}
611 611
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
      */
242 242
     public function request()
243 243
     {
244
-        if (! $this->request_handler instanceof EE_Request_Handler) {
244
+        if ( ! $this->request_handler instanceof EE_Request_Handler) {
245 245
             $this->request_handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
246 246
         }
247 247
         return $this->request_handler;
@@ -296,8 +296,8 @@  discard block
 block discarded – undo
296 296
             $all_taxonomies = $taxonomy_definitions->getCustomTaxonomyDefinitions();
297 297
             foreach ($taxonomies as $taxonomy => &$details) {
298 298
                 // add details to our taxonomies if they exist
299
-                $details = isset($all_taxonomies[ $taxonomy ])
300
-                    ? $all_taxonomies[ $taxonomy ]
299
+                $details = isset($all_taxonomies[$taxonomy])
300
+                    ? $all_taxonomies[$taxonomy]
301 301
                     : array();
302 302
             }
303 303
             // ALWAYS unset() variables that were passed by reference
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
         add_filter('posts_fields', array($this, 'postsFields'));
335 335
         add_filter('posts_join', array($this, 'postsJoin'));
336 336
         add_filter(
337
-            'get_' . $this->post_type . '_metadata',
337
+            'get_'.$this->post_type.'_metadata',
338 338
             array($CPT_Strategy, 'get_EE_post_type_metadata'),
339 339
             1,
340 340
             4
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
     public function setRequestVarsIfCpt()
387 387
     {
388 388
         // check if ee action var has been set
389
-        if (! $this->request->requestParamIsSet('ee')) {
389
+        if ( ! $this->request->requestParamIsSet('ee')) {
390 390
             // check that route exists for CPT archive slug
391 391
             if (is_archive() && EE_Config::get_route($this->cpt_details['plural_slug'])) {
392 392
                 // ie: set "ee" to "events"
@@ -411,10 +411,10 @@  discard block
 block discarded – undo
411 411
     {
412 412
         // get CPT table data via CPT Model
413 413
         $full_model_name = strpos($model_name, 'EEM_') !== 0
414
-            ? 'EEM_' . $model_name
414
+            ? 'EEM_'.$model_name
415 415
             : $model_name;
416 416
         $model = $this->loader->getShared($full_model_name);
417
-        if (! $model instanceof EEM_Base) {
417
+        if ( ! $model instanceof EEM_Base) {
418 418
             throw new EE_Error(
419 419
                 sprintf(
420 420
                     esc_html__(
@@ -427,13 +427,13 @@  discard block
 block discarded – undo
427 427
         }
428 428
         $this->setModel($model);
429 429
         $this->setModelTables($this->model->get_tables());
430
-        $meta_model = $model_name . '_Meta';
430
+        $meta_model = $model_name.'_Meta';
431 431
         // is there a Meta Table for this CPT?
432 432
         if (
433
-            isset($this->cpt_details['tables'][ $meta_model ])
434
-            && $this->cpt_details['tables'][ $meta_model ] instanceof EE_Secondary_Table
433
+            isset($this->cpt_details['tables'][$meta_model])
434
+            && $this->cpt_details['tables'][$meta_model] instanceof EE_Secondary_Table
435 435
         ) {
436
-            $this->setMetaTable($this->cpt_details['tables'][ $meta_model ]);
436
+            $this->setMetaTable($this->cpt_details['tables'][$meta_model]);
437 437
         }
438 438
     }
439 439
 
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
     protected function cptStrategyClass($model_name)
449 449
     {
450 450
         // creates classname like:  CPT_Event_Strategy
451
-        $CPT_Strategy_class_name = 'EE_CPT_' . $model_name . '_Strategy';
451
+        $CPT_Strategy_class_name = 'EE_CPT_'.$model_name.'_Strategy';
452 452
         // load and instantiate
453 453
         $CPT_Strategy = $this->loader->getShared(
454 454
             $CPT_Strategy_class_name,
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
         // does this CPT have a meta table ?
477 477
         if ($this->meta_table instanceof EE_Secondary_Table) {
478 478
             // adds something like ", wp_esp_event_meta.* " to WP Query SELECT statement
479
-            $SQL .= ', ' . $this->meta_table->get_table_name() . '.* ';
479
+            $SQL .= ', '.$this->meta_table->get_table_name().'.* ';
480 480
         }
481 481
         remove_filter('posts_fields', array($this, 'postsFields'));
482 482
         return $SQL;
@@ -576,7 +576,7 @@  discard block
 block discarded – undo
576 576
     public function addTemplateFilters()
577 577
     {
578 578
         // if requested cpt supports page_templates and it's the main query
579
-        if (! empty($this->cpt_details['args']['page_templates']) && $this->wp_query->is_main_query()) {
579
+        if ( ! empty($this->cpt_details['args']['page_templates']) && $this->wp_query->is_main_query()) {
580 580
             // then let's hook into the appropriate query_template hook
581 581
             add_filter('single_template', array($this, 'singleCptTemplate'));
582 582
         }
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
         if (
602 602
             $template === 'default'
603 603
             || empty($template)
604
-            || ! is_readable(get_stylesheet_directory() . '/' . $template)
604
+            || ! is_readable(get_stylesheet_directory().'/'.$template)
605 605
         ) {
606 606
             return $current_template;
607 607
         }
Please login to merge, or discard this patch.
core/EE_Cron_Tasks.core.php 2 patches
Indentation   +600 added lines, -600 removed lines patch added patch discarded remove patch
@@ -15,607 +15,607 @@
 block discarded – undo
15 15
 class EE_Cron_Tasks extends EE_Base
16 16
 {
17 17
 
18
-    /**
19
-     * WordPress doesn't allow duplicate crons within 10 minutes of the original,
20
-     * so we'll set our retry time for just over 10 minutes to avoid that
21
-     */
22
-    const reschedule_timeout = 605;
23
-
24
-
25
-    /**
26
-     * @var EE_Cron_Tasks
27
-     */
28
-    private static $_instance;
29
-
30
-
31
-    /**
32
-     * @return EE_Cron_Tasks
33
-     * @throws ReflectionException
34
-     * @throws EE_Error
35
-     * @throws InvalidArgumentException
36
-     * @throws InvalidInterfaceException
37
-     * @throws InvalidDataTypeException
38
-     */
39
-    public static function instance()
40
-    {
41
-        if (! self::$_instance instanceof EE_Cron_Tasks) {
42
-            self::$_instance = new self();
43
-        }
44
-        return self::$_instance;
45
-    }
46
-
47
-
48
-    /**
49
-     * @access private
50
-     * @throws InvalidDataTypeException
51
-     * @throws InvalidInterfaceException
52
-     * @throws InvalidArgumentException
53
-     * @throws EE_Error
54
-     * @throws ReflectionException
55
-     */
56
-    private function __construct()
57
-    {
58
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
59
-        // verify that WP Cron is enabled
60
-        if (
61
-            defined('DISABLE_WP_CRON')
62
-            && DISABLE_WP_CRON
63
-            && is_admin()
64
-            && ! get_option('ee_disabled_wp_cron_check')
65
-        ) {
66
-            /**
67
-             * This needs to be delayed until after the config is loaded because EE_Cron_Tasks is constructed before
68
-             * config is loaded.
69
-             * This is intentionally using a anonymous function so that its not easily de-registered.  Client code
70
-             * wanting to not have this functionality can just register its own action at a priority after this one to
71
-             * reverse any changes.
72
-             */
73
-            add_action(
74
-                'AHEE__EE_System__load_core_configuration__complete',
75
-                function () {
76
-                    EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
77
-                    EE_Registry::instance()->NET_CFG->update_config(true, false);
78
-                    add_option('ee_disabled_wp_cron_check', 1, '', false);
79
-                }
80
-            );
81
-        }
82
-        // UPDATE TRANSACTION WITH PAYMENT
83
-        add_action(
84
-            'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
85
-            array('EE_Cron_Tasks', 'setup_update_for_transaction_with_payment'),
86
-            10,
87
-            2
88
-        );
89
-        // ABANDONED / EXPIRED TRANSACTION CHECK
90
-        add_action(
91
-            'AHEE__EE_Cron_Tasks__expired_transaction_check',
92
-            array('EE_Cron_Tasks', 'expired_transaction_check'),
93
-            10,
94
-            1
95
-        );
96
-        // CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
97
-        add_action(
98
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
99
-            array('EE_Cron_Tasks', 'clean_out_junk_transactions')
100
-        );
101
-        // logging
102
-        add_action(
103
-            'AHEE__EE_System__load_core_configuration__complete',
104
-            array('EE_Cron_Tasks', 'log_scheduled_ee_crons')
105
-        );
106
-        EE_Registry::instance()->load_lib('Messages_Scheduler');
107
-        // clean out old gateway logs
108
-        add_action(
109
-            'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs',
110
-            array('EE_Cron_Tasks', 'clean_out_old_gateway_logs')
111
-        );
112
-    }
113
-
114
-
115
-    /**
116
-     * @access protected
117
-     * @return void
118
-     */
119
-    public static function log_scheduled_ee_crons()
120
-    {
121
-        $ee_crons = array(
122
-            'AHEE__EE_Cron_Tasks__update_transaction_with_payment',
123
-            'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
124
-            'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
125
-        );
126
-        $crons = (array) get_option('cron');
127
-        if (! is_array($crons)) {
128
-            return;
129
-        }
130
-        foreach ($crons as $timestamp => $cron) {
131
-            /** @var array[] $cron */
132
-            foreach ($ee_crons as $ee_cron) {
133
-                if (isset($cron[ $ee_cron ]) && is_array($cron[ $ee_cron ])) {
134
-                    do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
135
-                    foreach ($cron[ $ee_cron ] as $ee_cron_details) {
136
-                        if (! empty($ee_cron_details['args'])) {
137
-                            do_action(
138
-                                'AHEE_log',
139
-                                __CLASS__,
140
-                                __FUNCTION__,
141
-                                print_r($ee_cron_details['args'], true),
142
-                                "{$ee_cron} args"
143
-                            );
144
-                        }
145
-                    }
146
-                }
147
-            }
148
-        }
149
-    }
150
-
151
-
152
-    /**
153
-     * reschedule_cron_for_transactions_if_maintenance_mode
154
-     * if Maintenance Mode is active, this will reschedule a cron to run again in 10 minutes
155
-     *
156
-     * @param string $cron_task
157
-     * @param array  $TXN_IDs
158
-     * @return bool
159
-     * @throws DomainException
160
-     */
161
-    public static function reschedule_cron_for_transactions_if_maintenance_mode($cron_task, array $TXN_IDs)
162
-    {
163
-        if (! method_exists('EE_Cron_Tasks', $cron_task)) {
164
-            throw new DomainException(
165
-                sprintf(
166
-                    esc_html__('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
167
-                    $cron_task
168
-                )
169
-            );
170
-        }
171
-        // reschedule the cron if we can't hit the db right now
172
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
173
-            foreach ($TXN_IDs as $TXN_ID => $additional_vars) {
174
-                // ensure $additional_vars is an array
175
-                $additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
176
-                // reset cron job for the TXN
177
-                call_user_func_array(
178
-                    array('EE_Cron_Tasks', $cron_task),
179
-                    array_merge(
180
-                        array(
181
-                            time() + (10 * MINUTE_IN_SECONDS),
182
-                            $TXN_ID,
183
-                        ),
184
-                        $additional_vars
185
-                    )
186
-                );
187
-            }
188
-            return true;
189
-        }
190
-        return false;
191
-    }
192
-
193
-
194
-
195
-
196
-    /****************  UPDATE TRANSACTION WITH PAYMENT ****************/
197
-
198
-
199
-    /**
200
-     * array of TXN IDs and the payment
201
-     *
202
-     * @var array
203
-     */
204
-    protected static $_update_transactions_with_payment = array();
205
-
206
-
207
-    /**
208
-     * schedule_update_transaction_with_payment
209
-     * sets a wp_schedule_single_event() for updating any TXNs that may
210
-     * require updating due to recently received payments
211
-     *
212
-     * @param int $timestamp
213
-     * @param int $TXN_ID
214
-     * @param int $PAY_ID
215
-     */
216
-    public static function schedule_update_transaction_with_payment(
217
-        $timestamp,
218
-        $TXN_ID,
219
-        $PAY_ID
220
-    ) {
221
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
222
-        // validate $TXN_ID and $timestamp
223
-        $TXN_ID = absint($TXN_ID);
224
-        $timestamp = absint($timestamp);
225
-        if ($TXN_ID && $timestamp) {
226
-            wp_schedule_single_event(
227
-                $timestamp,
228
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
229
-                array($TXN_ID, $PAY_ID)
230
-            );
231
-        }
232
-    }
233
-
234
-
235
-    /**
236
-     * setup_update_for_transaction_with_payment
237
-     * this is the callback for the action hook:
238
-     * 'AHEE__EE_Cron_Tasks__update_transaction_with_payment'
239
-     * which is setup by EE_Cron_Tasks::schedule_update_transaction_with_payment().
240
-     * The passed TXN_ID and associated payment gets added to an array, and then
241
-     * the EE_Cron_Tasks::update_transaction_with_payment() function is hooked into
242
-     * 'shutdown' which will actually handle the processing of any
243
-     * transactions requiring updating, because doing so now would be too early
244
-     * and the required resources may not be available
245
-     *
246
-     * @param int $TXN_ID
247
-     * @param int $PAY_ID
248
-     */
249
-    public static function setup_update_for_transaction_with_payment($TXN_ID = 0, $PAY_ID = 0)
250
-    {
251
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
252
-        if (absint($TXN_ID)) {
253
-            self::$_update_transactions_with_payment[ $TXN_ID ] = $PAY_ID;
254
-            add_action(
255
-                'shutdown',
256
-                array('EE_Cron_Tasks', 'update_transaction_with_payment'),
257
-                5
258
-            );
259
-        }
260
-    }
261
-
262
-
263
-    /**
264
-     * update_transaction_with_payment
265
-     * loops through the self::$_abandoned_transactions array
266
-     * and attempts to finalize any TXNs that have not been completed
267
-     * but have had their sessions expired, most likely due to a user not
268
-     * returning from an off-site payment gateway
269
-     *
270
-     * @throws EE_Error
271
-     * @throws DomainException
272
-     * @throws InvalidDataTypeException
273
-     * @throws InvalidInterfaceException
274
-     * @throws InvalidArgumentException
275
-     * @throws ReflectionException
276
-     * @throws RuntimeException
277
-     */
278
-    public static function update_transaction_with_payment()
279
-    {
280
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
281
-        if (
18
+	/**
19
+	 * WordPress doesn't allow duplicate crons within 10 minutes of the original,
20
+	 * so we'll set our retry time for just over 10 minutes to avoid that
21
+	 */
22
+	const reschedule_timeout = 605;
23
+
24
+
25
+	/**
26
+	 * @var EE_Cron_Tasks
27
+	 */
28
+	private static $_instance;
29
+
30
+
31
+	/**
32
+	 * @return EE_Cron_Tasks
33
+	 * @throws ReflectionException
34
+	 * @throws EE_Error
35
+	 * @throws InvalidArgumentException
36
+	 * @throws InvalidInterfaceException
37
+	 * @throws InvalidDataTypeException
38
+	 */
39
+	public static function instance()
40
+	{
41
+		if (! self::$_instance instanceof EE_Cron_Tasks) {
42
+			self::$_instance = new self();
43
+		}
44
+		return self::$_instance;
45
+	}
46
+
47
+
48
+	/**
49
+	 * @access private
50
+	 * @throws InvalidDataTypeException
51
+	 * @throws InvalidInterfaceException
52
+	 * @throws InvalidArgumentException
53
+	 * @throws EE_Error
54
+	 * @throws ReflectionException
55
+	 */
56
+	private function __construct()
57
+	{
58
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
59
+		// verify that WP Cron is enabled
60
+		if (
61
+			defined('DISABLE_WP_CRON')
62
+			&& DISABLE_WP_CRON
63
+			&& is_admin()
64
+			&& ! get_option('ee_disabled_wp_cron_check')
65
+		) {
66
+			/**
67
+			 * This needs to be delayed until after the config is loaded because EE_Cron_Tasks is constructed before
68
+			 * config is loaded.
69
+			 * This is intentionally using a anonymous function so that its not easily de-registered.  Client code
70
+			 * wanting to not have this functionality can just register its own action at a priority after this one to
71
+			 * reverse any changes.
72
+			 */
73
+			add_action(
74
+				'AHEE__EE_System__load_core_configuration__complete',
75
+				function () {
76
+					EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
77
+					EE_Registry::instance()->NET_CFG->update_config(true, false);
78
+					add_option('ee_disabled_wp_cron_check', 1, '', false);
79
+				}
80
+			);
81
+		}
82
+		// UPDATE TRANSACTION WITH PAYMENT
83
+		add_action(
84
+			'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
85
+			array('EE_Cron_Tasks', 'setup_update_for_transaction_with_payment'),
86
+			10,
87
+			2
88
+		);
89
+		// ABANDONED / EXPIRED TRANSACTION CHECK
90
+		add_action(
91
+			'AHEE__EE_Cron_Tasks__expired_transaction_check',
92
+			array('EE_Cron_Tasks', 'expired_transaction_check'),
93
+			10,
94
+			1
95
+		);
96
+		// CLEAN OUT JUNK TRANSACTIONS AND RELATED DATA
97
+		add_action(
98
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
99
+			array('EE_Cron_Tasks', 'clean_out_junk_transactions')
100
+		);
101
+		// logging
102
+		add_action(
103
+			'AHEE__EE_System__load_core_configuration__complete',
104
+			array('EE_Cron_Tasks', 'log_scheduled_ee_crons')
105
+		);
106
+		EE_Registry::instance()->load_lib('Messages_Scheduler');
107
+		// clean out old gateway logs
108
+		add_action(
109
+			'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs',
110
+			array('EE_Cron_Tasks', 'clean_out_old_gateway_logs')
111
+		);
112
+	}
113
+
114
+
115
+	/**
116
+	 * @access protected
117
+	 * @return void
118
+	 */
119
+	public static function log_scheduled_ee_crons()
120
+	{
121
+		$ee_crons = array(
122
+			'AHEE__EE_Cron_Tasks__update_transaction_with_payment',
123
+			'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions',
124
+			'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
125
+		);
126
+		$crons = (array) get_option('cron');
127
+		if (! is_array($crons)) {
128
+			return;
129
+		}
130
+		foreach ($crons as $timestamp => $cron) {
131
+			/** @var array[] $cron */
132
+			foreach ($ee_crons as $ee_cron) {
133
+				if (isset($cron[ $ee_cron ]) && is_array($cron[ $ee_cron ])) {
134
+					do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
135
+					foreach ($cron[ $ee_cron ] as $ee_cron_details) {
136
+						if (! empty($ee_cron_details['args'])) {
137
+							do_action(
138
+								'AHEE_log',
139
+								__CLASS__,
140
+								__FUNCTION__,
141
+								print_r($ee_cron_details['args'], true),
142
+								"{$ee_cron} args"
143
+							);
144
+						}
145
+					}
146
+				}
147
+			}
148
+		}
149
+	}
150
+
151
+
152
+	/**
153
+	 * reschedule_cron_for_transactions_if_maintenance_mode
154
+	 * if Maintenance Mode is active, this will reschedule a cron to run again in 10 minutes
155
+	 *
156
+	 * @param string $cron_task
157
+	 * @param array  $TXN_IDs
158
+	 * @return bool
159
+	 * @throws DomainException
160
+	 */
161
+	public static function reschedule_cron_for_transactions_if_maintenance_mode($cron_task, array $TXN_IDs)
162
+	{
163
+		if (! method_exists('EE_Cron_Tasks', $cron_task)) {
164
+			throw new DomainException(
165
+				sprintf(
166
+					esc_html__('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
167
+					$cron_task
168
+				)
169
+			);
170
+		}
171
+		// reschedule the cron if we can't hit the db right now
172
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
173
+			foreach ($TXN_IDs as $TXN_ID => $additional_vars) {
174
+				// ensure $additional_vars is an array
175
+				$additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
176
+				// reset cron job for the TXN
177
+				call_user_func_array(
178
+					array('EE_Cron_Tasks', $cron_task),
179
+					array_merge(
180
+						array(
181
+							time() + (10 * MINUTE_IN_SECONDS),
182
+							$TXN_ID,
183
+						),
184
+						$additional_vars
185
+					)
186
+				);
187
+			}
188
+			return true;
189
+		}
190
+		return false;
191
+	}
192
+
193
+
194
+
195
+
196
+	/****************  UPDATE TRANSACTION WITH PAYMENT ****************/
197
+
198
+
199
+	/**
200
+	 * array of TXN IDs and the payment
201
+	 *
202
+	 * @var array
203
+	 */
204
+	protected static $_update_transactions_with_payment = array();
205
+
206
+
207
+	/**
208
+	 * schedule_update_transaction_with_payment
209
+	 * sets a wp_schedule_single_event() for updating any TXNs that may
210
+	 * require updating due to recently received payments
211
+	 *
212
+	 * @param int $timestamp
213
+	 * @param int $TXN_ID
214
+	 * @param int $PAY_ID
215
+	 */
216
+	public static function schedule_update_transaction_with_payment(
217
+		$timestamp,
218
+		$TXN_ID,
219
+		$PAY_ID
220
+	) {
221
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
222
+		// validate $TXN_ID and $timestamp
223
+		$TXN_ID = absint($TXN_ID);
224
+		$timestamp = absint($timestamp);
225
+		if ($TXN_ID && $timestamp) {
226
+			wp_schedule_single_event(
227
+				$timestamp,
228
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment_2',
229
+				array($TXN_ID, $PAY_ID)
230
+			);
231
+		}
232
+	}
233
+
234
+
235
+	/**
236
+	 * setup_update_for_transaction_with_payment
237
+	 * this is the callback for the action hook:
238
+	 * 'AHEE__EE_Cron_Tasks__update_transaction_with_payment'
239
+	 * which is setup by EE_Cron_Tasks::schedule_update_transaction_with_payment().
240
+	 * The passed TXN_ID and associated payment gets added to an array, and then
241
+	 * the EE_Cron_Tasks::update_transaction_with_payment() function is hooked into
242
+	 * 'shutdown' which will actually handle the processing of any
243
+	 * transactions requiring updating, because doing so now would be too early
244
+	 * and the required resources may not be available
245
+	 *
246
+	 * @param int $TXN_ID
247
+	 * @param int $PAY_ID
248
+	 */
249
+	public static function setup_update_for_transaction_with_payment($TXN_ID = 0, $PAY_ID = 0)
250
+	{
251
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
252
+		if (absint($TXN_ID)) {
253
+			self::$_update_transactions_with_payment[ $TXN_ID ] = $PAY_ID;
254
+			add_action(
255
+				'shutdown',
256
+				array('EE_Cron_Tasks', 'update_transaction_with_payment'),
257
+				5
258
+			);
259
+		}
260
+	}
261
+
262
+
263
+	/**
264
+	 * update_transaction_with_payment
265
+	 * loops through the self::$_abandoned_transactions array
266
+	 * and attempts to finalize any TXNs that have not been completed
267
+	 * but have had their sessions expired, most likely due to a user not
268
+	 * returning from an off-site payment gateway
269
+	 *
270
+	 * @throws EE_Error
271
+	 * @throws DomainException
272
+	 * @throws InvalidDataTypeException
273
+	 * @throws InvalidInterfaceException
274
+	 * @throws InvalidArgumentException
275
+	 * @throws ReflectionException
276
+	 * @throws RuntimeException
277
+	 */
278
+	public static function update_transaction_with_payment()
279
+	{
280
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
281
+		if (
282 282
 // are there any TXNs that need cleaning up ?
283
-            empty(self::$_update_transactions_with_payment)
284
-            // reschedule the cron if we can't hit the db right now
285
-            || EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
286
-                'schedule_update_transaction_with_payment',
287
-                self::$_update_transactions_with_payment
288
-            )
289
-        ) {
290
-            return;
291
-        }
292
-        /** @type EE_Payment_Processor $payment_processor */
293
-        $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
294
-        // set revisit flag for payment processor
295
-        $payment_processor->set_revisit();
296
-        // load EEM_Transaction
297
-        EE_Registry::instance()->load_model('Transaction');
298
-        foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
299
-            // reschedule the cron if we can't hit the db right now
300
-            if (! EE_Maintenance_Mode::instance()->models_can_query()) {
301
-                // reset cron job for updating the TXN
302
-                EE_Cron_Tasks::schedule_update_transaction_with_payment(
303
-                    time() + EE_Cron_Tasks::reschedule_timeout,
304
-                    $TXN_ID,
305
-                    $PAY_ID
306
-                );
307
-                continue;
308
-            }
309
-            $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
310
-            $payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
311
-            // verify transaction
312
-            if ($transaction instanceof EE_Transaction && $payment instanceof EE_Payment) {
313
-                // now try to update the TXN with any payments
314
-                $payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
315
-            }
316
-            unset(self::$_update_transactions_with_payment[ $TXN_ID ]);
317
-        }
318
-    }
319
-
320
-
321
-
322
-    /************  END OF UPDATE TRANSACTION WITH PAYMENT  ************/
323
-
324
-
325
-    /*****************  EXPIRED TRANSACTION CHECK *****************/
326
-
327
-
328
-    /**
329
-     * array of TXN IDs
330
-     *
331
-     * @var array
332
-     */
333
-    protected static $_expired_transactions = array();
334
-
335
-
336
-    /**
337
-     * schedule_expired_transaction_check
338
-     * sets a wp_schedule_single_event() for following up on TXNs after their session has expired
339
-     *
340
-     * @param int $timestamp
341
-     * @param int $TXN_ID
342
-     */
343
-    public static function schedule_expired_transaction_check(
344
-        $timestamp,
345
-        $TXN_ID
346
-    ) {
347
-        // validate $TXN_ID and $timestamp
348
-        $TXN_ID = absint($TXN_ID);
349
-        $timestamp = absint($timestamp);
350
-        if ($TXN_ID && $timestamp) {
351
-            wp_schedule_single_event(
352
-                $timestamp,
353
-                'AHEE__EE_Cron_Tasks__expired_transaction_check',
354
-                array($TXN_ID)
355
-            );
356
-        }
357
-    }
358
-
359
-
360
-    /**
361
-     * expired_transaction_check
362
-     * this is the callback for the action hook:
363
-     * 'AHEE__EE_Cron_Tasks__transaction_session_expiration_check'
364
-     * which is utilized by wp_schedule_single_event()
365
-     * in \EED_Single_Page_Checkout::_initialize_transaction().
366
-     * The passed TXN_ID gets added to an array, and then the
367
-     * process_expired_transactions() function is hooked into
368
-     * 'AHEE__EE_System__core_loaded_and_ready' which will actually handle the
369
-     * processing of any failed transactions, because doing so now would be
370
-     * too early and the required resources may not be available
371
-     *
372
-     * @param int $TXN_ID
373
-     */
374
-    public static function expired_transaction_check($TXN_ID = 0)
375
-    {
376
-        if (absint($TXN_ID)) {
377
-            self::$_expired_transactions[ $TXN_ID ] = $TXN_ID;
378
-            add_action(
379
-                'shutdown',
380
-                array('EE_Cron_Tasks', 'process_expired_transactions'),
381
-                5
382
-            );
383
-        }
384
-    }
385
-
386
-
387
-    /**
388
-     * process_expired_transactions
389
-     * loops through the self::$_expired_transactions array and processes any failed TXNs
390
-     *
391
-     * @throws EE_Error
392
-     * @throws InvalidDataTypeException
393
-     * @throws InvalidInterfaceException
394
-     * @throws InvalidArgumentException
395
-     * @throws ReflectionException
396
-     * @throws DomainException
397
-     * @throws RuntimeException
398
-     */
399
-    public static function process_expired_transactions()
400
-    {
401
-        if (
283
+			empty(self::$_update_transactions_with_payment)
284
+			// reschedule the cron if we can't hit the db right now
285
+			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
286
+				'schedule_update_transaction_with_payment',
287
+				self::$_update_transactions_with_payment
288
+			)
289
+		) {
290
+			return;
291
+		}
292
+		/** @type EE_Payment_Processor $payment_processor */
293
+		$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
294
+		// set revisit flag for payment processor
295
+		$payment_processor->set_revisit();
296
+		// load EEM_Transaction
297
+		EE_Registry::instance()->load_model('Transaction');
298
+		foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
299
+			// reschedule the cron if we can't hit the db right now
300
+			if (! EE_Maintenance_Mode::instance()->models_can_query()) {
301
+				// reset cron job for updating the TXN
302
+				EE_Cron_Tasks::schedule_update_transaction_with_payment(
303
+					time() + EE_Cron_Tasks::reschedule_timeout,
304
+					$TXN_ID,
305
+					$PAY_ID
306
+				);
307
+				continue;
308
+			}
309
+			$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
310
+			$payment = EEM_Payment::instance()->get_one_by_ID($PAY_ID);
311
+			// verify transaction
312
+			if ($transaction instanceof EE_Transaction && $payment instanceof EE_Payment) {
313
+				// now try to update the TXN with any payments
314
+				$payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
315
+			}
316
+			unset(self::$_update_transactions_with_payment[ $TXN_ID ]);
317
+		}
318
+	}
319
+
320
+
321
+
322
+	/************  END OF UPDATE TRANSACTION WITH PAYMENT  ************/
323
+
324
+
325
+	/*****************  EXPIRED TRANSACTION CHECK *****************/
326
+
327
+
328
+	/**
329
+	 * array of TXN IDs
330
+	 *
331
+	 * @var array
332
+	 */
333
+	protected static $_expired_transactions = array();
334
+
335
+
336
+	/**
337
+	 * schedule_expired_transaction_check
338
+	 * sets a wp_schedule_single_event() for following up on TXNs after their session has expired
339
+	 *
340
+	 * @param int $timestamp
341
+	 * @param int $TXN_ID
342
+	 */
343
+	public static function schedule_expired_transaction_check(
344
+		$timestamp,
345
+		$TXN_ID
346
+	) {
347
+		// validate $TXN_ID and $timestamp
348
+		$TXN_ID = absint($TXN_ID);
349
+		$timestamp = absint($timestamp);
350
+		if ($TXN_ID && $timestamp) {
351
+			wp_schedule_single_event(
352
+				$timestamp,
353
+				'AHEE__EE_Cron_Tasks__expired_transaction_check',
354
+				array($TXN_ID)
355
+			);
356
+		}
357
+	}
358
+
359
+
360
+	/**
361
+	 * expired_transaction_check
362
+	 * this is the callback for the action hook:
363
+	 * 'AHEE__EE_Cron_Tasks__transaction_session_expiration_check'
364
+	 * which is utilized by wp_schedule_single_event()
365
+	 * in \EED_Single_Page_Checkout::_initialize_transaction().
366
+	 * The passed TXN_ID gets added to an array, and then the
367
+	 * process_expired_transactions() function is hooked into
368
+	 * 'AHEE__EE_System__core_loaded_and_ready' which will actually handle the
369
+	 * processing of any failed transactions, because doing so now would be
370
+	 * too early and the required resources may not be available
371
+	 *
372
+	 * @param int $TXN_ID
373
+	 */
374
+	public static function expired_transaction_check($TXN_ID = 0)
375
+	{
376
+		if (absint($TXN_ID)) {
377
+			self::$_expired_transactions[ $TXN_ID ] = $TXN_ID;
378
+			add_action(
379
+				'shutdown',
380
+				array('EE_Cron_Tasks', 'process_expired_transactions'),
381
+				5
382
+			);
383
+		}
384
+	}
385
+
386
+
387
+	/**
388
+	 * process_expired_transactions
389
+	 * loops through the self::$_expired_transactions array and processes any failed TXNs
390
+	 *
391
+	 * @throws EE_Error
392
+	 * @throws InvalidDataTypeException
393
+	 * @throws InvalidInterfaceException
394
+	 * @throws InvalidArgumentException
395
+	 * @throws ReflectionException
396
+	 * @throws DomainException
397
+	 * @throws RuntimeException
398
+	 */
399
+	public static function process_expired_transactions()
400
+	{
401
+		if (
402 402
 // are there any TXNs that need cleaning up ?
403
-            empty(self::$_expired_transactions)
404
-            // reschedule the cron if we can't hit the db right now
405
-            || EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
406
-                'schedule_expired_transaction_check',
407
-                self::$_expired_transactions
408
-            )
409
-        ) {
410
-            return;
411
-        }
412
-        /** @type EE_Transaction_Processor $transaction_processor */
413
-        $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
414
-        // set revisit flag for txn processor
415
-        $transaction_processor->set_revisit();
416
-        // load EEM_Transaction
417
-        EE_Registry::instance()->load_model('Transaction');
418
-        foreach (self::$_expired_transactions as $TXN_ID) {
419
-            $transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
420
-            // verify transaction and whether it is failed or not
421
-            if ($transaction instanceof EE_Transaction) {
422
-                switch ($transaction->status_ID()) {
423
-                    // Completed TXNs
424
-                    case EEM_Transaction::complete_status_code:
425
-                        // Don't update the transaction/registrations if the Primary Registration is Not Approved.
426
-                        $primary_registration = $transaction->primary_registration();
427
-                        if (
428
-                            $primary_registration instanceof EE_Registration
429
-                            && $primary_registration->status_ID() !== EEM_Registration::status_id_not_approved
430
-                        ) {
431
-                            /** @type EE_Transaction_Processor $transaction_processor */
432
-                            $transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
433
-                            $transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
434
-                                $transaction,
435
-                                $transaction->last_payment()
436
-                            );
437
-                            do_action(
438
-                                'AHEE__EE_Cron_Tasks__process_expired_transactions__completed_transaction',
439
-                                $transaction
440
-                            );
441
-                        }
442
-                        break;
443
-                    // Overpaid TXNs
444
-                    case EEM_Transaction::overpaid_status_code:
445
-                        do_action(
446
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__overpaid_transaction',
447
-                            $transaction
448
-                        );
449
-                        break;
450
-                    // Incomplete TXNs
451
-                    case EEM_Transaction::incomplete_status_code:
452
-                        do_action(
453
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction',
454
-                            $transaction
455
-                        );
456
-                        // todo : move business logic into EE_Transaction_Processor for finalizing abandoned transactions
457
-                        break;
458
-                    // Abandoned TXNs
459
-                    case EEM_Transaction::abandoned_status_code:
460
-                        // run hook before updating transaction, primarily so
461
-                        // EED_Ticket_Sales_Monitor::process_abandoned_transactions() can release reserved tickets
462
-                        do_action(
463
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__abandoned_transaction',
464
-                            $transaction
465
-                        );
466
-                        // don't finalize the TXN if it has already been completed
467
-                        if ($transaction->all_reg_steps_completed() !== true) {
468
-                            /** @type EE_Payment_Processor $payment_processor */
469
-                            $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
470
-                            // let's simulate an IPN here which will trigger any notifications that need to go out
471
-                            $payment_processor->update_txn_based_on_payment(
472
-                                $transaction,
473
-                                $transaction->last_payment(),
474
-                                true,
475
-                                true
476
-                            );
477
-                        }
478
-                        break;
479
-                    // Failed TXNs
480
-                    case EEM_Transaction::failed_status_code:
481
-                        do_action(
482
-                            'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction',
483
-                            $transaction
484
-                        );
485
-                        // todo :
486
-                        // perform garbage collection here and remove clean_out_junk_transactions()
487
-                        // $registrations = $transaction->registrations();
488
-                        // if (! empty($registrations)) {
489
-                        //     foreach ($registrations as $registration) {
490
-                        //         if ($registration instanceof EE_Registration) {
491
-                        //             $delete_registration = true;
492
-                        //             if ($registration->attendee() instanceof EE_Attendee) {
493
-                        //                 $delete_registration = false;
494
-                        //             }
495
-                        //             if ($delete_registration) {
496
-                        //                 $registration->delete_permanently();
497
-                        //                 $registration->delete_related_permanently();
498
-                        //             }
499
-                        //         }
500
-                        //     }
501
-                        // }
502
-                        break;
503
-                }
504
-            }
505
-            unset(self::$_expired_transactions[ $TXN_ID ]);
506
-        }
507
-    }
508
-
509
-
510
-
511
-    /*************  END OF EXPIRED TRANSACTION CHECK  *************/
512
-
513
-
514
-    /************* START CLEAN UP BOT TRANSACTIONS **********************/
515
-
516
-
517
-    /**
518
-     * callback for 'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'
519
-     * which is setup during activation to run on an hourly cron
520
-     *
521
-     * @throws EE_Error
522
-     * @throws InvalidArgumentException
523
-     * @throws InvalidDataTypeException
524
-     * @throws InvalidInterfaceException
525
-     * @throws DomainException
526
-     */
527
-    public static function clean_out_junk_transactions()
528
-    {
529
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
530
-            EED_Ticket_Sales_Monitor::reset_reservation_counts();
531
-            EEM_Transaction::instance('')->delete_junk_transactions();
532
-            EEM_Registration::instance('')->delete_registrations_with_no_transaction();
533
-            EEM_Line_Item::instance('')->delete_line_items_with_no_transaction();
534
-        }
535
-    }
536
-
537
-
538
-    /**
539
-     * Deletes old gateway logs. After about a week we usually don't need them for debugging. But folks can filter that.
540
-     *
541
-     * @throws EE_Error
542
-     * @throws InvalidDataTypeException
543
-     * @throws InvalidInterfaceException
544
-     * @throws InvalidArgumentException
545
-     */
546
-    public static function clean_out_old_gateway_logs()
547
-    {
548
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
549
-            $reg_config = LoaderFactory::getLoader()->load('EE_Registration_Config');
550
-            $time_diff_for_comparison = apply_filters(
551
-                'FHEE__EE_Cron_Tasks__clean_out_old_gateway_logs__time_diff_for_comparison',
552
-                '-' . $reg_config->gateway_log_lifespan
553
-            );
554
-            EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime($time_diff_for_comparison));
555
-        }
556
-    }
557
-
558
-
559
-    /*****************  FINALIZE ABANDONED TRANSACTIONS *****************/
560
-
561
-
562
-    /**
563
-     * @var array
564
-     */
565
-    protected static $_abandoned_transactions = array();
566
-
567
-
568
-    /**
569
-     * @deprecated
570
-     * @param int $timestamp
571
-     * @param int $TXN_ID
572
-     */
573
-    public static function schedule_finalize_abandoned_transactions_check($timestamp, $TXN_ID)
574
-    {
575
-        EE_Cron_Tasks::schedule_expired_transaction_check($timestamp, $TXN_ID);
576
-    }
577
-
578
-
579
-    /**
580
-     * @deprecated
581
-     * @param int $TXN_ID
582
-     */
583
-    public static function check_for_abandoned_transactions($TXN_ID = 0)
584
-    {
585
-        EE_Cron_Tasks::expired_transaction_check($TXN_ID);
586
-    }
587
-
588
-
589
-    /**
590
-     * @deprecated
591
-     * @throws EE_Error
592
-     * @throws DomainException
593
-     * @throws InvalidDataTypeException
594
-     * @throws InvalidInterfaceException
595
-     * @throws InvalidArgumentException
596
-     * @throws ReflectionException
597
-     * @throws RuntimeException
598
-     */
599
-    public static function finalize_abandoned_transactions()
600
-    {
601
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
602
-        if (
403
+			empty(self::$_expired_transactions)
404
+			// reschedule the cron if we can't hit the db right now
405
+			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
406
+				'schedule_expired_transaction_check',
407
+				self::$_expired_transactions
408
+			)
409
+		) {
410
+			return;
411
+		}
412
+		/** @type EE_Transaction_Processor $transaction_processor */
413
+		$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
414
+		// set revisit flag for txn processor
415
+		$transaction_processor->set_revisit();
416
+		// load EEM_Transaction
417
+		EE_Registry::instance()->load_model('Transaction');
418
+		foreach (self::$_expired_transactions as $TXN_ID) {
419
+			$transaction = EEM_Transaction::instance()->get_one_by_ID($TXN_ID);
420
+			// verify transaction and whether it is failed or not
421
+			if ($transaction instanceof EE_Transaction) {
422
+				switch ($transaction->status_ID()) {
423
+					// Completed TXNs
424
+					case EEM_Transaction::complete_status_code:
425
+						// Don't update the transaction/registrations if the Primary Registration is Not Approved.
426
+						$primary_registration = $transaction->primary_registration();
427
+						if (
428
+							$primary_registration instanceof EE_Registration
429
+							&& $primary_registration->status_ID() !== EEM_Registration::status_id_not_approved
430
+						) {
431
+							/** @type EE_Transaction_Processor $transaction_processor */
432
+							$transaction_processor = EE_Registry::instance()->load_class('Transaction_Processor');
433
+							$transaction_processor->update_transaction_and_registrations_after_checkout_or_payment(
434
+								$transaction,
435
+								$transaction->last_payment()
436
+							);
437
+							do_action(
438
+								'AHEE__EE_Cron_Tasks__process_expired_transactions__completed_transaction',
439
+								$transaction
440
+							);
441
+						}
442
+						break;
443
+					// Overpaid TXNs
444
+					case EEM_Transaction::overpaid_status_code:
445
+						do_action(
446
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__overpaid_transaction',
447
+							$transaction
448
+						);
449
+						break;
450
+					// Incomplete TXNs
451
+					case EEM_Transaction::incomplete_status_code:
452
+						do_action(
453
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__incomplete_transaction',
454
+							$transaction
455
+						);
456
+						// todo : move business logic into EE_Transaction_Processor for finalizing abandoned transactions
457
+						break;
458
+					// Abandoned TXNs
459
+					case EEM_Transaction::abandoned_status_code:
460
+						// run hook before updating transaction, primarily so
461
+						// EED_Ticket_Sales_Monitor::process_abandoned_transactions() can release reserved tickets
462
+						do_action(
463
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__abandoned_transaction',
464
+							$transaction
465
+						);
466
+						// don't finalize the TXN if it has already been completed
467
+						if ($transaction->all_reg_steps_completed() !== true) {
468
+							/** @type EE_Payment_Processor $payment_processor */
469
+							$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
470
+							// let's simulate an IPN here which will trigger any notifications that need to go out
471
+							$payment_processor->update_txn_based_on_payment(
472
+								$transaction,
473
+								$transaction->last_payment(),
474
+								true,
475
+								true
476
+							);
477
+						}
478
+						break;
479
+					// Failed TXNs
480
+					case EEM_Transaction::failed_status_code:
481
+						do_action(
482
+							'AHEE__EE_Cron_Tasks__process_expired_transactions__failed_transaction',
483
+							$transaction
484
+						);
485
+						// todo :
486
+						// perform garbage collection here and remove clean_out_junk_transactions()
487
+						// $registrations = $transaction->registrations();
488
+						// if (! empty($registrations)) {
489
+						//     foreach ($registrations as $registration) {
490
+						//         if ($registration instanceof EE_Registration) {
491
+						//             $delete_registration = true;
492
+						//             if ($registration->attendee() instanceof EE_Attendee) {
493
+						//                 $delete_registration = false;
494
+						//             }
495
+						//             if ($delete_registration) {
496
+						//                 $registration->delete_permanently();
497
+						//                 $registration->delete_related_permanently();
498
+						//             }
499
+						//         }
500
+						//     }
501
+						// }
502
+						break;
503
+				}
504
+			}
505
+			unset(self::$_expired_transactions[ $TXN_ID ]);
506
+		}
507
+	}
508
+
509
+
510
+
511
+	/*************  END OF EXPIRED TRANSACTION CHECK  *************/
512
+
513
+
514
+	/************* START CLEAN UP BOT TRANSACTIONS **********************/
515
+
516
+
517
+	/**
518
+	 * callback for 'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'
519
+	 * which is setup during activation to run on an hourly cron
520
+	 *
521
+	 * @throws EE_Error
522
+	 * @throws InvalidArgumentException
523
+	 * @throws InvalidDataTypeException
524
+	 * @throws InvalidInterfaceException
525
+	 * @throws DomainException
526
+	 */
527
+	public static function clean_out_junk_transactions()
528
+	{
529
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
530
+			EED_Ticket_Sales_Monitor::reset_reservation_counts();
531
+			EEM_Transaction::instance('')->delete_junk_transactions();
532
+			EEM_Registration::instance('')->delete_registrations_with_no_transaction();
533
+			EEM_Line_Item::instance('')->delete_line_items_with_no_transaction();
534
+		}
535
+	}
536
+
537
+
538
+	/**
539
+	 * Deletes old gateway logs. After about a week we usually don't need them for debugging. But folks can filter that.
540
+	 *
541
+	 * @throws EE_Error
542
+	 * @throws InvalidDataTypeException
543
+	 * @throws InvalidInterfaceException
544
+	 * @throws InvalidArgumentException
545
+	 */
546
+	public static function clean_out_old_gateway_logs()
547
+	{
548
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
549
+			$reg_config = LoaderFactory::getLoader()->load('EE_Registration_Config');
550
+			$time_diff_for_comparison = apply_filters(
551
+				'FHEE__EE_Cron_Tasks__clean_out_old_gateway_logs__time_diff_for_comparison',
552
+				'-' . $reg_config->gateway_log_lifespan
553
+			);
554
+			EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime($time_diff_for_comparison));
555
+		}
556
+	}
557
+
558
+
559
+	/*****************  FINALIZE ABANDONED TRANSACTIONS *****************/
560
+
561
+
562
+	/**
563
+	 * @var array
564
+	 */
565
+	protected static $_abandoned_transactions = array();
566
+
567
+
568
+	/**
569
+	 * @deprecated
570
+	 * @param int $timestamp
571
+	 * @param int $TXN_ID
572
+	 */
573
+	public static function schedule_finalize_abandoned_transactions_check($timestamp, $TXN_ID)
574
+	{
575
+		EE_Cron_Tasks::schedule_expired_transaction_check($timestamp, $TXN_ID);
576
+	}
577
+
578
+
579
+	/**
580
+	 * @deprecated
581
+	 * @param int $TXN_ID
582
+	 */
583
+	public static function check_for_abandoned_transactions($TXN_ID = 0)
584
+	{
585
+		EE_Cron_Tasks::expired_transaction_check($TXN_ID);
586
+	}
587
+
588
+
589
+	/**
590
+	 * @deprecated
591
+	 * @throws EE_Error
592
+	 * @throws DomainException
593
+	 * @throws InvalidDataTypeException
594
+	 * @throws InvalidInterfaceException
595
+	 * @throws InvalidArgumentException
596
+	 * @throws ReflectionException
597
+	 * @throws RuntimeException
598
+	 */
599
+	public static function finalize_abandoned_transactions()
600
+	{
601
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
602
+		if (
603 603
 // are there any TXNs that need cleaning up ?
604
-            empty(self::$_abandoned_transactions)
605
-            // reschedule the cron if we can't hit the db right now
606
-            || EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
607
-                'schedule_expired_transaction_check',
608
-                self::$_abandoned_transactions
609
-            )
610
-        ) {
611
-            return;
612
-        }
613
-        // combine our arrays of transaction IDs
614
-        self::$_expired_transactions = self::$_abandoned_transactions + self::$_expired_transactions;
615
-        // and deal with abandoned transactions here now...
616
-        EE_Cron_Tasks::process_expired_transactions();
617
-    }
618
-
619
-
620
-    /*************  END OF FINALIZE ABANDONED TRANSACTIONS  *************/
604
+			empty(self::$_abandoned_transactions)
605
+			// reschedule the cron if we can't hit the db right now
606
+			|| EE_Cron_Tasks::reschedule_cron_for_transactions_if_maintenance_mode(
607
+				'schedule_expired_transaction_check',
608
+				self::$_abandoned_transactions
609
+			)
610
+		) {
611
+			return;
612
+		}
613
+		// combine our arrays of transaction IDs
614
+		self::$_expired_transactions = self::$_abandoned_transactions + self::$_expired_transactions;
615
+		// and deal with abandoned transactions here now...
616
+		EE_Cron_Tasks::process_expired_transactions();
617
+	}
618
+
619
+
620
+	/*************  END OF FINALIZE ABANDONED TRANSACTIONS  *************/
621 621
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
      */
39 39
     public static function instance()
40 40
     {
41
-        if (! self::$_instance instanceof EE_Cron_Tasks) {
41
+        if ( ! self::$_instance instanceof EE_Cron_Tasks) {
42 42
             self::$_instance = new self();
43 43
         }
44 44
         return self::$_instance;
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
              */
73 73
             add_action(
74 74
                 'AHEE__EE_System__load_core_configuration__complete',
75
-                function () {
75
+                function() {
76 76
                     EE_Registry::instance()->NET_CFG->core->do_messages_on_same_request = true;
77 77
                     EE_Registry::instance()->NET_CFG->update_config(true, false);
78 78
                     add_option('ee_disabled_wp_cron_check', 1, '', false);
@@ -124,16 +124,16 @@  discard block
 block discarded – undo
124 124
             'AHEE__EE_Cron_Tasks__clean_up_junk_transactions',
125 125
         );
126 126
         $crons = (array) get_option('cron');
127
-        if (! is_array($crons)) {
127
+        if ( ! is_array($crons)) {
128 128
             return;
129 129
         }
130 130
         foreach ($crons as $timestamp => $cron) {
131 131
             /** @var array[] $cron */
132 132
             foreach ($ee_crons as $ee_cron) {
133
-                if (isset($cron[ $ee_cron ]) && is_array($cron[ $ee_cron ])) {
133
+                if (isset($cron[$ee_cron]) && is_array($cron[$ee_cron])) {
134 134
                     do_action('AHEE_log', __CLASS__, __FUNCTION__, $ee_cron, 'scheduled EE cron');
135
-                    foreach ($cron[ $ee_cron ] as $ee_cron_details) {
136
-                        if (! empty($ee_cron_details['args'])) {
135
+                    foreach ($cron[$ee_cron] as $ee_cron_details) {
136
+                        if ( ! empty($ee_cron_details['args'])) {
137 137
                             do_action(
138 138
                                 'AHEE_log',
139 139
                                 __CLASS__,
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
      */
161 161
     public static function reschedule_cron_for_transactions_if_maintenance_mode($cron_task, array $TXN_IDs)
162 162
     {
163
-        if (! method_exists('EE_Cron_Tasks', $cron_task)) {
163
+        if ( ! method_exists('EE_Cron_Tasks', $cron_task)) {
164 164
             throw new DomainException(
165 165
                 sprintf(
166 166
                     esc_html__('"%1$s" is not valid method on EE_Cron_Tasks.', 'event_espresso'),
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
             );
170 170
         }
171 171
         // reschedule the cron if we can't hit the db right now
172
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
172
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
173 173
             foreach ($TXN_IDs as $TXN_ID => $additional_vars) {
174 174
                 // ensure $additional_vars is an array
175 175
                 $additional_vars = is_array($additional_vars) ? $additional_vars : array($additional_vars);
@@ -250,7 +250,7 @@  discard block
 block discarded – undo
250 250
     {
251 251
         do_action('AHEE_log', __CLASS__, __FUNCTION__, $TXN_ID, '$TXN_ID');
252 252
         if (absint($TXN_ID)) {
253
-            self::$_update_transactions_with_payment[ $TXN_ID ] = $PAY_ID;
253
+            self::$_update_transactions_with_payment[$TXN_ID] = $PAY_ID;
254 254
             add_action(
255 255
                 'shutdown',
256 256
                 array('EE_Cron_Tasks', 'update_transaction_with_payment'),
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
         EE_Registry::instance()->load_model('Transaction');
298 298
         foreach (self::$_update_transactions_with_payment as $TXN_ID => $PAY_ID) {
299 299
             // reschedule the cron if we can't hit the db right now
300
-            if (! EE_Maintenance_Mode::instance()->models_can_query()) {
300
+            if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
301 301
                 // reset cron job for updating the TXN
302 302
                 EE_Cron_Tasks::schedule_update_transaction_with_payment(
303 303
                     time() + EE_Cron_Tasks::reschedule_timeout,
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
                 // now try to update the TXN with any payments
314 314
                 $payment_processor->update_txn_based_on_payment($transaction, $payment, true, true);
315 315
             }
316
-            unset(self::$_update_transactions_with_payment[ $TXN_ID ]);
316
+            unset(self::$_update_transactions_with_payment[$TXN_ID]);
317 317
         }
318 318
     }
319 319
 
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
     public static function expired_transaction_check($TXN_ID = 0)
375 375
     {
376 376
         if (absint($TXN_ID)) {
377
-            self::$_expired_transactions[ $TXN_ID ] = $TXN_ID;
377
+            self::$_expired_transactions[$TXN_ID] = $TXN_ID;
378 378
             add_action(
379 379
                 'shutdown',
380 380
                 array('EE_Cron_Tasks', 'process_expired_transactions'),
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
                         break;
503 503
                 }
504 504
             }
505
-            unset(self::$_expired_transactions[ $TXN_ID ]);
505
+            unset(self::$_expired_transactions[$TXN_ID]);
506 506
         }
507 507
     }
508 508
 
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
             $reg_config = LoaderFactory::getLoader()->load('EE_Registration_Config');
550 550
             $time_diff_for_comparison = apply_filters(
551 551
                 'FHEE__EE_Cron_Tasks__clean_out_old_gateway_logs__time_diff_for_comparison',
552
-                '-' . $reg_config->gateway_log_lifespan
552
+                '-'.$reg_config->gateway_log_lifespan
553 553
             );
554 554
             EEM_Change_Log::instance()->delete_gateway_logs_older_than(new DateTime($time_diff_for_comparison));
555 555
         }
Please login to merge, or discard this patch.
core/helpers/EEH_Address.helper.php 2 patches
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -13,124 +13,124 @@
 block discarded – undo
13 13
 
14 14
 
15 15
 
16
-    /**
17
-     *    format - output formatted EE object address information
18
-     *
19
-     * @access public
20
-     * @param         object      EEI_Address $obj_with_address
21
-     * @param string  $type       how the address is formatted. for example: 'multiline' or 'inline'
22
-     * @param boolean $use_schema whether to apply schema.org formatting to the address
23
-     * @param bool    $add_wrapper
24
-     * @return string
25
-     */
26
-    public static function format(
27
-        $obj_with_address = null,
28
-        $type = 'multiline',
29
-        $use_schema = true,
30
-        $add_wrapper = true
31
-    ) {
32
-        // check that incoming object implements the EEI_Address interface
33
-        if (! $obj_with_address instanceof EEI_Address) {
34
-            $msg = esc_html__('The address could not be formatted.', 'event_espresso');
35
-            $dev_msg = esc_html__(
36
-                'The Address Formatter requires passed objects to implement the EEI_Address interface.',
37
-                'event_espresso'
38
-            );
39
-            EE_Error::add_error($msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
40
-            return null;
41
-        }
42
-        // obtain an address formatter
43
-        $formatter = EEH_Address::_get_formatter($type);
44
-        // apply schema.org formatting ?
45
-        $use_schema = ! is_admin() ? $use_schema : false;
46
-        $formatted_address = $use_schema
47
-            ? EEH_Address::_schema_formatting($formatter, $obj_with_address)
48
-            : EEH_Address::_regular_formatting($formatter, $obj_with_address, $add_wrapper);
49
-        $formatted_address = $add_wrapper && ! $use_schema
50
-            ? '<div class="espresso-address-dv">' . $formatted_address . '</div>'
51
-            : $formatted_address;
52
-        // return the formatted address
53
-        return $formatted_address;
54
-    }
16
+	/**
17
+	 *    format - output formatted EE object address information
18
+	 *
19
+	 * @access public
20
+	 * @param         object      EEI_Address $obj_with_address
21
+	 * @param string  $type       how the address is formatted. for example: 'multiline' or 'inline'
22
+	 * @param boolean $use_schema whether to apply schema.org formatting to the address
23
+	 * @param bool    $add_wrapper
24
+	 * @return string
25
+	 */
26
+	public static function format(
27
+		$obj_with_address = null,
28
+		$type = 'multiline',
29
+		$use_schema = true,
30
+		$add_wrapper = true
31
+	) {
32
+		// check that incoming object implements the EEI_Address interface
33
+		if (! $obj_with_address instanceof EEI_Address) {
34
+			$msg = esc_html__('The address could not be formatted.', 'event_espresso');
35
+			$dev_msg = esc_html__(
36
+				'The Address Formatter requires passed objects to implement the EEI_Address interface.',
37
+				'event_espresso'
38
+			);
39
+			EE_Error::add_error($msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
40
+			return null;
41
+		}
42
+		// obtain an address formatter
43
+		$formatter = EEH_Address::_get_formatter($type);
44
+		// apply schema.org formatting ?
45
+		$use_schema = ! is_admin() ? $use_schema : false;
46
+		$formatted_address = $use_schema
47
+			? EEH_Address::_schema_formatting($formatter, $obj_with_address)
48
+			: EEH_Address::_regular_formatting($formatter, $obj_with_address, $add_wrapper);
49
+		$formatted_address = $add_wrapper && ! $use_schema
50
+			? '<div class="espresso-address-dv">' . $formatted_address . '</div>'
51
+			: $formatted_address;
52
+		// return the formatted address
53
+		return $formatted_address;
54
+	}
55 55
 
56 56
 
57 57
 
58
-    /**
59
-     *    _get_formatter - obtain the requester formatter class
60
-     *
61
-     * @access private
62
-     * @param string $type how the address is formatted. for example: 'multiline' or 'inline'
63
-     * @return EEI_Address_Formatter
64
-     */
65
-    private static function _get_formatter($type)
66
-    {
67
-        switch ($type) {
68
-            case 'multiline':
69
-                return new EventEspresso\core\services\address\formatters\MultiLineAddressFormatter();
70
-            case 'inline':
71
-                return new EventEspresso\core\services\address\formatters\InlineAddressFormatter();
72
-            default:
73
-                return new EventEspresso\core\services\address\formatters\NullAddressFormatter();
74
-        }
75
-    }
58
+	/**
59
+	 *    _get_formatter - obtain the requester formatter class
60
+	 *
61
+	 * @access private
62
+	 * @param string $type how the address is formatted. for example: 'multiline' or 'inline'
63
+	 * @return EEI_Address_Formatter
64
+	 */
65
+	private static function _get_formatter($type)
66
+	{
67
+		switch ($type) {
68
+			case 'multiline':
69
+				return new EventEspresso\core\services\address\formatters\MultiLineAddressFormatter();
70
+			case 'inline':
71
+				return new EventEspresso\core\services\address\formatters\InlineAddressFormatter();
72
+			default:
73
+				return new EventEspresso\core\services\address\formatters\NullAddressFormatter();
74
+		}
75
+	}
76 76
 
77 77
 
78 78
 
79
-    /**
80
-     *    _regular_formatting
81
-     *    adds formatting to an address
82
-     *
83
-     * @access private
84
-     * @param      object EEI_Address_Formatter $formatter
85
-     * @param      object EEI_Address $obj_with_address
86
-     * @param bool $add_wrapper
87
-     * @return string
88
-     */
89
-    private static function _regular_formatting(
90
-        EEI_Address_Formatter $formatter,
91
-        EEI_Address $obj_with_address,
92
-        $add_wrapper = true
93
-    ) {
94
-        $formatted_address = $add_wrapper ? '<div>' : '';
95
-        $formatted_address .= $formatter->format(
96
-            $obj_with_address->address(),
97
-            $obj_with_address->address2(),
98
-            $obj_with_address->city(),
99
-            $obj_with_address->state_name(),
100
-            $obj_with_address->zip(),
101
-            $obj_with_address->country_name(),
102
-            $obj_with_address->country_ID()
103
-        );
104
-        $formatted_address .= $add_wrapper ? '</div>' : '';
105
-        // return the formatted address
106
-        return $formatted_address;
107
-    }
79
+	/**
80
+	 *    _regular_formatting
81
+	 *    adds formatting to an address
82
+	 *
83
+	 * @access private
84
+	 * @param      object EEI_Address_Formatter $formatter
85
+	 * @param      object EEI_Address $obj_with_address
86
+	 * @param bool $add_wrapper
87
+	 * @return string
88
+	 */
89
+	private static function _regular_formatting(
90
+		EEI_Address_Formatter $formatter,
91
+		EEI_Address $obj_with_address,
92
+		$add_wrapper = true
93
+	) {
94
+		$formatted_address = $add_wrapper ? '<div>' : '';
95
+		$formatted_address .= $formatter->format(
96
+			$obj_with_address->address(),
97
+			$obj_with_address->address2(),
98
+			$obj_with_address->city(),
99
+			$obj_with_address->state_name(),
100
+			$obj_with_address->zip(),
101
+			$obj_with_address->country_name(),
102
+			$obj_with_address->country_ID()
103
+		);
104
+		$formatted_address .= $add_wrapper ? '</div>' : '';
105
+		// return the formatted address
106
+		return $formatted_address;
107
+	}
108 108
 
109 109
 
110 110
 
111
-    /**
112
-     *    _schema_formatting
113
-     *    adds schema.org formatting to an address
114
-     *
115
-     * @access private
116
-     * @param object EEI_Address_Formatter $formatter
117
-     * @param object EEI_Address $obj_with_address
118
-     * @return string
119
-     */
120
-    private static function _schema_formatting(EEI_Address_Formatter $formatter, EEI_Address $obj_with_address)
121
-    {
122
-        $formatted_address = '<div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">';
123
-        $formatted_address .= $formatter->format(
124
-            EEH_Schema::streetAddress($obj_with_address),
125
-            EEH_Schema::postOfficeBoxNumber($obj_with_address),
126
-            EEH_Schema::addressLocality($obj_with_address),
127
-            EEH_Schema::addressRegion($obj_with_address),
128
-            EEH_Schema::postalCode($obj_with_address),
129
-            EEH_Schema::addressCountry($obj_with_address),
130
-            $obj_with_address->country_ID()
131
-        );
132
-        $formatted_address .= '</div>';
133
-        // return the formatted address
134
-        return $formatted_address;
135
-    }
111
+	/**
112
+	 *    _schema_formatting
113
+	 *    adds schema.org formatting to an address
114
+	 *
115
+	 * @access private
116
+	 * @param object EEI_Address_Formatter $formatter
117
+	 * @param object EEI_Address $obj_with_address
118
+	 * @return string
119
+	 */
120
+	private static function _schema_formatting(EEI_Address_Formatter $formatter, EEI_Address $obj_with_address)
121
+	{
122
+		$formatted_address = '<div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">';
123
+		$formatted_address .= $formatter->format(
124
+			EEH_Schema::streetAddress($obj_with_address),
125
+			EEH_Schema::postOfficeBoxNumber($obj_with_address),
126
+			EEH_Schema::addressLocality($obj_with_address),
127
+			EEH_Schema::addressRegion($obj_with_address),
128
+			EEH_Schema::postalCode($obj_with_address),
129
+			EEH_Schema::addressCountry($obj_with_address),
130
+			$obj_with_address->country_ID()
131
+		);
132
+		$formatted_address .= '</div>';
133
+		// return the formatted address
134
+		return $formatted_address;
135
+	}
136 136
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -30,13 +30,13 @@  discard block
 block discarded – undo
30 30
         $add_wrapper = true
31 31
     ) {
32 32
         // check that incoming object implements the EEI_Address interface
33
-        if (! $obj_with_address instanceof EEI_Address) {
33
+        if ( ! $obj_with_address instanceof EEI_Address) {
34 34
             $msg = esc_html__('The address could not be formatted.', 'event_espresso');
35 35
             $dev_msg = esc_html__(
36 36
                 'The Address Formatter requires passed objects to implement the EEI_Address interface.',
37 37
                 'event_espresso'
38 38
             );
39
-            EE_Error::add_error($msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
39
+            EE_Error::add_error($msg.'||'.$dev_msg, __FILE__, __FUNCTION__, __LINE__);
40 40
             return null;
41 41
         }
42 42
         // obtain an address formatter
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
             ? EEH_Address::_schema_formatting($formatter, $obj_with_address)
48 48
             : EEH_Address::_regular_formatting($formatter, $obj_with_address, $add_wrapper);
49 49
         $formatted_address = $add_wrapper && ! $use_schema
50
-            ? '<div class="espresso-address-dv">' . $formatted_address . '</div>'
50
+            ? '<div class="espresso-address-dv">'.$formatted_address.'</div>'
51 51
             : $formatted_address;
52 52
         // return the formatted address
53 53
         return $formatted_address;
Please login to merge, or discard this patch.
core/helpers/EEH_DTT_Helper.helper.php 2 patches
Indentation   +983 added lines, -983 removed lines patch added patch discarded remove patch
@@ -17,1045 +17,1045 @@
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     * return the timezone set for the WP install
22
-     *
23
-     * @return string valid timezone string for PHP DateTimeZone() class
24
-     * @throws InvalidArgumentException
25
-     * @throws InvalidDataTypeException
26
-     * @throws InvalidInterfaceException
27
-     */
28
-    public static function get_timezone()
29
-    {
30
-        return EEH_DTT_Helper::get_valid_timezone_string();
31
-    }
20
+	/**
21
+	 * return the timezone set for the WP install
22
+	 *
23
+	 * @return string valid timezone string for PHP DateTimeZone() class
24
+	 * @throws InvalidArgumentException
25
+	 * @throws InvalidDataTypeException
26
+	 * @throws InvalidInterfaceException
27
+	 */
28
+	public static function get_timezone()
29
+	{
30
+		return EEH_DTT_Helper::get_valid_timezone_string();
31
+	}
32 32
 
33 33
 
34
-    /**
35
-     * get_valid_timezone_string
36
-     *    ensures that a valid timezone string is returned
37
-     *
38
-     * @param string $timezone_string
39
-     * @return string
40
-     * @throws InvalidArgumentException
41
-     * @throws InvalidDataTypeException
42
-     * @throws InvalidInterfaceException
43
-     */
44
-    public static function get_valid_timezone_string($timezone_string = '')
45
-    {
46
-        return self::getHelperAdapter()->getValidTimezoneString($timezone_string);
47
-    }
34
+	/**
35
+	 * get_valid_timezone_string
36
+	 *    ensures that a valid timezone string is returned
37
+	 *
38
+	 * @param string $timezone_string
39
+	 * @return string
40
+	 * @throws InvalidArgumentException
41
+	 * @throws InvalidDataTypeException
42
+	 * @throws InvalidInterfaceException
43
+	 */
44
+	public static function get_valid_timezone_string($timezone_string = '')
45
+	{
46
+		return self::getHelperAdapter()->getValidTimezoneString($timezone_string);
47
+	}
48 48
 
49 49
 
50
-    /**
51
-     * This only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
52
-     *
53
-     * @static
54
-     * @param  string $timezone_string Timezone string to check
55
-     * @param bool    $throw_error
56
-     * @return bool
57
-     * @throws InvalidArgumentException
58
-     * @throws InvalidDataTypeException
59
-     * @throws InvalidInterfaceException
60
-     */
61
-    public static function validate_timezone($timezone_string, $throw_error = true)
62
-    {
63
-        return self::getHelperAdapter()->validateTimezone($timezone_string, $throw_error);
64
-    }
50
+	/**
51
+	 * This only purpose for this static method is to validate that the incoming timezone is a valid php timezone.
52
+	 *
53
+	 * @static
54
+	 * @param  string $timezone_string Timezone string to check
55
+	 * @param bool    $throw_error
56
+	 * @return bool
57
+	 * @throws InvalidArgumentException
58
+	 * @throws InvalidDataTypeException
59
+	 * @throws InvalidInterfaceException
60
+	 */
61
+	public static function validate_timezone($timezone_string, $throw_error = true)
62
+	{
63
+		return self::getHelperAdapter()->validateTimezone($timezone_string, $throw_error);
64
+	}
65 65
 
66 66
 
67
-    /**
68
-     * This returns a string that can represent the provided gmt offset in format that can be passed into
69
-     * DateTimeZone.  This is NOT a string that can be passed as a value on the WordPress timezone_string option.
70
-     *
71
-     * @param float|string $gmt_offset
72
-     * @return string
73
-     * @throws InvalidArgumentException
74
-     * @throws InvalidDataTypeException
75
-     * @throws InvalidInterfaceException
76
-     */
77
-    public static function get_timezone_string_from_gmt_offset($gmt_offset = '')
78
-    {
79
-        return self::getHelperAdapter()->getTimezoneStringFromGmtOffset($gmt_offset);
80
-    }
67
+	/**
68
+	 * This returns a string that can represent the provided gmt offset in format that can be passed into
69
+	 * DateTimeZone.  This is NOT a string that can be passed as a value on the WordPress timezone_string option.
70
+	 *
71
+	 * @param float|string $gmt_offset
72
+	 * @return string
73
+	 * @throws InvalidArgumentException
74
+	 * @throws InvalidDataTypeException
75
+	 * @throws InvalidInterfaceException
76
+	 */
77
+	public static function get_timezone_string_from_gmt_offset($gmt_offset = '')
78
+	{
79
+		return self::getHelperAdapter()->getTimezoneStringFromGmtOffset($gmt_offset);
80
+	}
81 81
 
82 82
 
83
-    /**
84
-     * Gets the site's GMT offset based on either the timezone string
85
-     * (in which case teh gmt offset will vary depending on the location's
86
-     * observance of daylight savings time) or the gmt_offset wp option
87
-     *
88
-     * @return int seconds offset
89
-     * @throws InvalidArgumentException
90
-     * @throws InvalidDataTypeException
91
-     * @throws InvalidInterfaceException
92
-     */
93
-    public static function get_site_timezone_gmt_offset()
94
-    {
95
-        return self::getHelperAdapter()->getSiteTimezoneGmtOffset();
96
-    }
83
+	/**
84
+	 * Gets the site's GMT offset based on either the timezone string
85
+	 * (in which case teh gmt offset will vary depending on the location's
86
+	 * observance of daylight savings time) or the gmt_offset wp option
87
+	 *
88
+	 * @return int seconds offset
89
+	 * @throws InvalidArgumentException
90
+	 * @throws InvalidDataTypeException
91
+	 * @throws InvalidInterfaceException
92
+	 */
93
+	public static function get_site_timezone_gmt_offset()
94
+	{
95
+		return self::getHelperAdapter()->getSiteTimezoneGmtOffset();
96
+	}
97 97
 
98 98
 
99
-    /**
100
-     * Depending on PHP version,
101
-     * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
-     * To get around that, for these fringe timezones we bump them to a known valid offset.
103
-     * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
-     *
105
-     * @deprecated 4.9.54.rc    Developers this was always meant to only be an internally used method.  This will be
106
-     *                          removed in a future version of EE.
107
-     * @param int $gmt_offset
108
-     * @return int
109
-     * @throws InvalidArgumentException
110
-     * @throws InvalidDataTypeException
111
-     * @throws InvalidInterfaceException
112
-     */
113
-    public static function adjust_invalid_gmt_offsets($gmt_offset = 0)
114
-    {
115
-        return self::getHelperAdapter()->adjustInvalidGmtOffsets($gmt_offset);
116
-    }
99
+	/**
100
+	 * Depending on PHP version,
101
+	 * there might not be valid current timezone strings to match these gmt_offsets in its timezone tables.
102
+	 * To get around that, for these fringe timezones we bump them to a known valid offset.
103
+	 * This method should ONLY be called after first verifying an timezone_string cannot be retrieved for the offset.
104
+	 *
105
+	 * @deprecated 4.9.54.rc    Developers this was always meant to only be an internally used method.  This will be
106
+	 *                          removed in a future version of EE.
107
+	 * @param int $gmt_offset
108
+	 * @return int
109
+	 * @throws InvalidArgumentException
110
+	 * @throws InvalidDataTypeException
111
+	 * @throws InvalidInterfaceException
112
+	 */
113
+	public static function adjust_invalid_gmt_offsets($gmt_offset = 0)
114
+	{
115
+		return self::getHelperAdapter()->adjustInvalidGmtOffsets($gmt_offset);
116
+	}
117 117
 
118 118
 
119
-    /**
120
-     * get_timezone_string_from_abbreviations_list
121
-     *
122
-     * @deprecated 4.9.54.rc  Developers, this was never intended to be public.  This is a soft deprecation for now.
123
-     *                        If you are using this, you'll want to work out an alternate way of getting the value.
124
-     * @param int  $gmt_offset
125
-     * @param bool $coerce If true, we attempt to coerce with our adjustment table @see self::adjust_invalid_gmt_offset.
126
-     * @return string
127
-     * @throws EE_Error
128
-     * @throws InvalidArgumentException
129
-     * @throws InvalidDataTypeException
130
-     * @throws InvalidInterfaceException
131
-     */
132
-    public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133
-    {
134
-        $gmt_offset =  (int) $gmt_offset;
135
-        /** @var array[] $abbreviations */
136
-        $abbreviations = DateTimeZone::listAbbreviations();
137
-        foreach ($abbreviations as $abbreviation) {
138
-            foreach ($abbreviation as $timezone) {
139
-                if ((int) $timezone['offset'] === $gmt_offset && (bool) $timezone['dst'] === false) {
140
-                    try {
141
-                        $offset = self::get_timezone_offset(new DateTimeZone($timezone['timezone_id']));
142
-                        if ($offset !== $gmt_offset) {
143
-                            continue;
144
-                        }
145
-                        return $timezone['timezone_id'];
146
-                    } catch (Exception $e) {
147
-                        continue;
148
-                    }
149
-                }
150
-            }
151
-        }
152
-        // if $coerce is true, let's see if we can get a timezone string after the offset is adjusted
153
-        if ($coerce === true) {
154
-            $timezone_string = self::get_timezone_string_from_abbreviations_list(
155
-                self::adjust_invalid_gmt_offsets($gmt_offset),
156
-                false
157
-            );
158
-            if ($timezone_string) {
159
-                return $timezone_string;
160
-            }
161
-        }
162
-        throw new EE_Error(
163
-            sprintf(
164
-                esc_html__(
165
-                    'The provided GMT offset (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
166
-                    'event_espresso'
167
-                ),
168
-                $gmt_offset / HOUR_IN_SECONDS,
169
-                '<a href="http://www.php.net/manual/en/timezones.php">',
170
-                '</a>'
171
-            )
172
-        );
173
-    }
119
+	/**
120
+	 * get_timezone_string_from_abbreviations_list
121
+	 *
122
+	 * @deprecated 4.9.54.rc  Developers, this was never intended to be public.  This is a soft deprecation for now.
123
+	 *                        If you are using this, you'll want to work out an alternate way of getting the value.
124
+	 * @param int  $gmt_offset
125
+	 * @param bool $coerce If true, we attempt to coerce with our adjustment table @see self::adjust_invalid_gmt_offset.
126
+	 * @return string
127
+	 * @throws EE_Error
128
+	 * @throws InvalidArgumentException
129
+	 * @throws InvalidDataTypeException
130
+	 * @throws InvalidInterfaceException
131
+	 */
132
+	public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133
+	{
134
+		$gmt_offset =  (int) $gmt_offset;
135
+		/** @var array[] $abbreviations */
136
+		$abbreviations = DateTimeZone::listAbbreviations();
137
+		foreach ($abbreviations as $abbreviation) {
138
+			foreach ($abbreviation as $timezone) {
139
+				if ((int) $timezone['offset'] === $gmt_offset && (bool) $timezone['dst'] === false) {
140
+					try {
141
+						$offset = self::get_timezone_offset(new DateTimeZone($timezone['timezone_id']));
142
+						if ($offset !== $gmt_offset) {
143
+							continue;
144
+						}
145
+						return $timezone['timezone_id'];
146
+					} catch (Exception $e) {
147
+						continue;
148
+					}
149
+				}
150
+			}
151
+		}
152
+		// if $coerce is true, let's see if we can get a timezone string after the offset is adjusted
153
+		if ($coerce === true) {
154
+			$timezone_string = self::get_timezone_string_from_abbreviations_list(
155
+				self::adjust_invalid_gmt_offsets($gmt_offset),
156
+				false
157
+			);
158
+			if ($timezone_string) {
159
+				return $timezone_string;
160
+			}
161
+		}
162
+		throw new EE_Error(
163
+			sprintf(
164
+				esc_html__(
165
+					'The provided GMT offset (%1$s), is invalid, please check with %2$sthis list%3$s for what valid timezones can be used',
166
+					'event_espresso'
167
+				),
168
+				$gmt_offset / HOUR_IN_SECONDS,
169
+				'<a href="http://www.php.net/manual/en/timezones.php">',
170
+				'</a>'
171
+			)
172
+		);
173
+	}
174 174
 
175 175
 
176
-    /**
177
-     * Get Timezone Transitions
178
-     *
179
-     * @param DateTimeZone $date_time_zone
180
-     * @param int|null     $time
181
-     * @param bool         $first_only
182
-     * @return array
183
-     * @throws InvalidArgumentException
184
-     * @throws InvalidDataTypeException
185
-     * @throws InvalidInterfaceException
186
-     */
187
-    public static function get_timezone_transitions(DateTimeZone $date_time_zone, $time = null, $first_only = true)
188
-    {
189
-        return self::getHelperAdapter()->getTimezoneTransitions($date_time_zone, $time, $first_only);
190
-    }
176
+	/**
177
+	 * Get Timezone Transitions
178
+	 *
179
+	 * @param DateTimeZone $date_time_zone
180
+	 * @param int|null     $time
181
+	 * @param bool         $first_only
182
+	 * @return array
183
+	 * @throws InvalidArgumentException
184
+	 * @throws InvalidDataTypeException
185
+	 * @throws InvalidInterfaceException
186
+	 */
187
+	public static function get_timezone_transitions(DateTimeZone $date_time_zone, $time = null, $first_only = true)
188
+	{
189
+		return self::getHelperAdapter()->getTimezoneTransitions($date_time_zone, $time, $first_only);
190
+	}
191 191
 
192 192
 
193
-    /**
194
-     * Get Timezone Offset for given timezone object.
195
-     *
196
-     * @param DateTimeZone $date_time_zone
197
-     * @param null         $time
198
-     * @return mixed
199
-     * @throws InvalidArgumentException
200
-     * @throws InvalidDataTypeException
201
-     * @throws InvalidInterfaceException
202
-     */
203
-    public static function get_timezone_offset(DateTimeZone $date_time_zone, $time = null)
204
-    {
205
-        return self::getHelperAdapter()->getTimezoneOffset($date_time_zone, $time);
206
-    }
193
+	/**
194
+	 * Get Timezone Offset for given timezone object.
195
+	 *
196
+	 * @param DateTimeZone $date_time_zone
197
+	 * @param null         $time
198
+	 * @return mixed
199
+	 * @throws InvalidArgumentException
200
+	 * @throws InvalidDataTypeException
201
+	 * @throws InvalidInterfaceException
202
+	 */
203
+	public static function get_timezone_offset(DateTimeZone $date_time_zone, $time = null)
204
+	{
205
+		return self::getHelperAdapter()->getTimezoneOffset($date_time_zone, $time);
206
+	}
207 207
 
208 208
 
209
-    /**
210
-     * Prints a select input for the given timezone string.
211
-     * @param string $timezone_string
212
-     * @deprecatd 4.9.54.rc   Soft deprecation.  Consider using \EEH_DTT_Helper::wp_timezone_choice instead.
213
-     * @throws InvalidArgumentException
214
-     * @throws InvalidDataTypeException
215
-     * @throws InvalidInterfaceException
216
-     */
217
-    public static function timezone_select_input($timezone_string = '')
218
-    {
219
-        self::getHelperAdapter()->timezoneSelectInput($timezone_string);
220
-    }
209
+	/**
210
+	 * Prints a select input for the given timezone string.
211
+	 * @param string $timezone_string
212
+	 * @deprecatd 4.9.54.rc   Soft deprecation.  Consider using \EEH_DTT_Helper::wp_timezone_choice instead.
213
+	 * @throws InvalidArgumentException
214
+	 * @throws InvalidDataTypeException
215
+	 * @throws InvalidInterfaceException
216
+	 */
217
+	public static function timezone_select_input($timezone_string = '')
218
+	{
219
+		self::getHelperAdapter()->timezoneSelectInput($timezone_string);
220
+	}
221 221
 
222 222
 
223
-    /**
224
-     * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
225
-     * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
226
-     * the site is used.
227
-     * This is used typically when using a Unix timestamp any core WP functions that expect their specially
228
-     * computed timestamp (i.e. date_i18n() )
229
-     *
230
-     * @param int    $unix_timestamp                  if 0, then time() will be used.
231
-     * @param string $timezone_string                 timezone_string. If empty, then the current set timezone for the
232
-     *                                                site will be used.
233
-     * @return int $unix_timestamp with the offset applied for the given timezone.
234
-     * @throws InvalidArgumentException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidInterfaceException
237
-     */
238
-    public static function get_timestamp_with_offset($unix_timestamp = 0, $timezone_string = '')
239
-    {
240
-        return self::getHelperAdapter()->getTimestampWithOffset($unix_timestamp, $timezone_string);
241
-    }
223
+	/**
224
+	 * This method will take an incoming unix timestamp and add the offset to it for the given timezone_string.
225
+	 * If no unix timestamp is given then time() is used.  If no timezone is given then the set timezone string for
226
+	 * the site is used.
227
+	 * This is used typically when using a Unix timestamp any core WP functions that expect their specially
228
+	 * computed timestamp (i.e. date_i18n() )
229
+	 *
230
+	 * @param int    $unix_timestamp                  if 0, then time() will be used.
231
+	 * @param string $timezone_string                 timezone_string. If empty, then the current set timezone for the
232
+	 *                                                site will be used.
233
+	 * @return int $unix_timestamp with the offset applied for the given timezone.
234
+	 * @throws InvalidArgumentException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidInterfaceException
237
+	 */
238
+	public static function get_timestamp_with_offset($unix_timestamp = 0, $timezone_string = '')
239
+	{
240
+		return self::getHelperAdapter()->getTimestampWithOffset($unix_timestamp, $timezone_string);
241
+	}
242 242
 
243 243
 
244
-    /**
245
-     *    _set_date_time_field
246
-     *    modifies EE_Base_Class EE_Datetime_Field objects
247
-     *
248
-     * @param  EE_Base_Class $obj                 EE_Base_Class object
249
-     * @param    DateTime    $DateTime            PHP DateTime object
250
-     * @param  string        $datetime_field_name the datetime fieldname to be manipulated
251
-     * @return EE_Base_Class
252
-     * @throws EE_Error
253
-     */
254
-    protected static function _set_date_time_field(EE_Base_Class $obj, DateTime $DateTime, $datetime_field_name)
255
-    {
256
-        // grab current datetime format
257
-        $current_format = $obj->get_format();
258
-        // set new full timestamp format
259
-        $obj->set_date_format(EE_Datetime_Field::mysql_date_format);
260
-        $obj->set_time_format(EE_Datetime_Field::mysql_time_format);
261
-        // set the new date value using a full timestamp format so that no data is lost
262
-        $obj->set($datetime_field_name, $DateTime->format(EE_Datetime_Field::mysql_timestamp_format));
263
-        // reset datetime formats
264
-        $obj->set_date_format($current_format[0]);
265
-        $obj->set_time_format($current_format[1]);
266
-        return $obj;
267
-    }
244
+	/**
245
+	 *    _set_date_time_field
246
+	 *    modifies EE_Base_Class EE_Datetime_Field objects
247
+	 *
248
+	 * @param  EE_Base_Class $obj                 EE_Base_Class object
249
+	 * @param    DateTime    $DateTime            PHP DateTime object
250
+	 * @param  string        $datetime_field_name the datetime fieldname to be manipulated
251
+	 * @return EE_Base_Class
252
+	 * @throws EE_Error
253
+	 */
254
+	protected static function _set_date_time_field(EE_Base_Class $obj, DateTime $DateTime, $datetime_field_name)
255
+	{
256
+		// grab current datetime format
257
+		$current_format = $obj->get_format();
258
+		// set new full timestamp format
259
+		$obj->set_date_format(EE_Datetime_Field::mysql_date_format);
260
+		$obj->set_time_format(EE_Datetime_Field::mysql_time_format);
261
+		// set the new date value using a full timestamp format so that no data is lost
262
+		$obj->set($datetime_field_name, $DateTime->format(EE_Datetime_Field::mysql_timestamp_format));
263
+		// reset datetime formats
264
+		$obj->set_date_format($current_format[0]);
265
+		$obj->set_time_format($current_format[1]);
266
+		return $obj;
267
+	}
268 268
 
269 269
 
270
-    /**
271
-     *    date_time_add
272
-     *    helper for doing simple datetime calculations on a given datetime from EE_Base_Class
273
-     *    and modifying it IN the EE_Base_Class so you don't have to do anything else.
274
-     *
275
-     * @param  EE_Base_Class $obj                 EE_Base_Class object
276
-     * @param  string        $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
277
-     * @param  string        $period              what you are adding. The options are (years, months, days, hours,
278
-     *                                            minutes, seconds) defaults to years
279
-     * @param  integer       $value               what you want to increment the time by
280
-     * @return EE_Base_Class return the EE_Base_Class object so right away you can do something with it
281
-     *                                            (chaining)
282
-     * @throws EE_Error
283
-     * @throws Exception
284
-     */
285
-    public static function date_time_add(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
286
-    {
287
-        // get the raw UTC date.
288
-        $DateTime = $obj->get_DateTime_object($datetime_field_name);
289
-        $DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value);
290
-        return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
291
-    }
270
+	/**
271
+	 *    date_time_add
272
+	 *    helper for doing simple datetime calculations on a given datetime from EE_Base_Class
273
+	 *    and modifying it IN the EE_Base_Class so you don't have to do anything else.
274
+	 *
275
+	 * @param  EE_Base_Class $obj                 EE_Base_Class object
276
+	 * @param  string        $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
277
+	 * @param  string        $period              what you are adding. The options are (years, months, days, hours,
278
+	 *                                            minutes, seconds) defaults to years
279
+	 * @param  integer       $value               what you want to increment the time by
280
+	 * @return EE_Base_Class return the EE_Base_Class object so right away you can do something with it
281
+	 *                                            (chaining)
282
+	 * @throws EE_Error
283
+	 * @throws Exception
284
+	 */
285
+	public static function date_time_add(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
286
+	{
287
+		// get the raw UTC date.
288
+		$DateTime = $obj->get_DateTime_object($datetime_field_name);
289
+		$DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value);
290
+		return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
291
+	}
292 292
 
293 293
 
294
-    /**
295
-     *    date_time_subtract
296
-     *    same as date_time_add except subtracting value instead of adding.
297
-     *
298
-     * @param EE_Base_Class $obj
299
-     * @param  string       $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
300
-     * @param string        $period
301
-     * @param int           $value
302
-     * @return EE_Base_Class
303
-     * @throws EE_Error
304
-     * @throws Exception
305
-     */
306
-    public static function date_time_subtract(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
307
-    {
308
-        // get the raw UTC date
309
-        $DateTime = $obj->get_DateTime_object($datetime_field_name);
310
-        $DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value, '-');
311
-        return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
312
-    }
294
+	/**
295
+	 *    date_time_subtract
296
+	 *    same as date_time_add except subtracting value instead of adding.
297
+	 *
298
+	 * @param EE_Base_Class $obj
299
+	 * @param  string       $datetime_field_name name of the EE_Datetime_Filed datatype db column to be manipulated
300
+	 * @param string        $period
301
+	 * @param int           $value
302
+	 * @return EE_Base_Class
303
+	 * @throws EE_Error
304
+	 * @throws Exception
305
+	 */
306
+	public static function date_time_subtract(EE_Base_Class $obj, $datetime_field_name, $period = 'years', $value = 1)
307
+	{
308
+		// get the raw UTC date
309
+		$DateTime = $obj->get_DateTime_object($datetime_field_name);
310
+		$DateTime = EEH_DTT_Helper::calc_date($DateTime, $period, $value, '-');
311
+		return EEH_DTT_Helper::_set_date_time_field($obj, $DateTime, $datetime_field_name);
312
+	}
313 313
 
314 314
 
315
-    /**
316
-     * Simply takes an incoming DateTime object and does calculations on it based on the incoming parameters
317
-     *
318
-     * @param  DateTime   $DateTime DateTime object
319
-     * @param  string     $period   a value to indicate what interval is being used in the calculation. The options are
320
-     *                              'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
321
-     * @param  int|string $value    What you want to increment the date by
322
-     * @param  string     $operand  What operand you wish to use for the calculation
323
-     * @return DateTime return whatever type came in.
324
-     * @throws Exception
325
-     * @throws EE_Error
326
-     */
327
-    protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328
-    {
329
-        if (! $DateTime instanceof DateTime) {
330
-            throw new EE_Error(
331
-                sprintf(
332
-                    esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
333
-                    print_r($DateTime, true)
334
-                )
335
-            );
336
-        }
337
-        switch ($period) {
338
-            case 'years':
339
-                $value = 'P' . $value . 'Y';
340
-                break;
341
-            case 'months':
342
-                $value = 'P' . $value . 'M';
343
-                break;
344
-            case 'weeks':
345
-                $value = 'P' . $value . 'W';
346
-                break;
347
-            case 'days':
348
-                $value = 'P' . $value . 'D';
349
-                break;
350
-            case 'hours':
351
-                $value = 'PT' . $value . 'H';
352
-                break;
353
-            case 'minutes':
354
-                $value = 'PT' . $value . 'M';
355
-                break;
356
-            case 'seconds':
357
-                $value = 'PT' . $value . 'S';
358
-                break;
359
-        }
360
-        switch ($operand) {
361
-            case '+':
362
-                $DateTime->add(new DateInterval($value));
363
-                break;
364
-            case '-':
365
-                $DateTime->sub(new DateInterval($value));
366
-                break;
367
-        }
368
-        return $DateTime;
369
-    }
315
+	/**
316
+	 * Simply takes an incoming DateTime object and does calculations on it based on the incoming parameters
317
+	 *
318
+	 * @param  DateTime   $DateTime DateTime object
319
+	 * @param  string     $period   a value to indicate what interval is being used in the calculation. The options are
320
+	 *                              'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
321
+	 * @param  int|string $value    What you want to increment the date by
322
+	 * @param  string     $operand  What operand you wish to use for the calculation
323
+	 * @return DateTime return whatever type came in.
324
+	 * @throws Exception
325
+	 * @throws EE_Error
326
+	 */
327
+	protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328
+	{
329
+		if (! $DateTime instanceof DateTime) {
330
+			throw new EE_Error(
331
+				sprintf(
332
+					esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
333
+					print_r($DateTime, true)
334
+				)
335
+			);
336
+		}
337
+		switch ($period) {
338
+			case 'years':
339
+				$value = 'P' . $value . 'Y';
340
+				break;
341
+			case 'months':
342
+				$value = 'P' . $value . 'M';
343
+				break;
344
+			case 'weeks':
345
+				$value = 'P' . $value . 'W';
346
+				break;
347
+			case 'days':
348
+				$value = 'P' . $value . 'D';
349
+				break;
350
+			case 'hours':
351
+				$value = 'PT' . $value . 'H';
352
+				break;
353
+			case 'minutes':
354
+				$value = 'PT' . $value . 'M';
355
+				break;
356
+			case 'seconds':
357
+				$value = 'PT' . $value . 'S';
358
+				break;
359
+		}
360
+		switch ($operand) {
361
+			case '+':
362
+				$DateTime->add(new DateInterval($value));
363
+				break;
364
+			case '-':
365
+				$DateTime->sub(new DateInterval($value));
366
+				break;
367
+		}
368
+		return $DateTime;
369
+	}
370 370
 
371 371
 
372
-    /**
373
-     * Simply takes an incoming Unix timestamp and does calculations on it based on the incoming parameters
374
-     *
375
-     * @param  int     $timestamp Unix timestamp
376
-     * @param  string  $period    a value to indicate what interval is being used in the calculation. The options are
377
-     *                            'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
378
-     * @param  integer $value     What you want to increment the date by
379
-     * @param  string  $operand   What operand you wish to use for the calculation
380
-     * @return int
381
-     * @throws EE_Error
382
-     */
383
-    protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384
-    {
385
-        if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386
-            throw new EE_Error(
387
-                sprintf(
388
-                    esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
389
-                    print_r($timestamp, true)
390
-                )
391
-            );
392
-        }
393
-        switch ($period) {
394
-            case 'years':
395
-                $value = YEAR_IN_SECONDS * $value;
396
-                break;
397
-            case 'months':
398
-                $value = YEAR_IN_SECONDS / 12 * $value;
399
-                break;
400
-            case 'weeks':
401
-                $value = WEEK_IN_SECONDS * $value;
402
-                break;
403
-            case 'days':
404
-                $value = DAY_IN_SECONDS * $value;
405
-                break;
406
-            case 'hours':
407
-                $value = HOUR_IN_SECONDS * $value;
408
-                break;
409
-            case 'minutes':
410
-                $value = MINUTE_IN_SECONDS * $value;
411
-                break;
412
-        }
413
-        switch ($operand) {
414
-            case '+':
415
-                $timestamp += $value;
416
-                break;
417
-            case '-':
418
-                $timestamp -= $value;
419
-                break;
420
-        }
421
-        return $timestamp;
422
-    }
372
+	/**
373
+	 * Simply takes an incoming Unix timestamp and does calculations on it based on the incoming parameters
374
+	 *
375
+	 * @param  int     $timestamp Unix timestamp
376
+	 * @param  string  $period    a value to indicate what interval is being used in the calculation. The options are
377
+	 *                            'years', 'months', 'days', 'hours', 'minutes', 'seconds'. Defaults to years.
378
+	 * @param  integer $value     What you want to increment the date by
379
+	 * @param  string  $operand   What operand you wish to use for the calculation
380
+	 * @return int
381
+	 * @throws EE_Error
382
+	 */
383
+	protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384
+	{
385
+		if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386
+			throw new EE_Error(
387
+				sprintf(
388
+					esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
389
+					print_r($timestamp, true)
390
+				)
391
+			);
392
+		}
393
+		switch ($period) {
394
+			case 'years':
395
+				$value = YEAR_IN_SECONDS * $value;
396
+				break;
397
+			case 'months':
398
+				$value = YEAR_IN_SECONDS / 12 * $value;
399
+				break;
400
+			case 'weeks':
401
+				$value = WEEK_IN_SECONDS * $value;
402
+				break;
403
+			case 'days':
404
+				$value = DAY_IN_SECONDS * $value;
405
+				break;
406
+			case 'hours':
407
+				$value = HOUR_IN_SECONDS * $value;
408
+				break;
409
+			case 'minutes':
410
+				$value = MINUTE_IN_SECONDS * $value;
411
+				break;
412
+		}
413
+		switch ($operand) {
414
+			case '+':
415
+				$timestamp += $value;
416
+				break;
417
+			case '-':
418
+				$timestamp -= $value;
419
+				break;
420
+		}
421
+		return $timestamp;
422
+	}
423 423
 
424 424
 
425
-    /**
426
-     * Simply takes an incoming UTC timestamp or DateTime object and does calculations on it based on the incoming
427
-     * parameters and returns the new timestamp or DateTime.
428
-     *
429
-     * @param  int | DateTime $DateTime_or_timestamp DateTime object or Unix timestamp
430
-     * @param  string         $period                a value to indicate what interval is being used in the
431
-     *                                               calculation. The options are 'years', 'months', 'days', 'hours',
432
-     *                                               'minutes', 'seconds'. Defaults to years.
433
-     * @param  integer        $value                 What you want to increment the date by
434
-     * @param  string         $operand               What operand you wish to use for the calculation
435
-     * @return mixed string|DateTime          return whatever type came in.
436
-     * @throws Exception
437
-     * @throws EE_Error
438
-     */
439
-    public static function calc_date($DateTime_or_timestamp, $period = 'years', $value = 1, $operand = '+')
440
-    {
441
-        if ($DateTime_or_timestamp instanceof DateTime) {
442
-            return EEH_DTT_Helper::_modify_datetime_object(
443
-                $DateTime_or_timestamp,
444
-                $period,
445
-                $value,
446
-                $operand
447
-            );
448
-        }
449
-        if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $DateTime_or_timestamp)) {
450
-            return EEH_DTT_Helper::_modify_timestamp(
451
-                $DateTime_or_timestamp,
452
-                $period,
453
-                $value,
454
-                $operand
455
-            );
456
-        }
457
-        // error
458
-        return $DateTime_or_timestamp;
459
-    }
425
+	/**
426
+	 * Simply takes an incoming UTC timestamp or DateTime object and does calculations on it based on the incoming
427
+	 * parameters and returns the new timestamp or DateTime.
428
+	 *
429
+	 * @param  int | DateTime $DateTime_or_timestamp DateTime object or Unix timestamp
430
+	 * @param  string         $period                a value to indicate what interval is being used in the
431
+	 *                                               calculation. The options are 'years', 'months', 'days', 'hours',
432
+	 *                                               'minutes', 'seconds'. Defaults to years.
433
+	 * @param  integer        $value                 What you want to increment the date by
434
+	 * @param  string         $operand               What operand you wish to use for the calculation
435
+	 * @return mixed string|DateTime          return whatever type came in.
436
+	 * @throws Exception
437
+	 * @throws EE_Error
438
+	 */
439
+	public static function calc_date($DateTime_or_timestamp, $period = 'years', $value = 1, $operand = '+')
440
+	{
441
+		if ($DateTime_or_timestamp instanceof DateTime) {
442
+			return EEH_DTT_Helper::_modify_datetime_object(
443
+				$DateTime_or_timestamp,
444
+				$period,
445
+				$value,
446
+				$operand
447
+			);
448
+		}
449
+		if (preg_match(EE_Datetime_Field::unix_timestamp_regex, $DateTime_or_timestamp)) {
450
+			return EEH_DTT_Helper::_modify_timestamp(
451
+				$DateTime_or_timestamp,
452
+				$period,
453
+				$value,
454
+				$operand
455
+			);
456
+		}
457
+		// error
458
+		return $DateTime_or_timestamp;
459
+	}
460 460
 
461 461
 
462
-    /**
463
-     * The purpose of this helper method is to receive an incoming format string in php date/time format
464
-     * and spit out the js and moment.js equivalent formats.
465
-     * Note, if no format string is given, then it is assumed the user wants what is set for WP.
466
-     * Note, js date and time formats are those used by the jquery-ui datepicker and the jquery-ui date-
467
-     * time picker.
468
-     *
469
-     * @see http://stackoverflow.com/posts/16725290/ for the code inspiration.
470
-     * @param string $date_format_string
471
-     * @param string $time_format_string
472
-     * @return array
473
-     *              array(
474
-     *              'js' => array (
475
-     *              'date' => //date format
476
-     *              'time' => //time format
477
-     *              ),
478
-     *              'moment' => //date and time format.
479
-     *              )
480
-     */
481
-    public static function convert_php_to_js_and_moment_date_formats(
482
-        $date_format_string = null,
483
-        $time_format_string = null
484
-    ) {
485
-        if ($date_format_string === null) {
486
-            $date_format_string = (string) get_option('date_format');
487
-        }
488
-        if ($time_format_string === null) {
489
-            $time_format_string = (string) get_option('time_format');
490
-        }
491
-        $date_format = self::_php_to_js_moment_converter($date_format_string);
492
-        $time_format = self::_php_to_js_moment_converter($time_format_string);
493
-        return array(
494
-            'js'     => array(
495
-                'date' => $date_format['js'],
496
-                'time' => $time_format['js'],
497
-            ),
498
-            'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
499
-            'moment_split' => array(
500
-                'date' => $date_format['moment'],
501
-                'time' => $time_format['moment']
502
-            )
503
-        );
504
-    }
462
+	/**
463
+	 * The purpose of this helper method is to receive an incoming format string in php date/time format
464
+	 * and spit out the js and moment.js equivalent formats.
465
+	 * Note, if no format string is given, then it is assumed the user wants what is set for WP.
466
+	 * Note, js date and time formats are those used by the jquery-ui datepicker and the jquery-ui date-
467
+	 * time picker.
468
+	 *
469
+	 * @see http://stackoverflow.com/posts/16725290/ for the code inspiration.
470
+	 * @param string $date_format_string
471
+	 * @param string $time_format_string
472
+	 * @return array
473
+	 *              array(
474
+	 *              'js' => array (
475
+	 *              'date' => //date format
476
+	 *              'time' => //time format
477
+	 *              ),
478
+	 *              'moment' => //date and time format.
479
+	 *              )
480
+	 */
481
+	public static function convert_php_to_js_and_moment_date_formats(
482
+		$date_format_string = null,
483
+		$time_format_string = null
484
+	) {
485
+		if ($date_format_string === null) {
486
+			$date_format_string = (string) get_option('date_format');
487
+		}
488
+		if ($time_format_string === null) {
489
+			$time_format_string = (string) get_option('time_format');
490
+		}
491
+		$date_format = self::_php_to_js_moment_converter($date_format_string);
492
+		$time_format = self::_php_to_js_moment_converter($time_format_string);
493
+		return array(
494
+			'js'     => array(
495
+				'date' => $date_format['js'],
496
+				'time' => $time_format['js'],
497
+			),
498
+			'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
499
+			'moment_split' => array(
500
+				'date' => $date_format['moment'],
501
+				'time' => $time_format['moment']
502
+			)
503
+		);
504
+	}
505 505
 
506 506
 
507
-    /**
508
-     * This converts incoming format string into js and moment variations.
509
-     *
510
-     * @param string $format_string incoming php format string
511
-     * @return array js and moment formats.
512
-     */
513
-    protected static function _php_to_js_moment_converter($format_string)
514
-    {
515
-        /**
516
-         * This is a map of symbols for formats.
517
-         * The index is the php symbol, the equivalent values are in the array.
518
-         *
519
-         * @var array
520
-         */
521
-        $symbols_map          = array(
522
-            // Day
523
-            // 01
524
-            'd' => array(
525
-                'js'     => 'dd',
526
-                'moment' => 'DD',
527
-            ),
528
-            // Mon
529
-            'D' => array(
530
-                'js'     => 'D',
531
-                'moment' => 'ddd',
532
-            ),
533
-            // 1,2,...31
534
-            'j' => array(
535
-                'js'     => 'd',
536
-                'moment' => 'D',
537
-            ),
538
-            // Monday
539
-            'l' => array(
540
-                'js'     => 'DD',
541
-                'moment' => 'dddd',
542
-            ),
543
-            // ISO numeric representation of the day of the week (1-6)
544
-            'N' => array(
545
-                'js'     => '',
546
-                'moment' => 'E',
547
-            ),
548
-            // st,nd.rd
549
-            'S' => array(
550
-                'js'     => '',
551
-                'moment' => 'o',
552
-            ),
553
-            // numeric representation of day of week (0-6)
554
-            'w' => array(
555
-                'js'     => '',
556
-                'moment' => 'd',
557
-            ),
558
-            // day of year starting from 0 (0-365)
559
-            'z' => array(
560
-                'js'     => 'o',
561
-                'moment' => 'DDD' // note moment does not start with 0 so will need to modify by subtracting 1
562
-            ),
563
-            // Week
564
-            // ISO-8601 week number of year (weeks starting on monday)
565
-            'W' => array(
566
-                'js'     => '',
567
-                'moment' => 'w',
568
-            ),
569
-            // Month
570
-            // January...December
571
-            'F' => array(
572
-                'js'     => 'MM',
573
-                'moment' => 'MMMM',
574
-            ),
575
-            // 01...12
576
-            'm' => array(
577
-                'js'     => 'mm',
578
-                'moment' => 'MM',
579
-            ),
580
-            // Jan...Dec
581
-            'M' => array(
582
-                'js'     => 'M',
583
-                'moment' => 'MMM',
584
-            ),
585
-            // 1-12
586
-            'n' => array(
587
-                'js'     => 'm',
588
-                'moment' => 'M',
589
-            ),
590
-            // number of days in given month
591
-            't' => array(
592
-                'js'     => '',
593
-                'moment' => '',
594
-            ),
595
-            // Year
596
-            // whether leap year or not 1/0
597
-            'L' => array(
598
-                'js'     => '',
599
-                'moment' => '',
600
-            ),
601
-            // ISO-8601 year number
602
-            'o' => array(
603
-                'js'     => '',
604
-                'moment' => 'GGGG',
605
-            ),
606
-            // 1999...2003
607
-            'Y' => array(
608
-                'js'     => 'yy',
609
-                'moment' => 'YYYY',
610
-            ),
611
-            // 99...03
612
-            'y' => array(
613
-                'js'     => 'y',
614
-                'moment' => 'YY',
615
-            ),
616
-            // Time
617
-            // am/pm
618
-            'a' => array(
619
-                'js'     => 'tt',
620
-                'moment' => 'a',
621
-            ),
622
-            // AM/PM
623
-            'A' => array(
624
-                'js'     => 'TT',
625
-                'moment' => 'A',
626
-            ),
627
-            // Swatch Internet Time?!?
628
-            'B' => array(
629
-                'js'     => '',
630
-                'moment' => '',
631
-            ),
632
-            // 1...12
633
-            'g' => array(
634
-                'js'     => 'h',
635
-                'moment' => 'h',
636
-            ),
637
-            // 0...23
638
-            'G' => array(
639
-                'js'     => 'H',
640
-                'moment' => 'H',
641
-            ),
642
-            // 01...12
643
-            'h' => array(
644
-                'js'     => 'hh',
645
-                'moment' => 'hh',
646
-            ),
647
-            // 00...23
648
-            'H' => array(
649
-                'js'     => 'HH',
650
-                'moment' => 'HH',
651
-            ),
652
-            // 00..59
653
-            'i' => array(
654
-                'js'     => 'mm',
655
-                'moment' => 'mm',
656
-            ),
657
-            // seconds... 00...59
658
-            's' => array(
659
-                'js'     => 'ss',
660
-                'moment' => 'ss',
661
-            ),
662
-            // microseconds
663
-            'u' => array(
664
-                'js'     => '',
665
-                'moment' => '',
666
-            ),
667
-        );
668
-        $jquery_ui_format     = '';
669
-        $moment_format        = '';
670
-        $escaping             = false;
671
-        $format_string_length = strlen($format_string);
672
-        for ($i = 0; $i < $format_string_length; $i++) {
673
-            $char = $format_string[ $i ];
674
-            if ($char === '\\') { // PHP date format escaping character
675
-                $i++;
676
-                if ($escaping) {
677
-                    $jquery_ui_format .= $format_string[ $i ];
678
-                    $moment_format    .= $format_string[ $i ];
679
-                } else {
680
-                    $jquery_ui_format .= '\'' . $format_string[ $i ];
681
-                    $moment_format    .= $format_string[ $i ];
682
-                }
683
-                $escaping = true;
684
-            } else {
685
-                if ($escaping) {
686
-                    $jquery_ui_format .= "'";
687
-                    $moment_format    .= "'";
688
-                    $escaping         = false;
689
-                }
690
-                if (isset($symbols_map[ $char ])) {
691
-                    $jquery_ui_format .= $symbols_map[ $char ]['js'];
692
-                    $moment_format    .= $symbols_map[ $char ]['moment'];
693
-                } else {
694
-                    $jquery_ui_format .= $char;
695
-                    $moment_format    .= $char;
696
-                }
697
-            }
698
-        }
699
-        return array('js' => $jquery_ui_format, 'moment' => $moment_format);
700
-    }
507
+	/**
508
+	 * This converts incoming format string into js and moment variations.
509
+	 *
510
+	 * @param string $format_string incoming php format string
511
+	 * @return array js and moment formats.
512
+	 */
513
+	protected static function _php_to_js_moment_converter($format_string)
514
+	{
515
+		/**
516
+		 * This is a map of symbols for formats.
517
+		 * The index is the php symbol, the equivalent values are in the array.
518
+		 *
519
+		 * @var array
520
+		 */
521
+		$symbols_map          = array(
522
+			// Day
523
+			// 01
524
+			'd' => array(
525
+				'js'     => 'dd',
526
+				'moment' => 'DD',
527
+			),
528
+			// Mon
529
+			'D' => array(
530
+				'js'     => 'D',
531
+				'moment' => 'ddd',
532
+			),
533
+			// 1,2,...31
534
+			'j' => array(
535
+				'js'     => 'd',
536
+				'moment' => 'D',
537
+			),
538
+			// Monday
539
+			'l' => array(
540
+				'js'     => 'DD',
541
+				'moment' => 'dddd',
542
+			),
543
+			// ISO numeric representation of the day of the week (1-6)
544
+			'N' => array(
545
+				'js'     => '',
546
+				'moment' => 'E',
547
+			),
548
+			// st,nd.rd
549
+			'S' => array(
550
+				'js'     => '',
551
+				'moment' => 'o',
552
+			),
553
+			// numeric representation of day of week (0-6)
554
+			'w' => array(
555
+				'js'     => '',
556
+				'moment' => 'd',
557
+			),
558
+			// day of year starting from 0 (0-365)
559
+			'z' => array(
560
+				'js'     => 'o',
561
+				'moment' => 'DDD' // note moment does not start with 0 so will need to modify by subtracting 1
562
+			),
563
+			// Week
564
+			// ISO-8601 week number of year (weeks starting on monday)
565
+			'W' => array(
566
+				'js'     => '',
567
+				'moment' => 'w',
568
+			),
569
+			// Month
570
+			// January...December
571
+			'F' => array(
572
+				'js'     => 'MM',
573
+				'moment' => 'MMMM',
574
+			),
575
+			// 01...12
576
+			'm' => array(
577
+				'js'     => 'mm',
578
+				'moment' => 'MM',
579
+			),
580
+			// Jan...Dec
581
+			'M' => array(
582
+				'js'     => 'M',
583
+				'moment' => 'MMM',
584
+			),
585
+			// 1-12
586
+			'n' => array(
587
+				'js'     => 'm',
588
+				'moment' => 'M',
589
+			),
590
+			// number of days in given month
591
+			't' => array(
592
+				'js'     => '',
593
+				'moment' => '',
594
+			),
595
+			// Year
596
+			// whether leap year or not 1/0
597
+			'L' => array(
598
+				'js'     => '',
599
+				'moment' => '',
600
+			),
601
+			// ISO-8601 year number
602
+			'o' => array(
603
+				'js'     => '',
604
+				'moment' => 'GGGG',
605
+			),
606
+			// 1999...2003
607
+			'Y' => array(
608
+				'js'     => 'yy',
609
+				'moment' => 'YYYY',
610
+			),
611
+			// 99...03
612
+			'y' => array(
613
+				'js'     => 'y',
614
+				'moment' => 'YY',
615
+			),
616
+			// Time
617
+			// am/pm
618
+			'a' => array(
619
+				'js'     => 'tt',
620
+				'moment' => 'a',
621
+			),
622
+			// AM/PM
623
+			'A' => array(
624
+				'js'     => 'TT',
625
+				'moment' => 'A',
626
+			),
627
+			// Swatch Internet Time?!?
628
+			'B' => array(
629
+				'js'     => '',
630
+				'moment' => '',
631
+			),
632
+			// 1...12
633
+			'g' => array(
634
+				'js'     => 'h',
635
+				'moment' => 'h',
636
+			),
637
+			// 0...23
638
+			'G' => array(
639
+				'js'     => 'H',
640
+				'moment' => 'H',
641
+			),
642
+			// 01...12
643
+			'h' => array(
644
+				'js'     => 'hh',
645
+				'moment' => 'hh',
646
+			),
647
+			// 00...23
648
+			'H' => array(
649
+				'js'     => 'HH',
650
+				'moment' => 'HH',
651
+			),
652
+			// 00..59
653
+			'i' => array(
654
+				'js'     => 'mm',
655
+				'moment' => 'mm',
656
+			),
657
+			// seconds... 00...59
658
+			's' => array(
659
+				'js'     => 'ss',
660
+				'moment' => 'ss',
661
+			),
662
+			// microseconds
663
+			'u' => array(
664
+				'js'     => '',
665
+				'moment' => '',
666
+			),
667
+		);
668
+		$jquery_ui_format     = '';
669
+		$moment_format        = '';
670
+		$escaping             = false;
671
+		$format_string_length = strlen($format_string);
672
+		for ($i = 0; $i < $format_string_length; $i++) {
673
+			$char = $format_string[ $i ];
674
+			if ($char === '\\') { // PHP date format escaping character
675
+				$i++;
676
+				if ($escaping) {
677
+					$jquery_ui_format .= $format_string[ $i ];
678
+					$moment_format    .= $format_string[ $i ];
679
+				} else {
680
+					$jquery_ui_format .= '\'' . $format_string[ $i ];
681
+					$moment_format    .= $format_string[ $i ];
682
+				}
683
+				$escaping = true;
684
+			} else {
685
+				if ($escaping) {
686
+					$jquery_ui_format .= "'";
687
+					$moment_format    .= "'";
688
+					$escaping         = false;
689
+				}
690
+				if (isset($symbols_map[ $char ])) {
691
+					$jquery_ui_format .= $symbols_map[ $char ]['js'];
692
+					$moment_format    .= $symbols_map[ $char ]['moment'];
693
+				} else {
694
+					$jquery_ui_format .= $char;
695
+					$moment_format    .= $char;
696
+				}
697
+			}
698
+		}
699
+		return array('js' => $jquery_ui_format, 'moment' => $moment_format);
700
+	}
701 701
 
702 702
 
703
-    /**
704
-     * This takes an incoming format string and validates it to ensure it will work fine with PHP.
705
-     *
706
-     * @param string $format_string   Incoming format string for php date().
707
-     * @return mixed bool|array  If all is okay then TRUE is returned.  Otherwise an array of validation
708
-     *                                errors is returned.  So for client code calling, check for is_array() to
709
-     *                                indicate failed validations.
710
-     */
711
-    public static function validate_format_string($format_string)
712
-    {
713
-        $error_msg = array();
714
-        // time format checks
715
-        switch (true) {
716
-            case strpos($format_string, 'h') !== false:
717
-            case strpos($format_string, 'g') !== false:
718
-                /**
719
-                 * if the time string has a lowercase 'h' which == 12 hour time format and there
720
-                 * is not any ante meridiem format ('a' or 'A').  Then throw an error because its
721
-                 * too ambiguous and PHP won't be able to figure out whether 1 = 1pm or 1am.
722
-                 */
723
-                if (stripos($format_string, 'A') === false) {
724
-                    $error_msg[] = esc_html__(
725
-                        'There is a  time format for 12 hour time but no  "a" or "A" to indicate am/pm.  Without this distinction, PHP is unable to determine if a "1" for the hour value equals "1pm" or "1am".',
726
-                        'event_espresso'
727
-                    );
728
-                }
729
-                break;
730
-        }
731
-        return empty($error_msg) ? true : $error_msg;
732
-    }
703
+	/**
704
+	 * This takes an incoming format string and validates it to ensure it will work fine with PHP.
705
+	 *
706
+	 * @param string $format_string   Incoming format string for php date().
707
+	 * @return mixed bool|array  If all is okay then TRUE is returned.  Otherwise an array of validation
708
+	 *                                errors is returned.  So for client code calling, check for is_array() to
709
+	 *                                indicate failed validations.
710
+	 */
711
+	public static function validate_format_string($format_string)
712
+	{
713
+		$error_msg = array();
714
+		// time format checks
715
+		switch (true) {
716
+			case strpos($format_string, 'h') !== false:
717
+			case strpos($format_string, 'g') !== false:
718
+				/**
719
+				 * if the time string has a lowercase 'h' which == 12 hour time format and there
720
+				 * is not any ante meridiem format ('a' or 'A').  Then throw an error because its
721
+				 * too ambiguous and PHP won't be able to figure out whether 1 = 1pm or 1am.
722
+				 */
723
+				if (stripos($format_string, 'A') === false) {
724
+					$error_msg[] = esc_html__(
725
+						'There is a  time format for 12 hour time but no  "a" or "A" to indicate am/pm.  Without this distinction, PHP is unable to determine if a "1" for the hour value equals "1pm" or "1am".',
726
+						'event_espresso'
727
+					);
728
+				}
729
+				break;
730
+		}
731
+		return empty($error_msg) ? true : $error_msg;
732
+	}
733 733
 
734 734
 
735
-    /**
736
-     *     If the the first date starts at midnight on one day, and the next date ends at midnight on the
737
-     *     very next day then this method will return true.
738
-     *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-16 00:00:00 then this function will return true.
739
-     *    If $date_1 = 2015-12-15 03:00:00 and $date_2 = 2015-12_16 03:00:00 then this function will return false.
740
-     *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-15 00:00:00 then this function will return true.
741
-     *
742
-     * @param mixed $date_1
743
-     * @param mixed $date_2
744
-     * @return bool
745
-     */
746
-    public static function dates_represent_one_24_hour_date($date_1, $date_2)
747
-    {
735
+	/**
736
+	 *     If the the first date starts at midnight on one day, and the next date ends at midnight on the
737
+	 *     very next day then this method will return true.
738
+	 *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-16 00:00:00 then this function will return true.
739
+	 *    If $date_1 = 2015-12-15 03:00:00 and $date_2 = 2015-12_16 03:00:00 then this function will return false.
740
+	 *    If $date_1 = 2015-12-15 00:00:00 and $date_2 = 2015-12-15 00:00:00 then this function will return true.
741
+	 *
742
+	 * @param mixed $date_1
743
+	 * @param mixed $date_2
744
+	 * @return bool
745
+	 */
746
+	public static function dates_represent_one_24_hour_date($date_1, $date_2)
747
+	{
748 748
 
749
-        if (
750
-            (! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
751
-            || ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
752
-                || $date_2->format(
753
-                    EE_Datetime_Field::mysql_time_format
754
-                ) !== '00:00:00')
755
-        ) {
756
-            return false;
757
-        }
758
-        return $date_2->format('U') - $date_1->format('U') === 86400;
759
-    }
749
+		if (
750
+			(! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
751
+			|| ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
752
+				|| $date_2->format(
753
+					EE_Datetime_Field::mysql_time_format
754
+				) !== '00:00:00')
755
+		) {
756
+			return false;
757
+		}
758
+		return $date_2->format('U') - $date_1->format('U') === 86400;
759
+	}
760 760
 
761 761
 
762
-    /**
763
-     * This returns the appropriate query interval string that can be used in sql queries involving mysql Date
764
-     * Functions.
765
-     *
766
-     * @param string $timezone_string    A timezone string in a valid format to instantiate a DateTimeZone object.
767
-     * @param string $field_for_interval The Database field that is the interval is applied to in the query.
768
-     * @return string
769
-     */
770
-    public static function get_sql_query_interval_for_offset($timezone_string, $field_for_interval)
771
-    {
772
-        try {
773
-            /** need to account for timezone offset on the selects */
774
-            $DateTimeZone = new DateTimeZone($timezone_string);
775
-        } catch (Exception $e) {
776
-            $DateTimeZone = null;
777
-        }
778
-        /**
779
-         * Note get_option( 'gmt_offset') returns a value in hours, whereas DateTimeZone::getOffset returns values in seconds.
780
-         * Hence we do the calc for DateTimeZone::getOffset.
781
-         */
782
-        $offset         = $DateTimeZone instanceof DateTimeZone
783
-            ? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
784
-            : (float) get_option('gmt_offset');
785
-        $query_interval = $offset < 0
786
-            ? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
787
-            : 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
788
-        return $query_interval;
789
-    }
762
+	/**
763
+	 * This returns the appropriate query interval string that can be used in sql queries involving mysql Date
764
+	 * Functions.
765
+	 *
766
+	 * @param string $timezone_string    A timezone string in a valid format to instantiate a DateTimeZone object.
767
+	 * @param string $field_for_interval The Database field that is the interval is applied to in the query.
768
+	 * @return string
769
+	 */
770
+	public static function get_sql_query_interval_for_offset($timezone_string, $field_for_interval)
771
+	{
772
+		try {
773
+			/** need to account for timezone offset on the selects */
774
+			$DateTimeZone = new DateTimeZone($timezone_string);
775
+		} catch (Exception $e) {
776
+			$DateTimeZone = null;
777
+		}
778
+		/**
779
+		 * Note get_option( 'gmt_offset') returns a value in hours, whereas DateTimeZone::getOffset returns values in seconds.
780
+		 * Hence we do the calc for DateTimeZone::getOffset.
781
+		 */
782
+		$offset         = $DateTimeZone instanceof DateTimeZone
783
+			? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
784
+			: (float) get_option('gmt_offset');
785
+		$query_interval = $offset < 0
786
+			? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
787
+			: 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
788
+		return $query_interval;
789
+	}
790 790
 
791 791
 
792
-    /**
793
-     * Retrieves the site's default timezone and returns it formatted so it's ready for display
794
-     * to users. If you want to customize how its displayed feel free to fetch the 'timezone_string'
795
-     * and 'gmt_offset' WordPress options directly; or use the filter
796
-     * FHEE__EEH_DTT_Helper__get_timezone_string_for_display
797
-     * (although note that we remove any HTML that may be added)
798
-     *
799
-     * @return string
800
-     */
801
-    public static function get_timezone_string_for_display()
802
-    {
803
-        $pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
804
-        if (! empty($pretty_timezone)) {
805
-            return esc_html($pretty_timezone);
806
-        }
807
-        $timezone_string = get_option('timezone_string');
808
-        if ($timezone_string) {
809
-            static $mo_loaded = false;
810
-            // Load translations for continents and cities just like wp_timezone_choice does
811
-            if (! $mo_loaded) {
812
-                $locale = get_locale();
813
-                $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
814
-                load_textdomain('continents-cities', $mofile);
815
-                $mo_loaded = true;
816
-            }
817
-            // well that was easy.
818
-            $parts = explode('/', $timezone_string);
819
-            // remove the continent
820
-            unset($parts[0]);
821
-            $t_parts = array();
822
-            // phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
823
-            // phpcs:disable WordPress.WP.I18n.TextDomainMismatch
824
-            // disabled because this code is copied from WordPress and is a WordPress domain
825
-            foreach ($parts as $part) {
826
-                $t_parts[] = translate(str_replace('_', ' ', $part), 'continents-cities');
827
-            }
828
-            return implode(' - ', $t_parts);
829
-            // phpcs:enable
830
-        }
831
-        // they haven't set the timezone string, so let's return a string like "UTC+1"
832
-        $gmt_offset = get_option('gmt_offset');
833
-        $prefix     = (int) $gmt_offset >= 0 ? '+' : '';
834
-        $parts      = explode('.', (string) $gmt_offset);
835
-        if (count($parts) === 1) {
836
-            $parts[1] = '00';
837
-        } else {
838
-            // convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
839
-            // to minutes, eg 30 or 15, respectively
840
-            $hour_fraction = (float) ('0.' . $parts[1]);
841
-            $parts[1]      = (string) $hour_fraction * 60;
842
-        }
843
-        return sprintf(esc_html__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
844
-    }
792
+	/**
793
+	 * Retrieves the site's default timezone and returns it formatted so it's ready for display
794
+	 * to users. If you want to customize how its displayed feel free to fetch the 'timezone_string'
795
+	 * and 'gmt_offset' WordPress options directly; or use the filter
796
+	 * FHEE__EEH_DTT_Helper__get_timezone_string_for_display
797
+	 * (although note that we remove any HTML that may be added)
798
+	 *
799
+	 * @return string
800
+	 */
801
+	public static function get_timezone_string_for_display()
802
+	{
803
+		$pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
804
+		if (! empty($pretty_timezone)) {
805
+			return esc_html($pretty_timezone);
806
+		}
807
+		$timezone_string = get_option('timezone_string');
808
+		if ($timezone_string) {
809
+			static $mo_loaded = false;
810
+			// Load translations for continents and cities just like wp_timezone_choice does
811
+			if (! $mo_loaded) {
812
+				$locale = get_locale();
813
+				$mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
814
+				load_textdomain('continents-cities', $mofile);
815
+				$mo_loaded = true;
816
+			}
817
+			// well that was easy.
818
+			$parts = explode('/', $timezone_string);
819
+			// remove the continent
820
+			unset($parts[0]);
821
+			$t_parts = array();
822
+			// phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
823
+			// phpcs:disable WordPress.WP.I18n.TextDomainMismatch
824
+			// disabled because this code is copied from WordPress and is a WordPress domain
825
+			foreach ($parts as $part) {
826
+				$t_parts[] = translate(str_replace('_', ' ', $part), 'continents-cities');
827
+			}
828
+			return implode(' - ', $t_parts);
829
+			// phpcs:enable
830
+		}
831
+		// they haven't set the timezone string, so let's return a string like "UTC+1"
832
+		$gmt_offset = get_option('gmt_offset');
833
+		$prefix     = (int) $gmt_offset >= 0 ? '+' : '';
834
+		$parts      = explode('.', (string) $gmt_offset);
835
+		if (count($parts) === 1) {
836
+			$parts[1] = '00';
837
+		} else {
838
+			// convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
839
+			// to minutes, eg 30 or 15, respectively
840
+			$hour_fraction = (float) ('0.' . $parts[1]);
841
+			$parts[1]      = (string) $hour_fraction * 60;
842
+		}
843
+		return sprintf(esc_html__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
844
+	}
845 845
 
846 846
 
847 847
 
848
-    /**
849
-     * So PHP does this awesome thing where if you are trying to get a timestamp
850
-     * for a month using a string like "February" or "February 2017",
851
-     * and you don't specify a day as part of your string,
852
-     * then PHP will use whatever the current day of the month is.
853
-     * IF the current day of the month happens to be the 30th or 31st,
854
-     * then PHP gets really confused by a date like February 30,
855
-     * so instead of saying
856
-     *      "Hey February only has 28 days (this year)...
857
-     *      ...you must have meant the last day of the month!"
858
-     * PHP does the next most logical thing, and bumps the date up to March 2nd,
859
-     * because someone requesting February 30th obviously meant March 1st!
860
-     * The way around this is to always set the day to the first,
861
-     * so that the month will stay on the month you wanted.
862
-     * this method will add that "1" into your date regardless of the format.
863
-     *
864
-     * @param string $month
865
-     * @return string
866
-     */
867
-    public static function first_of_month_timestamp($month = '')
868
-    {
869
-        $month = (string) $month;
870
-        $year  = '';
871
-        // check if the incoming string has a year in it or not
872
-        if (preg_match('/\b\d{4}\b/', $month, $matches)) {
873
-            $year = $matches[0];
874
-            // ten remove that from the month string as well as any spaces
875
-            $month = trim(str_replace($year, '', $month));
876
-            // add a space before the year
877
-            $year = " {$year}";
878
-        }
879
-        // return timestamp for something like "February 1 2017"
880
-        return strtotime("{$month} 1{$year}");
881
-    }
848
+	/**
849
+	 * So PHP does this awesome thing where if you are trying to get a timestamp
850
+	 * for a month using a string like "February" or "February 2017",
851
+	 * and you don't specify a day as part of your string,
852
+	 * then PHP will use whatever the current day of the month is.
853
+	 * IF the current day of the month happens to be the 30th or 31st,
854
+	 * then PHP gets really confused by a date like February 30,
855
+	 * so instead of saying
856
+	 *      "Hey February only has 28 days (this year)...
857
+	 *      ...you must have meant the last day of the month!"
858
+	 * PHP does the next most logical thing, and bumps the date up to March 2nd,
859
+	 * because someone requesting February 30th obviously meant March 1st!
860
+	 * The way around this is to always set the day to the first,
861
+	 * so that the month will stay on the month you wanted.
862
+	 * this method will add that "1" into your date regardless of the format.
863
+	 *
864
+	 * @param string $month
865
+	 * @return string
866
+	 */
867
+	public static function first_of_month_timestamp($month = '')
868
+	{
869
+		$month = (string) $month;
870
+		$year  = '';
871
+		// check if the incoming string has a year in it or not
872
+		if (preg_match('/\b\d{4}\b/', $month, $matches)) {
873
+			$year = $matches[0];
874
+			// ten remove that from the month string as well as any spaces
875
+			$month = trim(str_replace($year, '', $month));
876
+			// add a space before the year
877
+			$year = " {$year}";
878
+		}
879
+		// return timestamp for something like "February 1 2017"
880
+		return strtotime("{$month} 1{$year}");
881
+	}
882 882
 
883 883
 
884
-    /**
885
-     * This simply returns the timestamp for tomorrow (midnight next day) in this sites timezone.  So it may be midnight
886
-     * for this sites timezone, but the timestamp could be some other time GMT.
887
-     */
888
-    public static function tomorrow()
889
-    {
890
-        // The multiplication of -1 ensures that we switch positive offsets to negative and negative offsets to positive
891
-        // before adding to the timestamp.  Why? Because we want tomorrow to be for midnight the next day in THIS timezone
892
-        // not an offset from midnight in UTC.  So if we're starting with UTC 00:00:00, then we want to make sure the
893
-        // final timestamp is equivalent to midnight in this timezone as represented in GMT.
894
-        return strtotime('tomorrow') + (self::get_site_timezone_gmt_offset() * -1);
895
-    }
884
+	/**
885
+	 * This simply returns the timestamp for tomorrow (midnight next day) in this sites timezone.  So it may be midnight
886
+	 * for this sites timezone, but the timestamp could be some other time GMT.
887
+	 */
888
+	public static function tomorrow()
889
+	{
890
+		// The multiplication of -1 ensures that we switch positive offsets to negative and negative offsets to positive
891
+		// before adding to the timestamp.  Why? Because we want tomorrow to be for midnight the next day in THIS timezone
892
+		// not an offset from midnight in UTC.  So if we're starting with UTC 00:00:00, then we want to make sure the
893
+		// final timestamp is equivalent to midnight in this timezone as represented in GMT.
894
+		return strtotime('tomorrow') + (self::get_site_timezone_gmt_offset() * -1);
895
+	}
896 896
 
897 897
 
898
-    /**
899
-     * **
900
-     * Gives a nicely-formatted list of timezone strings.
901
-     * Copied from the core wp function by the same name so we could customize to remove UTC offsets.
902
-     *
903
-     * @since     4.9.40.rc.008
904
-     * @staticvar bool $mo_loaded
905
-     * @staticvar string $locale_loaded
906
-     * @param string $selected_zone Selected timezone.
907
-     * @param string $locale        Optional. Locale to load the timezones in. Default current site locale.
908
-     * @return string
909
-     */
910
-    public static function wp_timezone_choice($selected_zone, $locale = null)
911
-    {
912
-        static $mo_loaded = false, $locale_loaded = null;
913
-        $continents = array(
914
-            'Africa',
915
-            'America',
916
-            'Antarctica',
917
-            'Arctic',
918
-            'Asia',
919
-            'Atlantic',
920
-            'Australia',
921
-            'Europe',
922
-            'Indian',
923
-            'Pacific',
924
-        );
925
-        // Load translations for continents and cities.
926
-        if (! $mo_loaded || $locale !== $locale_loaded) {
927
-            $locale_loaded = $locale ? $locale : get_locale();
928
-            $mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
929
-            unload_textdomain('continents-cities');
930
-            load_textdomain('continents-cities', $mofile);
931
-            $mo_loaded = true;
932
-        }
933
-        $zone_data = array();
934
-        foreach (timezone_identifiers_list() as $zone) {
935
-            $zone = explode('/', $zone);
936
-            if (! in_array($zone[0], $continents, true)) {
937
-                continue;
938
-            }
939
-            // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
940
-            $exists      = array(
941
-                0 => isset($zone[0]) && $zone[0],
942
-                1 => isset($zone[1]) && $zone[1],
943
-                2 => isset($zone[2]) && $zone[2],
944
-            );
945
-            $exists[3]   = $exists[0] && $zone[0] !== 'Etc';
946
-            $exists[4]   = $exists[1] && $exists[3];
947
-            $exists[5]   = $exists[2] && $exists[3];
948
-            // phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
949
-            // phpcs:disable WordPress.WP.I18n.TextDomainMismatch
950
-            // disabled because this code is copied from WordPress and is a WordPress domain
951
-            $zone_data[] = array(
952
-                'continent'   => $exists[0] ? $zone[0] : '',
953
-                'city'        => $exists[1] ? $zone[1] : '',
954
-                'subcity'     => $exists[2] ? $zone[2] : '',
955
-                't_continent' => $exists[3]
956
-                    ? translate(str_replace('_', ' ', $zone[0]), 'continents-cities')
957
-                    : '',
958
-                't_city'      => $exists[4]
959
-                    ? translate(str_replace('_', ' ', $zone[1]), 'continents-cities')
960
-                    : '',
961
-                't_subcity'   => $exists[5]
962
-                    ? translate(str_replace('_', ' ', $zone[2]), 'continents-cities')
963
-                    : '',
964
-            );
965
-            // phpcs:enable
966
-        }
967
-        usort($zone_data, '_wp_timezone_choice_usort_callback');
968
-        $structure = array();
969
-        if (empty($selected_zone)) {
970
-            $structure[] = '<option selected="selected" value="">' . esc_html__('Select a city', 'event_espresso') . '</option>';
971
-        }
972
-        foreach ($zone_data as $key => $zone) {
973
-            // Build value in an array to join later
974
-            $value = array($zone['continent']);
975
-            if (empty($zone['city'])) {
976
-                // It's at the continent level (generally won't happen)
977
-                $display = $zone['t_continent'];
978
-            } else {
979
-                // It's inside a continent group
980
-                // Continent optgroup
981
-                if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
982
-                    $label       = $zone['t_continent'];
983
-                    $structure[] = '<optgroup label="' . esc_attr($label) . '">';
984
-                }
985
-                // Add the city to the value
986
-                $value[] = $zone['city'];
987
-                $display = $zone['t_city'];
988
-                if (! empty($zone['subcity'])) {
989
-                    // Add the subcity to the value
990
-                    $value[] = $zone['subcity'];
991
-                    $display .= ' - ' . $zone['t_subcity'];
992
-                }
993
-            }
994
-            // Build the value
995
-            $value       = implode('/', $value);
996
-            $selected    = $value === $selected_zone ? ' selected="selected"' : '';
997
-            $structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
998
-                           . esc_html($display)
999
-                           . '</option>';
1000
-            // Close continent optgroup
1001
-            if (
1002
-                ! empty($zone['city'])
1003
-                && (
1004
-                    ! isset($zone_data[ $key + 1 ])
1005
-                    || (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1006
-                )
1007
-            ) {
1008
-                $structure[] = '</optgroup>';
1009
-            }
1010
-        }
1011
-        return implode("\n", $structure);
1012
-    }
898
+	/**
899
+	 * **
900
+	 * Gives a nicely-formatted list of timezone strings.
901
+	 * Copied from the core wp function by the same name so we could customize to remove UTC offsets.
902
+	 *
903
+	 * @since     4.9.40.rc.008
904
+	 * @staticvar bool $mo_loaded
905
+	 * @staticvar string $locale_loaded
906
+	 * @param string $selected_zone Selected timezone.
907
+	 * @param string $locale        Optional. Locale to load the timezones in. Default current site locale.
908
+	 * @return string
909
+	 */
910
+	public static function wp_timezone_choice($selected_zone, $locale = null)
911
+	{
912
+		static $mo_loaded = false, $locale_loaded = null;
913
+		$continents = array(
914
+			'Africa',
915
+			'America',
916
+			'Antarctica',
917
+			'Arctic',
918
+			'Asia',
919
+			'Atlantic',
920
+			'Australia',
921
+			'Europe',
922
+			'Indian',
923
+			'Pacific',
924
+		);
925
+		// Load translations for continents and cities.
926
+		if (! $mo_loaded || $locale !== $locale_loaded) {
927
+			$locale_loaded = $locale ? $locale : get_locale();
928
+			$mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
929
+			unload_textdomain('continents-cities');
930
+			load_textdomain('continents-cities', $mofile);
931
+			$mo_loaded = true;
932
+		}
933
+		$zone_data = array();
934
+		foreach (timezone_identifiers_list() as $zone) {
935
+			$zone = explode('/', $zone);
936
+			if (! in_array($zone[0], $continents, true)) {
937
+				continue;
938
+			}
939
+			// This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
940
+			$exists      = array(
941
+				0 => isset($zone[0]) && $zone[0],
942
+				1 => isset($zone[1]) && $zone[1],
943
+				2 => isset($zone[2]) && $zone[2],
944
+			);
945
+			$exists[3]   = $exists[0] && $zone[0] !== 'Etc';
946
+			$exists[4]   = $exists[1] && $exists[3];
947
+			$exists[5]   = $exists[2] && $exists[3];
948
+			// phpcs:disable WordPress.WP.I18n.NonSingularStringLiteralText
949
+			// phpcs:disable WordPress.WP.I18n.TextDomainMismatch
950
+			// disabled because this code is copied from WordPress and is a WordPress domain
951
+			$zone_data[] = array(
952
+				'continent'   => $exists[0] ? $zone[0] : '',
953
+				'city'        => $exists[1] ? $zone[1] : '',
954
+				'subcity'     => $exists[2] ? $zone[2] : '',
955
+				't_continent' => $exists[3]
956
+					? translate(str_replace('_', ' ', $zone[0]), 'continents-cities')
957
+					: '',
958
+				't_city'      => $exists[4]
959
+					? translate(str_replace('_', ' ', $zone[1]), 'continents-cities')
960
+					: '',
961
+				't_subcity'   => $exists[5]
962
+					? translate(str_replace('_', ' ', $zone[2]), 'continents-cities')
963
+					: '',
964
+			);
965
+			// phpcs:enable
966
+		}
967
+		usort($zone_data, '_wp_timezone_choice_usort_callback');
968
+		$structure = array();
969
+		if (empty($selected_zone)) {
970
+			$structure[] = '<option selected="selected" value="">' . esc_html__('Select a city', 'event_espresso') . '</option>';
971
+		}
972
+		foreach ($zone_data as $key => $zone) {
973
+			// Build value in an array to join later
974
+			$value = array($zone['continent']);
975
+			if (empty($zone['city'])) {
976
+				// It's at the continent level (generally won't happen)
977
+				$display = $zone['t_continent'];
978
+			} else {
979
+				// It's inside a continent group
980
+				// Continent optgroup
981
+				if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
982
+					$label       = $zone['t_continent'];
983
+					$structure[] = '<optgroup label="' . esc_attr($label) . '">';
984
+				}
985
+				// Add the city to the value
986
+				$value[] = $zone['city'];
987
+				$display = $zone['t_city'];
988
+				if (! empty($zone['subcity'])) {
989
+					// Add the subcity to the value
990
+					$value[] = $zone['subcity'];
991
+					$display .= ' - ' . $zone['t_subcity'];
992
+				}
993
+			}
994
+			// Build the value
995
+			$value       = implode('/', $value);
996
+			$selected    = $value === $selected_zone ? ' selected="selected"' : '';
997
+			$structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
998
+						   . esc_html($display)
999
+						   . '</option>';
1000
+			// Close continent optgroup
1001
+			if (
1002
+				! empty($zone['city'])
1003
+				&& (
1004
+					! isset($zone_data[ $key + 1 ])
1005
+					|| (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1006
+				)
1007
+			) {
1008
+				$structure[] = '</optgroup>';
1009
+			}
1010
+		}
1011
+		return implode("\n", $structure);
1012
+	}
1013 1013
 
1014 1014
 
1015
-    /**
1016
-     * Shim for the WP function `get_user_locale` that was added in WordPress 4.7.0
1017
-     *
1018
-     * @param int|WP_User $user_id
1019
-     * @return string
1020
-     */
1021
-    public static function get_user_locale($user_id = 0)
1022
-    {
1023
-        if (function_exists('get_user_locale')) {
1024
-            return get_user_locale($user_id);
1025
-        }
1026
-        return get_locale();
1027
-    }
1015
+	/**
1016
+	 * Shim for the WP function `get_user_locale` that was added in WordPress 4.7.0
1017
+	 *
1018
+	 * @param int|WP_User $user_id
1019
+	 * @return string
1020
+	 */
1021
+	public static function get_user_locale($user_id = 0)
1022
+	{
1023
+		if (function_exists('get_user_locale')) {
1024
+			return get_user_locale($user_id);
1025
+		}
1026
+		return get_locale();
1027
+	}
1028 1028
 
1029 1029
 
1030
-    /**
1031
-     * Return the appropriate helper adapter for DTT related things.
1032
-     *
1033
-     * @return HelperInterface
1034
-     * @throws InvalidArgumentException
1035
-     * @throws InvalidDataTypeException
1036
-     * @throws InvalidInterfaceException
1037
-     */
1038
-    private static function getHelperAdapter()
1039
-    {
1040
-        $dtt_helper_fqcn = PHP_VERSION_ID < 50600
1041
-            ? 'EventEspresso\core\services\helpers\datetime\PhpCompatLessFiveSixHelper'
1042
-            : 'EventEspresso\core\services\helpers\datetime\PhpCompatGreaterFiveSixHelper';
1043
-        return LoaderFactory::getLoader()->getShared($dtt_helper_fqcn);
1044
-    }
1030
+	/**
1031
+	 * Return the appropriate helper adapter for DTT related things.
1032
+	 *
1033
+	 * @return HelperInterface
1034
+	 * @throws InvalidArgumentException
1035
+	 * @throws InvalidDataTypeException
1036
+	 * @throws InvalidInterfaceException
1037
+	 */
1038
+	private static function getHelperAdapter()
1039
+	{
1040
+		$dtt_helper_fqcn = PHP_VERSION_ID < 50600
1041
+			? 'EventEspresso\core\services\helpers\datetime\PhpCompatLessFiveSixHelper'
1042
+			: 'EventEspresso\core\services\helpers\datetime\PhpCompatGreaterFiveSixHelper';
1043
+		return LoaderFactory::getLoader()->getShared($dtt_helper_fqcn);
1044
+	}
1045 1045
 
1046 1046
 
1047
-    /**
1048
-     * Helper function for setting the timezone on a DateTime object.
1049
-     * This is implemented to standardize a workaround for a PHP bug outlined in
1050
-     * https://events.codebasehq.com/projects/event-espresso/tickets/11407 and
1051
-     * https://events.codebasehq.com/projects/event-espresso/tickets/11233
1052
-     *
1053
-     * @param DateTime     $datetime
1054
-     * @param DateTimeZone $timezone
1055
-     */
1056
-    public static function setTimezone(DateTime $datetime, DateTimeZone $timezone)
1057
-    {
1058
-        $datetime->setTimezone($timezone);
1059
-        $datetime->getTimestamp();
1060
-    }
1047
+	/**
1048
+	 * Helper function for setting the timezone on a DateTime object.
1049
+	 * This is implemented to standardize a workaround for a PHP bug outlined in
1050
+	 * https://events.codebasehq.com/projects/event-espresso/tickets/11407 and
1051
+	 * https://events.codebasehq.com/projects/event-espresso/tickets/11233
1052
+	 *
1053
+	 * @param DateTime     $datetime
1054
+	 * @param DateTimeZone $timezone
1055
+	 */
1056
+	public static function setTimezone(DateTime $datetime, DateTimeZone $timezone)
1057
+	{
1058
+		$datetime->setTimezone($timezone);
1059
+		$datetime->getTimestamp();
1060
+	}
1061 1061
 }
Please login to merge, or discard this patch.
Spacing   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
      */
132 132
     public static function get_timezone_string_from_abbreviations_list($gmt_offset = 0, $coerce = true)
133 133
     {
134
-        $gmt_offset =  (int) $gmt_offset;
134
+        $gmt_offset = (int) $gmt_offset;
135 135
         /** @var array[] $abbreviations */
136 136
         $abbreviations = DateTimeZone::listAbbreviations();
137 137
         foreach ($abbreviations as $abbreviation) {
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
      */
327 327
     protected static function _modify_datetime_object(DateTime $DateTime, $period = 'years', $value = 1, $operand = '+')
328 328
     {
329
-        if (! $DateTime instanceof DateTime) {
329
+        if ( ! $DateTime instanceof DateTime) {
330 330
             throw new EE_Error(
331 331
                 sprintf(
332 332
                     esc_html__('Expected a PHP DateTime object, but instead received %1$s', 'event_espresso'),
@@ -336,25 +336,25 @@  discard block
 block discarded – undo
336 336
         }
337 337
         switch ($period) {
338 338
             case 'years':
339
-                $value = 'P' . $value . 'Y';
339
+                $value = 'P'.$value.'Y';
340 340
                 break;
341 341
             case 'months':
342
-                $value = 'P' . $value . 'M';
342
+                $value = 'P'.$value.'M';
343 343
                 break;
344 344
             case 'weeks':
345
-                $value = 'P' . $value . 'W';
345
+                $value = 'P'.$value.'W';
346 346
                 break;
347 347
             case 'days':
348
-                $value = 'P' . $value . 'D';
348
+                $value = 'P'.$value.'D';
349 349
                 break;
350 350
             case 'hours':
351
-                $value = 'PT' . $value . 'H';
351
+                $value = 'PT'.$value.'H';
352 352
                 break;
353 353
             case 'minutes':
354
-                $value = 'PT' . $value . 'M';
354
+                $value = 'PT'.$value.'M';
355 355
                 break;
356 356
             case 'seconds':
357
-                $value = 'PT' . $value . 'S';
357
+                $value = 'PT'.$value.'S';
358 358
                 break;
359 359
         }
360 360
         switch ($operand) {
@@ -382,7 +382,7 @@  discard block
 block discarded – undo
382 382
      */
383 383
     protected static function _modify_timestamp($timestamp, $period = 'years', $value = 1, $operand = '+')
384 384
     {
385
-        if (! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
385
+        if ( ! preg_match(EE_Datetime_Field::unix_timestamp_regex, $timestamp)) {
386 386
             throw new EE_Error(
387 387
                 sprintf(
388 388
                     esc_html__('Expected a Unix timestamp, but instead received %1$s', 'event_espresso'),
@@ -495,7 +495,7 @@  discard block
 block discarded – undo
495 495
                 'date' => $date_format['js'],
496 496
                 'time' => $time_format['js'],
497 497
             ),
498
-            'moment' => $date_format['moment'] . ' ' . $time_format['moment'],
498
+            'moment' => $date_format['moment'].' '.$time_format['moment'],
499 499
             'moment_split' => array(
500 500
                 'date' => $date_format['moment'],
501 501
                 'time' => $time_format['moment']
@@ -518,7 +518,7 @@  discard block
 block discarded – undo
518 518
          *
519 519
          * @var array
520 520
          */
521
-        $symbols_map          = array(
521
+        $symbols_map = array(
522 522
             // Day
523 523
             // 01
524 524
             'd' => array(
@@ -670,26 +670,26 @@  discard block
 block discarded – undo
670 670
         $escaping             = false;
671 671
         $format_string_length = strlen($format_string);
672 672
         for ($i = 0; $i < $format_string_length; $i++) {
673
-            $char = $format_string[ $i ];
673
+            $char = $format_string[$i];
674 674
             if ($char === '\\') { // PHP date format escaping character
675 675
                 $i++;
676 676
                 if ($escaping) {
677
-                    $jquery_ui_format .= $format_string[ $i ];
678
-                    $moment_format    .= $format_string[ $i ];
677
+                    $jquery_ui_format .= $format_string[$i];
678
+                    $moment_format    .= $format_string[$i];
679 679
                 } else {
680
-                    $jquery_ui_format .= '\'' . $format_string[ $i ];
681
-                    $moment_format    .= $format_string[ $i ];
680
+                    $jquery_ui_format .= '\''.$format_string[$i];
681
+                    $moment_format    .= $format_string[$i];
682 682
                 }
683 683
                 $escaping = true;
684 684
             } else {
685 685
                 if ($escaping) {
686 686
                     $jquery_ui_format .= "'";
687 687
                     $moment_format    .= "'";
688
-                    $escaping         = false;
688
+                    $escaping = false;
689 689
                 }
690
-                if (isset($symbols_map[ $char ])) {
691
-                    $jquery_ui_format .= $symbols_map[ $char ]['js'];
692
-                    $moment_format    .= $symbols_map[ $char ]['moment'];
690
+                if (isset($symbols_map[$char])) {
691
+                    $jquery_ui_format .= $symbols_map[$char]['js'];
692
+                    $moment_format    .= $symbols_map[$char]['moment'];
693 693
                 } else {
694 694
                     $jquery_ui_format .= $char;
695 695
                     $moment_format    .= $char;
@@ -747,7 +747,7 @@  discard block
 block discarded – undo
747 747
     {
748 748
 
749 749
         if (
750
-            (! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
750
+            ( ! $date_1 instanceof DateTime || ! $date_2 instanceof DateTime)
751 751
             || ($date_1->format(EE_Datetime_Field::mysql_time_format) !== '00:00:00'
752 752
                 || $date_2->format(
753 753
                     EE_Datetime_Field::mysql_time_format
@@ -783,8 +783,8 @@  discard block
 block discarded – undo
783 783
             ? $DateTimeZone->getOffset(new DateTime('now')) / HOUR_IN_SECONDS
784 784
             : (float) get_option('gmt_offset');
785 785
         $query_interval = $offset < 0
786
-            ? 'DATE_SUB(' . $field_for_interval . ', INTERVAL ' . $offset * -1 . ' HOUR)'
787
-            : 'DATE_ADD(' . $field_for_interval . ', INTERVAL ' . $offset . ' HOUR)';
786
+            ? 'DATE_SUB('.$field_for_interval.', INTERVAL '.$offset * -1.' HOUR)'
787
+            : 'DATE_ADD('.$field_for_interval.', INTERVAL '.$offset.' HOUR)';
788 788
         return $query_interval;
789 789
     }
790 790
 
@@ -801,16 +801,16 @@  discard block
 block discarded – undo
801 801
     public static function get_timezone_string_for_display()
802 802
     {
803 803
         $pretty_timezone = apply_filters('FHEE__EEH_DTT_Helper__get_timezone_string_for_display', '');
804
-        if (! empty($pretty_timezone)) {
804
+        if ( ! empty($pretty_timezone)) {
805 805
             return esc_html($pretty_timezone);
806 806
         }
807 807
         $timezone_string = get_option('timezone_string');
808 808
         if ($timezone_string) {
809 809
             static $mo_loaded = false;
810 810
             // Load translations for continents and cities just like wp_timezone_choice does
811
-            if (! $mo_loaded) {
811
+            if ( ! $mo_loaded) {
812 812
                 $locale = get_locale();
813
-                $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
813
+                $mofile = WP_LANG_DIR.'/continents-cities-'.$locale.'.mo';
814 814
                 load_textdomain('continents-cities', $mofile);
815 815
                 $mo_loaded = true;
816 816
             }
@@ -837,10 +837,10 @@  discard block
 block discarded – undo
837 837
         } else {
838 838
             // convert the part after the decimal, eg "5" (from x.5) or "25" (from x.25)
839 839
             // to minutes, eg 30 or 15, respectively
840
-            $hour_fraction = (float) ('0.' . $parts[1]);
840
+            $hour_fraction = (float) ('0.'.$parts[1]);
841 841
             $parts[1]      = (string) $hour_fraction * 60;
842 842
         }
843
-        return sprintf(esc_html__('UTC%1$s', 'event_espresso'), $prefix . implode(':', $parts));
843
+        return sprintf(esc_html__('UTC%1$s', 'event_espresso'), $prefix.implode(':', $parts));
844 844
     }
845 845
 
846 846
 
@@ -923,9 +923,9 @@  discard block
 block discarded – undo
923 923
             'Pacific',
924 924
         );
925 925
         // Load translations for continents and cities.
926
-        if (! $mo_loaded || $locale !== $locale_loaded) {
926
+        if ( ! $mo_loaded || $locale !== $locale_loaded) {
927 927
             $locale_loaded = $locale ? $locale : get_locale();
928
-            $mofile        = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
928
+            $mofile        = WP_LANG_DIR.'/continents-cities-'.$locale_loaded.'.mo';
929 929
             unload_textdomain('continents-cities');
930 930
             load_textdomain('continents-cities', $mofile);
931 931
             $mo_loaded = true;
@@ -933,11 +933,11 @@  discard block
 block discarded – undo
933 933
         $zone_data = array();
934 934
         foreach (timezone_identifiers_list() as $zone) {
935 935
             $zone = explode('/', $zone);
936
-            if (! in_array($zone[0], $continents, true)) {
936
+            if ( ! in_array($zone[0], $continents, true)) {
937 937
                 continue;
938 938
             }
939 939
             // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
940
-            $exists      = array(
940
+            $exists = array(
941 941
                 0 => isset($zone[0]) && $zone[0],
942 942
                 1 => isset($zone[1]) && $zone[1],
943 943
                 2 => isset($zone[2]) && $zone[2],
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
         usort($zone_data, '_wp_timezone_choice_usort_callback');
968 968
         $structure = array();
969 969
         if (empty($selected_zone)) {
970
-            $structure[] = '<option selected="selected" value="">' . esc_html__('Select a city', 'event_espresso') . '</option>';
970
+            $structure[] = '<option selected="selected" value="">'.esc_html__('Select a city', 'event_espresso').'</option>';
971 971
         }
972 972
         foreach ($zone_data as $key => $zone) {
973 973
             // Build value in an array to join later
@@ -978,31 +978,31 @@  discard block
 block discarded – undo
978 978
             } else {
979 979
                 // It's inside a continent group
980 980
                 // Continent optgroup
981
-                if (! isset($zone_data[ $key - 1 ]) || $zone_data[ $key - 1 ]['continent'] !== $zone['continent']) {
981
+                if ( ! isset($zone_data[$key - 1]) || $zone_data[$key - 1]['continent'] !== $zone['continent']) {
982 982
                     $label       = $zone['t_continent'];
983
-                    $structure[] = '<optgroup label="' . esc_attr($label) . '">';
983
+                    $structure[] = '<optgroup label="'.esc_attr($label).'">';
984 984
                 }
985 985
                 // Add the city to the value
986 986
                 $value[] = $zone['city'];
987 987
                 $display = $zone['t_city'];
988
-                if (! empty($zone['subcity'])) {
988
+                if ( ! empty($zone['subcity'])) {
989 989
                     // Add the subcity to the value
990 990
                     $value[] = $zone['subcity'];
991
-                    $display .= ' - ' . $zone['t_subcity'];
991
+                    $display .= ' - '.$zone['t_subcity'];
992 992
                 }
993 993
             }
994 994
             // Build the value
995 995
             $value       = implode('/', $value);
996 996
             $selected    = $value === $selected_zone ? ' selected="selected"' : '';
997
-            $structure[] = '<option value="' . esc_attr($value) . '"' . $selected . '>'
997
+            $structure[] = '<option value="'.esc_attr($value).'"'.$selected.'>'
998 998
                            . esc_html($display)
999 999
                            . '</option>';
1000 1000
             // Close continent optgroup
1001 1001
             if (
1002 1002
                 ! empty($zone['city'])
1003 1003
                 && (
1004
-                    ! isset($zone_data[ $key + 1 ])
1005
-                    || (isset($zone_data[ $key + 1 ]) && $zone_data[ $key + 1 ]['continent'] !== $zone['continent'])
1004
+                    ! isset($zone_data[$key + 1])
1005
+                    || (isset($zone_data[$key + 1]) && $zone_data[$key + 1]['continent'] !== $zone['continent'])
1006 1006
                 )
1007 1007
             ) {
1008 1008
                 $structure[] = '</optgroup>';
Please login to merge, or discard this patch.
core/helpers/EEH_Sideloader.helper.php 2 patches
Indentation   +324 added lines, -324 removed lines patch added patch discarded remove patch
@@ -12,328 +12,328 @@
 block discarded – undo
12 12
 class EEH_Sideloader extends EEH_Base
13 13
 {
14 14
 
15
-    /**
16
-     * @since   4.1.0
17
-     * @var     string
18
-     */
19
-    private $_upload_to;
20
-
21
-    /**
22
-     * @since   4.10.5.p
23
-     * @var     string
24
-     */
25
-    private $_download_from;
26
-
27
-    /**
28
-     * @since   4.1.0
29
-     * @var     string
30
-     */
31
-    private $_permissions;
32
-
33
-    /**
34
-     * @since   4.1.0
35
-     * @var     string
36
-     */
37
-    private $_new_file_name;
38
-
39
-
40
-    /**
41
-     * constructor allows the user to set the properties on the sideloader on construct.  However, there are also setters for doing so.
42
-     *
43
-     * @since 4.1.0
44
-     * @param array $init array fo initializing the sideloader if keys match the properties.
45
-     */
46
-    public function __construct($init = array())
47
-    {
48
-        $this->_init($init);
49
-    }
50
-
51
-
52
-    /**
53
-     * sets the properties for class either to defaults or using incoming initialization array
54
-     *
55
-     * @since 4.1.0
56
-     * @param  array  $init array on init (keys match properties others ignored)
57
-     * @return void
58
-     */
59
-    private function _init($init)
60
-    {
61
-        $defaults = array(
62
-            '_upload_to' => $this->_get_wp_uploads_dir(),
63
-            '_download_from' => '',
64
-            '_permissions' => 0644,
65
-            '_new_file_name' => 'EE_Sideloader_' . uniqid() . '.default'
66
-            );
67
-
68
-        $props = array_merge($defaults, $init);
69
-
70
-        foreach ($props as $property => $val) {
71
-            $setter = 'set' . $property;
72
-            if (method_exists($this, $setter)) {
73
-                $this->$setter($val);
74
-            } else {
75
-                 // No setter found.
76
-                EE_Error::add_error(
77
-                    sprintf(
78
-                        esc_html__(
79
-                            'EEH_Sideloader::%1$s not found. There is no setter for the %2$s property.',
80
-                            'event_espresso'
81
-                        ),
82
-                        $setter,
83
-                        $property
84
-                    ),
85
-                    __FILE__,
86
-                    __FUNCTION__,
87
-                    __LINE__
88
-                );
89
-            }
90
-        }
91
-
92
-        // make sure we include the required wp file for needed functions
93
-        require_once(ABSPATH . 'wp-admin/includes/file.php');
94
-    }
95
-
96
-
97
-    // utilities
98
-
99
-
100
-    /**
101
-     * @since 4.1.0
102
-     * @return void
103
-     */
104
-    private function _get_wp_uploads_dir()
105
-    {
106
-    }
107
-
108
-    // setters
109
-
110
-
111
-    /**
112
-     * sets the _upload_to property to the directory to upload to.
113
-     *
114
-     * @since 4.1.0
115
-     * @param $upload_to_folder
116
-     * @return void
117
-     */
118
-    public function set_upload_to($upload_to_folder)
119
-    {
120
-        $this->_upload_to = $upload_to_folder;
121
-    }
122
-
123
-
124
-    /**
125
-     * sets the _download_from property to the location we should download the file from.
126
-     *
127
-     * @since 4.10.5.p
128
-     * @param string $download_from The full path to the file we should sideload.
129
-     * @return void
130
-     */
131
-    public function set_download_from($download_from)
132
-    {
133
-        $this->_download_from = $download_from;
134
-    }
135
-
136
-
137
-    /**
138
-     * sets the _permissions property used on the sideloaded file.
139
-     *
140
-     * @since 4.1.0
141
-     * @param int $permissions
142
-     * @return void
143
-     */
144
-    public function set_permissions($permissions)
145
-    {
146
-        $this->_permissions = $permissions;
147
-    }
148
-
149
-
150
-    /**
151
-     * sets the _new_file_name property used on the sideloaded file.
152
-     *
153
-     * @since 4.1.0
154
-     * @param string $new_file_name
155
-     * @return void
156
-     */
157
-    public function set_new_file_name($new_file_name)
158
-    {
159
-        $this->_new_file_name = $new_file_name;
160
-    }
161
-
162
-    // getters
163
-
164
-
165
-    /**
166
-     * @since 4.1.0
167
-     * @return string
168
-     */
169
-    public function get_upload_to()
170
-    {
171
-        return $this->_upload_to;
172
-    }
173
-
174
-
175
-    /**
176
-     * @since 4.10.5.p
177
-     * @return string
178
-     */
179
-    public function get_download_from()
180
-    {
181
-        return $this->_download_from;
182
-    }
183
-
184
-
185
-    /**
186
-     * @since 4.1.0
187
-     * @return int
188
-     */
189
-    public function get_permissions()
190
-    {
191
-        return $this->_permissions;
192
-    }
193
-
194
-
195
-    /**
196
-     * @since 4.1.0
197
-     * @return string
198
-     */
199
-    public function get_new_file_name()
200
-    {
201
-        return $this->_new_file_name;
202
-    }
203
-
204
-
205
-    // upload methods
206
-
207
-
208
-    /**
209
-     * Downloads the file using the WordPress HTTP API.
210
-     *
211
-     * @since 4.1.0
212
-     * @return bool
213
-     */
214
-    public function sideload()
215
-    {
216
-        // setup temp dir
217
-        $temp_file = wp_tempnam($this->_download_from);
218
-
219
-        if (!$temp_file) {
220
-            EE_Error::add_error(
221
-                esc_html__('Something went wrong with the upload.  Unable to create a tmp file for the uploaded file on the server', 'event_espresso'),
222
-                __FILE__,
223
-                __FUNCTION__,
224
-                __LINE__
225
-            );
226
-            return false;
227
-        }
228
-
229
-        do_action('AHEE__EEH_Sideloader__sideload__before', $this, $temp_file);
230
-
231
-        $wp_remote_args = apply_filters('FHEE__EEH_Sideloader__sideload__wp_remote_args', array( 'timeout' => 500, 'stream' => true, 'filename' => $temp_file ), $this, $temp_file);
232
-
233
-        $response = wp_safe_remote_get($this->_download_from, $wp_remote_args);
234
-
235
-        if (is_wp_error($response) || 200 != wp_remote_retrieve_response_code($response)) {
236
-            unlink($temp_file);
237
-            if (defined('WP_DEBUG') && WP_DEBUG) {
238
-                EE_Error::add_error(
239
-                    sprintf(
240
-                        esc_html__('Unable to upload the file. Either the path given to download from is incorrect, or something else happened. Here is the path given: %s', 'event_espresso'),
241
-                        $this->_download_from
242
-                    ),
243
-                    __FILE__,
244
-                    __FUNCTION__,
245
-                    __LINE__
246
-                );
247
-            }
248
-            return false;
249
-        }
250
-
251
-        // possible md5 check
252
-        $content_md5 = wp_remote_retrieve_header($response, 'content-md5');
253
-        if ($content_md5) {
254
-            $md5_check = verify_file_md5($temp_file, $content_md5);
255
-            if (is_wp_error($md5_check)) {
256
-                unlink($temp_file);
257
-                EE_Error::add_error(
258
-                    $md5_check->get_error_message(),
259
-                    __FILE__,
260
-                    __FUNCTION__,
261
-                    __LINE__
262
-                );
263
-                return false;
264
-            }
265
-        }
266
-
267
-        $file = $temp_file;
268
-
269
-        // now we have the file, let's get it in the right directory with the right name.
270
-        $path = apply_filters('FHEE__EEH_Sideloader__sideload__new_path', $this->_upload_to . $this->_new_file_name, $this);
271
-
272
-        // move file in
273
-        if (false === @ rename($file, $path)) {
274
-            unlink($temp_file);
275
-            EE_Error::add_error(
276
-                sprintf(
277
-                    esc_html__('Unable to move the file to new location (possible permissions errors). This is the path the class attempted to move the file to: %s', 'event_espresso'),
278
-                    $path
279
-                ),
280
-                __FILE__,
281
-                __FUNCTION__,
282
-                __LINE__
283
-            );
284
-            return false;
285
-        }
286
-
287
-        // set permissions
288
-        $permissions = apply_filters('FHEE__EEH_Sideloader__sideload__permissions_applied', $this->_permissions, $this);
289
-        chmod($path, $permissions);
290
-
291
-        // that's it.  let's allow for actions after file uploaded.
292
-        do_action('AHEE__EE_Sideloader__sideload_after', $this, $path);
293
-
294
-        // unlink tempfile
295
-        @unlink($temp_file);
296
-        return true;
297
-    }
298
-
299
-    // deprecated
300
-
301
-    /**
302
-     * sets the _upload_from property to the location we should download the file from.
303
-     *
304
-     * @param string $upload_from The full path to the file we should sideload.
305
-     * @return void
306
-     * @deprecated since version 4.10.5.p
307
-     */
308
-    public function set_upload_from($upload_from)
309
-    {
310
-        EE_Error::doing_it_wrong(
311
-            __CLASS__ . '::' . __FUNCTION__,
312
-            esc_html__(
313
-                'EEH_Sideloader::set_upload_from was renamed to EEH_Sideloader::set_download_from',
314
-                'event_espresso'
315
-            ),
316
-            '4.10.5.p'
317
-        );
318
-        $this->set_download_from($upload_from);
319
-    }
320
-
321
-
322
-    /**
323
-     * @since 4.1.0
324
-     * @return string
325
-     * @deprecated since version 4.10.5.p
326
-     */
327
-    public function get_upload_from()
328
-    {
329
-        EE_Error::doing_it_wrong(
330
-            __CLASS__ . '::' . __FUNCTION__,
331
-            esc_html__(
332
-                'EEH_Sideloader::get_upload_from was renamed to EEH_Sideloader::get_download_from',
333
-                'event_espresso'
334
-            ),
335
-            '4.10.5.p'
336
-        );
337
-        return $this->_download_from;
338
-    }
15
+	/**
16
+	 * @since   4.1.0
17
+	 * @var     string
18
+	 */
19
+	private $_upload_to;
20
+
21
+	/**
22
+	 * @since   4.10.5.p
23
+	 * @var     string
24
+	 */
25
+	private $_download_from;
26
+
27
+	/**
28
+	 * @since   4.1.0
29
+	 * @var     string
30
+	 */
31
+	private $_permissions;
32
+
33
+	/**
34
+	 * @since   4.1.0
35
+	 * @var     string
36
+	 */
37
+	private $_new_file_name;
38
+
39
+
40
+	/**
41
+	 * constructor allows the user to set the properties on the sideloader on construct.  However, there are also setters for doing so.
42
+	 *
43
+	 * @since 4.1.0
44
+	 * @param array $init array fo initializing the sideloader if keys match the properties.
45
+	 */
46
+	public function __construct($init = array())
47
+	{
48
+		$this->_init($init);
49
+	}
50
+
51
+
52
+	/**
53
+	 * sets the properties for class either to defaults or using incoming initialization array
54
+	 *
55
+	 * @since 4.1.0
56
+	 * @param  array  $init array on init (keys match properties others ignored)
57
+	 * @return void
58
+	 */
59
+	private function _init($init)
60
+	{
61
+		$defaults = array(
62
+			'_upload_to' => $this->_get_wp_uploads_dir(),
63
+			'_download_from' => '',
64
+			'_permissions' => 0644,
65
+			'_new_file_name' => 'EE_Sideloader_' . uniqid() . '.default'
66
+			);
67
+
68
+		$props = array_merge($defaults, $init);
69
+
70
+		foreach ($props as $property => $val) {
71
+			$setter = 'set' . $property;
72
+			if (method_exists($this, $setter)) {
73
+				$this->$setter($val);
74
+			} else {
75
+				 // No setter found.
76
+				EE_Error::add_error(
77
+					sprintf(
78
+						esc_html__(
79
+							'EEH_Sideloader::%1$s not found. There is no setter for the %2$s property.',
80
+							'event_espresso'
81
+						),
82
+						$setter,
83
+						$property
84
+					),
85
+					__FILE__,
86
+					__FUNCTION__,
87
+					__LINE__
88
+				);
89
+			}
90
+		}
91
+
92
+		// make sure we include the required wp file for needed functions
93
+		require_once(ABSPATH . 'wp-admin/includes/file.php');
94
+	}
95
+
96
+
97
+	// utilities
98
+
99
+
100
+	/**
101
+	 * @since 4.1.0
102
+	 * @return void
103
+	 */
104
+	private function _get_wp_uploads_dir()
105
+	{
106
+	}
107
+
108
+	// setters
109
+
110
+
111
+	/**
112
+	 * sets the _upload_to property to the directory to upload to.
113
+	 *
114
+	 * @since 4.1.0
115
+	 * @param $upload_to_folder
116
+	 * @return void
117
+	 */
118
+	public function set_upload_to($upload_to_folder)
119
+	{
120
+		$this->_upload_to = $upload_to_folder;
121
+	}
122
+
123
+
124
+	/**
125
+	 * sets the _download_from property to the location we should download the file from.
126
+	 *
127
+	 * @since 4.10.5.p
128
+	 * @param string $download_from The full path to the file we should sideload.
129
+	 * @return void
130
+	 */
131
+	public function set_download_from($download_from)
132
+	{
133
+		$this->_download_from = $download_from;
134
+	}
135
+
136
+
137
+	/**
138
+	 * sets the _permissions property used on the sideloaded file.
139
+	 *
140
+	 * @since 4.1.0
141
+	 * @param int $permissions
142
+	 * @return void
143
+	 */
144
+	public function set_permissions($permissions)
145
+	{
146
+		$this->_permissions = $permissions;
147
+	}
148
+
149
+
150
+	/**
151
+	 * sets the _new_file_name property used on the sideloaded file.
152
+	 *
153
+	 * @since 4.1.0
154
+	 * @param string $new_file_name
155
+	 * @return void
156
+	 */
157
+	public function set_new_file_name($new_file_name)
158
+	{
159
+		$this->_new_file_name = $new_file_name;
160
+	}
161
+
162
+	// getters
163
+
164
+
165
+	/**
166
+	 * @since 4.1.0
167
+	 * @return string
168
+	 */
169
+	public function get_upload_to()
170
+	{
171
+		return $this->_upload_to;
172
+	}
173
+
174
+
175
+	/**
176
+	 * @since 4.10.5.p
177
+	 * @return string
178
+	 */
179
+	public function get_download_from()
180
+	{
181
+		return $this->_download_from;
182
+	}
183
+
184
+
185
+	/**
186
+	 * @since 4.1.0
187
+	 * @return int
188
+	 */
189
+	public function get_permissions()
190
+	{
191
+		return $this->_permissions;
192
+	}
193
+
194
+
195
+	/**
196
+	 * @since 4.1.0
197
+	 * @return string
198
+	 */
199
+	public function get_new_file_name()
200
+	{
201
+		return $this->_new_file_name;
202
+	}
203
+
204
+
205
+	// upload methods
206
+
207
+
208
+	/**
209
+	 * Downloads the file using the WordPress HTTP API.
210
+	 *
211
+	 * @since 4.1.0
212
+	 * @return bool
213
+	 */
214
+	public function sideload()
215
+	{
216
+		// setup temp dir
217
+		$temp_file = wp_tempnam($this->_download_from);
218
+
219
+		if (!$temp_file) {
220
+			EE_Error::add_error(
221
+				esc_html__('Something went wrong with the upload.  Unable to create a tmp file for the uploaded file on the server', 'event_espresso'),
222
+				__FILE__,
223
+				__FUNCTION__,
224
+				__LINE__
225
+			);
226
+			return false;
227
+		}
228
+
229
+		do_action('AHEE__EEH_Sideloader__sideload__before', $this, $temp_file);
230
+
231
+		$wp_remote_args = apply_filters('FHEE__EEH_Sideloader__sideload__wp_remote_args', array( 'timeout' => 500, 'stream' => true, 'filename' => $temp_file ), $this, $temp_file);
232
+
233
+		$response = wp_safe_remote_get($this->_download_from, $wp_remote_args);
234
+
235
+		if (is_wp_error($response) || 200 != wp_remote_retrieve_response_code($response)) {
236
+			unlink($temp_file);
237
+			if (defined('WP_DEBUG') && WP_DEBUG) {
238
+				EE_Error::add_error(
239
+					sprintf(
240
+						esc_html__('Unable to upload the file. Either the path given to download from is incorrect, or something else happened. Here is the path given: %s', 'event_espresso'),
241
+						$this->_download_from
242
+					),
243
+					__FILE__,
244
+					__FUNCTION__,
245
+					__LINE__
246
+				);
247
+			}
248
+			return false;
249
+		}
250
+
251
+		// possible md5 check
252
+		$content_md5 = wp_remote_retrieve_header($response, 'content-md5');
253
+		if ($content_md5) {
254
+			$md5_check = verify_file_md5($temp_file, $content_md5);
255
+			if (is_wp_error($md5_check)) {
256
+				unlink($temp_file);
257
+				EE_Error::add_error(
258
+					$md5_check->get_error_message(),
259
+					__FILE__,
260
+					__FUNCTION__,
261
+					__LINE__
262
+				);
263
+				return false;
264
+			}
265
+		}
266
+
267
+		$file = $temp_file;
268
+
269
+		// now we have the file, let's get it in the right directory with the right name.
270
+		$path = apply_filters('FHEE__EEH_Sideloader__sideload__new_path', $this->_upload_to . $this->_new_file_name, $this);
271
+
272
+		// move file in
273
+		if (false === @ rename($file, $path)) {
274
+			unlink($temp_file);
275
+			EE_Error::add_error(
276
+				sprintf(
277
+					esc_html__('Unable to move the file to new location (possible permissions errors). This is the path the class attempted to move the file to: %s', 'event_espresso'),
278
+					$path
279
+				),
280
+				__FILE__,
281
+				__FUNCTION__,
282
+				__LINE__
283
+			);
284
+			return false;
285
+		}
286
+
287
+		// set permissions
288
+		$permissions = apply_filters('FHEE__EEH_Sideloader__sideload__permissions_applied', $this->_permissions, $this);
289
+		chmod($path, $permissions);
290
+
291
+		// that's it.  let's allow for actions after file uploaded.
292
+		do_action('AHEE__EE_Sideloader__sideload_after', $this, $path);
293
+
294
+		// unlink tempfile
295
+		@unlink($temp_file);
296
+		return true;
297
+	}
298
+
299
+	// deprecated
300
+
301
+	/**
302
+	 * sets the _upload_from property to the location we should download the file from.
303
+	 *
304
+	 * @param string $upload_from The full path to the file we should sideload.
305
+	 * @return void
306
+	 * @deprecated since version 4.10.5.p
307
+	 */
308
+	public function set_upload_from($upload_from)
309
+	{
310
+		EE_Error::doing_it_wrong(
311
+			__CLASS__ . '::' . __FUNCTION__,
312
+			esc_html__(
313
+				'EEH_Sideloader::set_upload_from was renamed to EEH_Sideloader::set_download_from',
314
+				'event_espresso'
315
+			),
316
+			'4.10.5.p'
317
+		);
318
+		$this->set_download_from($upload_from);
319
+	}
320
+
321
+
322
+	/**
323
+	 * @since 4.1.0
324
+	 * @return string
325
+	 * @deprecated since version 4.10.5.p
326
+	 */
327
+	public function get_upload_from()
328
+	{
329
+		EE_Error::doing_it_wrong(
330
+			__CLASS__ . '::' . __FUNCTION__,
331
+			esc_html__(
332
+				'EEH_Sideloader::get_upload_from was renamed to EEH_Sideloader::get_download_from',
333
+				'event_espresso'
334
+			),
335
+			'4.10.5.p'
336
+		);
337
+		return $this->_download_from;
338
+	}
339 339
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -62,13 +62,13 @@  discard block
 block discarded – undo
62 62
             '_upload_to' => $this->_get_wp_uploads_dir(),
63 63
             '_download_from' => '',
64 64
             '_permissions' => 0644,
65
-            '_new_file_name' => 'EE_Sideloader_' . uniqid() . '.default'
65
+            '_new_file_name' => 'EE_Sideloader_'.uniqid().'.default'
66 66
             );
67 67
 
68 68
         $props = array_merge($defaults, $init);
69 69
 
70 70
         foreach ($props as $property => $val) {
71
-            $setter = 'set' . $property;
71
+            $setter = 'set'.$property;
72 72
             if (method_exists($this, $setter)) {
73 73
                 $this->$setter($val);
74 74
             } else {
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
         }
91 91
 
92 92
         // make sure we include the required wp file for needed functions
93
-        require_once(ABSPATH . 'wp-admin/includes/file.php');
93
+        require_once(ABSPATH.'wp-admin/includes/file.php');
94 94
     }
95 95
 
96 96
 
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
         // setup temp dir
217 217
         $temp_file = wp_tempnam($this->_download_from);
218 218
 
219
-        if (!$temp_file) {
219
+        if ( ! $temp_file) {
220 220
             EE_Error::add_error(
221 221
                 esc_html__('Something went wrong with the upload.  Unable to create a tmp file for the uploaded file on the server', 'event_espresso'),
222 222
                 __FILE__,
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 
229 229
         do_action('AHEE__EEH_Sideloader__sideload__before', $this, $temp_file);
230 230
 
231
-        $wp_remote_args = apply_filters('FHEE__EEH_Sideloader__sideload__wp_remote_args', array( 'timeout' => 500, 'stream' => true, 'filename' => $temp_file ), $this, $temp_file);
231
+        $wp_remote_args = apply_filters('FHEE__EEH_Sideloader__sideload__wp_remote_args', array('timeout' => 500, 'stream' => true, 'filename' => $temp_file), $this, $temp_file);
232 232
 
233 233
         $response = wp_safe_remote_get($this->_download_from, $wp_remote_args);
234 234
 
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
         $file = $temp_file;
268 268
 
269 269
         // now we have the file, let's get it in the right directory with the right name.
270
-        $path = apply_filters('FHEE__EEH_Sideloader__sideload__new_path', $this->_upload_to . $this->_new_file_name, $this);
270
+        $path = apply_filters('FHEE__EEH_Sideloader__sideload__new_path', $this->_upload_to.$this->_new_file_name, $this);
271 271
 
272 272
         // move file in
273 273
         if (false === @ rename($file, $path)) {
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
     public function set_upload_from($upload_from)
309 309
     {
310 310
         EE_Error::doing_it_wrong(
311
-            __CLASS__ . '::' . __FUNCTION__,
311
+            __CLASS__.'::'.__FUNCTION__,
312 312
             esc_html__(
313 313
                 'EEH_Sideloader::set_upload_from was renamed to EEH_Sideloader::set_download_from',
314 314
                 'event_espresso'
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
     public function get_upload_from()
328 328
     {
329 329
         EE_Error::doing_it_wrong(
330
-            __CLASS__ . '::' . __FUNCTION__,
330
+            __CLASS__.'::'.__FUNCTION__,
331 331
             esc_html__(
332 332
                 'EEH_Sideloader::get_upload_from was renamed to EEH_Sideloader::get_download_from',
333 333
                 'event_espresso'
Please login to merge, or discard this patch.
core/helpers/EEH_MSG_Template.helper.php 2 patches
Indentation   +1247 added lines, -1247 removed lines patch added patch discarded remove patch
@@ -15,1251 +15,1251 @@
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * Holds a collection of EE_Message_Template_Pack objects.
20
-     * @type EE_Messages_Template_Pack_Collection
21
-     */
22
-    protected static $_template_pack_collection;
23
-
24
-
25
-    /**
26
-     * @throws EE_Error
27
-     */
28
-    private static function _set_autoloader()
29
-    {
30
-        EED_Messages::set_autoloaders();
31
-    }
32
-
33
-
34
-    /**
35
-     * generate_new_templates
36
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
37
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
38
-     * for the event.
39
-     *
40
-     * @access protected
41
-     * @param string $messenger     the messenger we are generating templates for
42
-     * @param array  $message_types array of message types that the templates are generated for.
43
-     * @param int    $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID
44
-     *                              to use as the base for the new generated template.
45
-     * @param bool   $global        true indicates generating templates on messenger activation. false requires GRP_ID
46
-     *                              for event specific template generation.
47
-     * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array
48
-     *                for templates that are generated.  If this is an empty array then it means no templates were
49
-     *                generated which usually means there was an error.  Anything in the array with an empty value for
50
-     *                `MTP_context` means that it was not a new generated template but just reactivated (which only
51
-     *                happens for global templates that already exist in the database.
52
-     * @throws EE_Error
53
-     * @throws ReflectionException
54
-     */
55
-    public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
56
-    {
57
-        // make sure message_type is an array.
58
-        $message_types = (array) $message_types;
59
-        $templates = array();
60
-
61
-        if (empty($messenger)) {
62
-            throw new EE_Error(esc_html__('We need a messenger to generate templates!', 'event_espresso'));
63
-        }
64
-
65
-        // if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
66
-        if (empty($message_types)) {
67
-            throw new EE_Error(esc_html__('We need at least one message type to generate templates!', 'event_espresso'));
68
-        }
69
-
70
-        EEH_MSG_Template::_set_autoloader();
71
-        foreach ($message_types as $message_type) {
72
-            // if global then let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
73
-            if ($global && empty($GRP_ID)) {
74
-                $GRP_ID = EEM_Message_Template_Group::instance()->get_one(
75
-                    array(
76
-                        array(
77
-                            'MTP_messenger'    => $messenger,
78
-                            'MTP_message_type' => $message_type,
79
-                            'MTP_is_global'    => true,
80
-                        ),
81
-                    )
82
-                );
83
-                $GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
84
-            }
85
-            // if this is global template generation.
86
-            // First let's determine if we already HAVE global templates for this messenger and message_type combination.
87
-            //  If we do then NO generation!!
88
-            if ($global && EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
89
-                $templates[] = array(
90
-                    'GRP_ID' => $GRP_ID,
91
-                    'MTP_context' => '',
92
-                );
93
-                // we already have generated templates for this so let's go to the next message type.
94
-                continue;
95
-            }
96
-            $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
97
-
98
-            if (! $new_message_template_group) {
99
-                continue;
100
-            }
101
-            $templates[] = $new_message_template_group;
102
-        }
103
-
104
-        return $templates;
105
-    }
106
-
107
-
108
-    /**
109
-     * The purpose of this method is to determine if there are already generated templates in the database for the
110
-     * given variables.
111
-     *
112
-     * @param string $messenger    messenger
113
-     * @param string $message_type message type
114
-     * @param int    $GRP_ID       GRP ID ( if a custom template) (if not provided then we're just doing global
115
-     *                             template check)
116
-     * @return bool                true = generated, false = hasn't been generated.
117
-     * @throws EE_Error
118
-     */
119
-    public static function already_generated($messenger, $message_type, $GRP_ID = 0)
120
-    {
121
-        EEH_MSG_Template::_set_autoloader();
122
-        // what method we use depends on whether we have an GRP_ID or not
123
-        $count = empty($GRP_ID)
124
-            ? EEM_Message_Template::instance()->count(
125
-                array(
126
-                    array(
127
-                        'Message_Template_Group.MTP_messenger'    => $messenger,
128
-                        'Message_Template_Group.MTP_message_type' => $message_type,
129
-                        'Message_Template_Group.MTP_is_global'    => true
130
-                    )
131
-                )
132
-            )
133
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
134
-
135
-        return $count > 0;
136
-    }
137
-
138
-
139
-    /**
140
-     * Updates all message templates matching the incoming messengers and message types to active status.
141
-     *
142
-     * @static
143
-     * @param array $messenger_names    Messenger slug
144
-     * @param array $message_type_names Message type slug
145
-     * @return  int                         count of updated records.
146
-     * @throws EE_Error
147
-     */
148
-    public static function update_to_active($messenger_names, $message_type_names)
149
-    {
150
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
151
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
152
-        return EEM_Message_Template_Group::instance()->update(
153
-            array( 'MTP_is_active' => 1 ),
154
-            array(
155
-                array(
156
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
157
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
158
-                )
159
-            )
160
-        );
161
-    }
162
-
163
-
164
-    /**
165
-     * Updates all message template groups matching the incoming arguments to inactive status.
166
-     *
167
-     * @static
168
-     * @param array $messenger_names    The messenger slugs.
169
-     *                                  If empty then all templates matching the message types are marked inactive.
170
-     *                                  Otherwise only templates matching the messengers and message types.
171
-     * @param array $message_type_names The message type slugs.
172
-     *                                  If empty then all templates matching the messengers are marked inactive.
173
-     *                                  Otherwise only templates matching the messengers and message types.
174
-     *
175
-     * @return int  count of updated records.
176
-     * @throws EE_Error
177
-     */
178
-    public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
179
-    {
180
-        return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
181
-            $messenger_names,
182
-            $message_type_names
183
-        );
184
-    }
185
-
186
-
187
-    /**
188
-     * The purpose of this function is to return all installed message objects
189
-     * (messengers and message type regardless of whether they are ACTIVE or not)
190
-     *
191
-     * @param string $type
192
-     * @return array array consisting of installed messenger objects and installed message type objects.
193
-     * @throws EE_Error
194
-     * @throws ReflectionException
195
-     * @deprecated 4.9.0
196
-     * @static
197
-     */
198
-    public static function get_installed_message_objects($type = 'all')
199
-    {
200
-        self::_set_autoloader();
201
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
202
-        return array(
203
-            'messenger' => $message_resource_manager->installed_messengers(),
204
-            'message_type' => $message_resource_manager->installed_message_types()
205
-        );
206
-    }
207
-
208
-
209
-    /**
210
-     * This will return an array of shortcodes => labels from the
211
-     * messenger and message_type objects associated with this
212
-     * template.
213
-     *
214
-     * @param string $message_type
215
-     * @param string $messenger
216
-     * @param array  $fields                        What fields we're returning valid shortcodes for.
217
-     *                                              If empty then we assume all fields are to be returned. Optional.
218
-     * @param string $context                       What context we're going to return shortcodes for. Optional.
219
-     * @param bool   $merged                        If TRUE then we don't return shortcodes indexed by field,
220
-     *                                              but instead an array of the unique shortcodes for all the given (
221
-     *                                              or all) fields. Optional.
222
-     * @return array                                an array of shortcodes in the format
223
-     *                                              array( '[shortcode] => 'label')
224
-     *                                              OR
225
-     *                                              FALSE if no shortcodes found.
226
-     * @throws ReflectionException
227
-     * @throws EE_Error*@since 4.3.0
228
-     *
229
-     */
230
-    public static function get_shortcodes(
231
-        $message_type,
232
-        $messenger,
233
-        $fields = array(),
234
-        $context = 'admin',
235
-        $merged = false
236
-    ) {
237
-        $messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
238
-        $mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
239
-        /** @var EE_Message_Resource_Manager $message_resource_manager */
240
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
241
-        // convert slug to object
242
-        $messenger = $message_resource_manager->get_messenger($messenger);
243
-
244
-        // if messenger isn't a EE_messenger resource then bail.
245
-        if (! $messenger instanceof EE_messenger) {
246
-            return array();
247
-        }
248
-
249
-        // validate class for getting our list of shortcodes
250
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
251
-        if (! class_exists($classname)) {
252
-            $msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
253
-            $msg[] = sprintf(
254
-                esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
255
-                $classname
256
-            );
257
-            throw new EE_Error(implode('||', $msg));
258
-        }
259
-
260
-        /** @type EE_Messages_Validator $_VLD */
261
-        $_VLD = new $classname(array(), $context);
262
-        $valid_shortcodes = $_VLD->get_validators();
263
-
264
-        // let's make sure we're only getting the shortcode part of the validators
265
-        $shortcodes = array();
266
-        foreach ($valid_shortcodes as $field => $validators) {
267
-            $shortcodes[ $field ] = $validators['shortcodes'];
268
-        }
269
-        $valid_shortcodes = $shortcodes;
270
-
271
-        // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
272
-        if (! empty($fields)) {
273
-            $specified_shortcodes = array();
274
-            foreach ($fields as $field) {
275
-                if (isset($valid_shortcodes[ $field ])) {
276
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
277
-                }
278
-            }
279
-            $valid_shortcodes = $specified_shortcodes;
280
-        }
281
-
282
-        // if not merged then let's replace the fields with the localized fields
283
-        if (! $merged) {
284
-            // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
285
-            $field_settings = $messenger->get_template_fields();
286
-            $localized = array();
287
-            foreach ($valid_shortcodes as $field => $shortcodes) {
288
-                // get localized field label
289
-                if (isset($field_settings[ $field ])) {
290
-                    // possible that this is used as a main field.
291
-                    if (empty($field_settings[ $field ])) {
292
-                        if (isset($field_settings['extra'][ $field ])) {
293
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
294
-                        } else {
295
-                            $_field = $field;
296
-                        }
297
-                    } else {
298
-                        $_field = $field_settings[ $field ]['label'];
299
-                    }
300
-                } elseif (isset($field_settings['extra'])) {
301
-                    // loop through extra "main fields" and see if any of their children have our field
302
-                    foreach ($field_settings['extra'] as $fields) {
303
-                        if (isset($fields[ $field ])) {
304
-                            $_field = $fields[ $field ]['label'];
305
-                        } else {
306
-                            $_field = $field;
307
-                        }
308
-                    }
309
-                } else {
310
-                    $_field = $field;
311
-                }
312
-                if (isset($_field)) {
313
-                    $localized[ (string) $_field ] = $shortcodes;
314
-                }
315
-            }
316
-            $valid_shortcodes = $localized;
317
-        }
318
-
319
-        // if $merged then let's merge all the shortcodes into one list NOT indexed by field.
320
-        if ($merged) {
321
-            $merged_codes = array();
322
-            foreach ($valid_shortcodes as $shortcode) {
323
-                foreach ($shortcode as $code => $label) {
324
-                    if (isset($merged_codes[ $code ])) {
325
-                        continue;
326
-                    } else {
327
-                        $merged_codes[ $code ] = $label;
328
-                    }
329
-                }
330
-            }
331
-            $valid_shortcodes = $merged_codes;
332
-        }
333
-
334
-        return $valid_shortcodes;
335
-    }
336
-
337
-
338
-    /**
339
-     * Get Messenger object.
340
-     *
341
-     * @param string $messenger messenger slug for the messenger object we want to retrieve.
342
-     * @return EE_messenger
343
-     * @throws ReflectionException
344
-     * @throws EE_Error*@since 4.3.0
345
-     * @deprecated 4.9.0
346
-     */
347
-    public static function messenger_obj($messenger)
348
-    {
349
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
350
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
351
-        return $Message_Resource_Manager->get_messenger($messenger);
352
-    }
353
-
354
-
355
-    /**
356
-     * get Message type object
357
-     *
358
-     * @param string $message_type the slug for the message type object to retrieve
359
-     * @return EE_message_type
360
-     * @throws ReflectionException
361
-     * @throws EE_Error*@since 4.3.0
362
-     * @deprecated 4.9.0
363
-     */
364
-    public static function message_type_obj($message_type)
365
-    {
366
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
367
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
368
-        return $Message_Resource_Manager->get_message_type($message_type);
369
-    }
370
-
371
-
372
-    /**
373
-     * Given a message_type slug, will return whether that message type is active in the system or not.
374
-     *
375
-     * @since    4.3.0
376
-     * @param string $message_type message type to check for.
377
-     * @return boolean
378
-     * @throws EE_Error
379
-     * @throws ReflectionException
380
-     */
381
-    public static function is_mt_active($message_type)
382
-    {
383
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
384
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
385
-        $active_mts = $Message_Resource_Manager->list_of_active_message_types();
386
-        return in_array($message_type, $active_mts);
387
-    }
388
-
389
-
390
-    /**
391
-     * Given a messenger slug, will return whether that messenger is active in the system or not.
392
-     *
393
-     * @since    4.3.0
394
-     *
395
-     * @param string $messenger slug for messenger to check.
396
-     * @return boolean
397
-     * @throws EE_Error
398
-     * @throws ReflectionException
399
-     */
400
-    public static function is_messenger_active($messenger)
401
-    {
402
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
403
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
404
-        $active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
405
-        return $active_messenger instanceof EE_messenger;
406
-    }
407
-
408
-
409
-    /**
410
-     * Used to return active messengers array stored in the wp options table.
411
-     * If no value is present in the option then an empty array is returned.
412
-     *
413
-     * @deprecated 4.9
414
-     * @since      4.3.1
415
-     *
416
-     * @return array
417
-     * @throws EE_Error
418
-     * @throws ReflectionException
419
-     */
420
-    public static function get_active_messengers_in_db()
421
-    {
422
-        EE_Error::doing_it_wrong(
423
-            __METHOD__,
424
-            esc_html__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
425
-            '4.9.0'
426
-        );
427
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
428
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
429
-        return $Message_Resource_Manager->get_active_messengers_option();
430
-    }
431
-
432
-
433
-    /**
434
-     * Used to update the active messengers array stored in the wp options table.
435
-     *
436
-     * @since      4.3.1
437
-     * @deprecated 4.9.0
438
-     *
439
-     * @param array $data_to_save Incoming data to save.
440
-     *
441
-     * @return bool FALSE if not updated, TRUE if updated.
442
-     * @throws EE_Error
443
-     * @throws ReflectionException
444
-     */
445
-    public static function update_active_messengers_in_db($data_to_save)
446
-    {
447
-        EE_Error::doing_it_wrong(
448
-            __METHOD__,
449
-            esc_html__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
450
-            '4.9.0'
451
-        );
452
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
453
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
454
-        return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
455
-    }
456
-
457
-
458
-    /**
459
-     * This does some validation of incoming params, determines what type of url is being prepped and returns the
460
-     * appropriate url trigger
461
-     *
462
-     * @param EE_message_type $message_type
463
-     * @param EE_Message $message
464
-     * @param EE_Registration | null $registration  The registration object must be included if this
465
-     *                                              is going to be a registration trigger url.
466
-     * @param string $sending_messenger             The (optional) sending messenger for the url.
467
-     *
468
-     * @return string
469
-     * @throws EE_Error
470
-     */
471
-    public static function get_url_trigger(
472
-        EE_message_type $message_type,
473
-        EE_Message $message,
474
-        $registration = null,
475
-        $sending_messenger = ''
476
-    ) {
477
-        // first determine if the url can be to the EE_Message object.
478
-        if (! $message_type->always_generate()) {
479
-            return EEH_MSG_Template::generate_browser_trigger($message);
480
-        }
481
-
482
-        // if $registration object is not valid then exit early because there's nothing that can be generated.
483
-        if (! $registration instanceof EE_Registration) {
484
-            throw new EE_Error(
485
-                esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
486
-            );
487
-        }
488
-
489
-        // validate given context
490
-        $contexts = $message_type->get_contexts();
491
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
492
-            throw new EE_Error(
493
-                sprintf(
494
-                    esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
495
-                    $message->context(),
496
-                    get_class($message_type)
497
-                )
498
-            );
499
-        }
500
-
501
-        // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
502
-        if (! empty($sending_messenger)) {
503
-            $with_messengers = $message_type->with_messengers();
504
-            if (
505
-                ! isset($with_messengers[ $message->messenger() ])
506
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
507
-            ) {
508
-                throw new EE_Error(
509
-                    sprintf(
510
-                        esc_html__(
511
-                            'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
512
-                            'event_espresso'
513
-                        ),
514
-                        $sending_messenger,
515
-                        get_class($message_type)
516
-                    )
517
-                );
518
-            }
519
-        } else {
520
-            $sending_messenger = $message->messenger();
521
-        }
522
-        return EEH_MSG_Template::generate_url_trigger(
523
-            $sending_messenger,
524
-            $message->messenger(),
525
-            $message->context(),
526
-            $message->message_type(),
527
-            $registration,
528
-            $message->GRP_ID()
529
-        );
530
-    }
531
-
532
-
533
-    /**
534
-     * This returns the url for triggering a in browser view of a specific EE_Message object.
535
-     * @param EE_Message $message
536
-     * @return string.
537
-     */
538
-    public static function generate_browser_trigger(EE_Message $message)
539
-    {
540
-        $query_args = array(
541
-            'ee' => 'msg_browser_trigger',
542
-            'token' => $message->MSG_token()
543
-        );
544
-        return apply_filters(
545
-            'FHEE__EEH_MSG_Template__generate_browser_trigger',
546
-            add_query_arg($query_args, site_url()),
547
-            $message
548
-        );
549
-    }
550
-
551
-
552
-
553
-
554
-
555
-
556
-    /**
557
-     * This returns the url for triggering an in browser view of the error saved on the incoming message object.
558
-     * @param EE_Message $message
559
-     * @return string
560
-     */
561
-    public static function generate_error_display_trigger(EE_Message $message)
562
-    {
563
-        return apply_filters(
564
-            'FHEE__EEH_MSG_Template__generate_error_display_trigger',
565
-            add_query_arg(
566
-                array(
567
-                    'ee' => 'msg_browser_error_trigger',
568
-                    'token' => $message->MSG_token()
569
-                ),
570
-                site_url()
571
-            ),
572
-            $message
573
-        );
574
-    }
575
-
576
-
577
-    /**
578
-     * This generates a url trigger for the msg_url_trigger route using the given arguments
579
-     *
580
-     * @param string          $sending_messenger      The sending messenger slug.
581
-     * @param string          $generating_messenger   The generating messenger slug.
582
-     * @param string          $context                The context for the template.
583
-     * @param string          $message_type           The message type slug
584
-     * @param EE_Registration $registration
585
-     * @param integer         $message_template_group id   The EE_Message_Template_Group ID for the template.
586
-     * @param integer         $data_id                The id to the EE_Base_Class for getting the data used by the
587
-     *                                                trigger.
588
-     * @return string          The generated url.
589
-     * @throws EE_Error
590
-     */
591
-    public static function generate_url_trigger(
592
-        $sending_messenger,
593
-        $generating_messenger,
594
-        $context,
595
-        $message_type,
596
-        EE_Registration $registration,
597
-        $message_template_group,
598
-        $data_id = 0
599
-    ) {
600
-        $query_args = array(
601
-            'ee' => 'msg_url_trigger',
602
-            'snd_msgr' => $sending_messenger,
603
-            'gen_msgr' => $generating_messenger,
604
-            'message_type' => $message_type,
605
-            'context' => $context,
606
-            'token' => $registration->reg_url_link(),
607
-            'GRP_ID' => $message_template_group,
608
-            'id' => $data_id
609
-            );
610
-        $url = add_query_arg($query_args, get_home_url());
611
-
612
-        // made it here so now we can just get the url and filter it.  Filtered globally and by message type.
613
-        return apply_filters(
614
-            'FHEE__EEH_MSG_Template__generate_url_trigger',
615
-            $url,
616
-            $sending_messenger,
617
-            $generating_messenger,
618
-            $context,
619
-            $message_type,
620
-            $registration,
621
-            $message_template_group,
622
-            $data_id
623
-        );
624
-    }
625
-
626
-
627
-
628
-
629
-    /**
630
-     * Return the specific css for the action icon given.
631
-     *
632
-     * @param string $type  What action to return.
633
-     * @return string[]
634
-     * @since 4.9.0
635
-     */
636
-    public static function get_message_action_icon($type)
637
-    {
638
-        $action_icons = self::get_message_action_icons();
639
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
640
-    }
641
-
642
-
643
-    /**
644
-     * This is used for retrieving the css classes used for the icons representing message actions.
645
-     *
646
-     * @since 4.9.0
647
-     *
648
-     * @return array
649
-     */
650
-    public static function get_message_action_icons()
651
-    {
652
-        return apply_filters(
653
-            'FHEE__EEH_MSG_Template__message_action_icons',
654
-            array(
655
-                'view' => array(
656
-                    'label' => esc_html__('View Message', 'event_espresso'),
657
-                    'css_class' => 'dashicons dashicons-welcome-view-site',
658
-                ),
659
-                'error' => array(
660
-                    'label' => esc_html__('View Error Message', 'event_espresso'),
661
-                    'css_class' => 'dashicons dashicons-info',
662
-                ),
663
-                'see_notifications_for' => array(
664
-                    'label' => esc_html__('View Related Messages', 'event_espresso'),
665
-                    'css_class' => 'dashicons dashicons-megaphone',
666
-                ),
667
-                'generate_now' => array(
668
-                    'label' => esc_html__('Generate the message now.', 'event_espresso'),
669
-                    'css_class' => 'dashicons dashicons-admin-tools',
670
-                ),
671
-                'send_now' => array(
672
-                    'label' => esc_html__('Send Immediately', 'event_espresso'),
673
-                    'css_class' => 'dashicons dashicons-controls-forward',
674
-                ),
675
-                'queue_for_resending' => array(
676
-                    'label' => esc_html__('Queue for Resending', 'event_espresso'),
677
-                    'css_class' => 'dashicons dashicons-controls-repeat',
678
-                ),
679
-                'view_transaction' => array(
680
-                    'label' => esc_html__('View related Transaction', 'event_espresso'),
681
-                    'css_class' => 'dashicons dashicons-cart',
682
-                )
683
-            )
684
-        );
685
-    }
686
-
687
-
688
-    /**
689
-     * This returns the url for a given action related to EE_Message.
690
-     *
691
-     * @param string     $type         What type of action to return the url for.
692
-     * @param EE_Message $message      Required for generating the correct url for some types.
693
-     * @param array      $query_params Any additional query params to be included with the generated url.
694
-     *
695
-     * @return string
696
-     * @throws EE_Error
697
-     * @throws ReflectionException
698
-     * @since 4.9.0
699
-     *
700
-     */
701
-    public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
702
-    {
703
-        $action_urls = self::get_message_action_urls($message, $query_params);
704
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
705
-    }
706
-
707
-
708
-    /**
709
-     * This returns all the current urls for EE_Message actions.
710
-     *
711
-     * @since 4.9.0
712
-     *
713
-     * @param EE_Message $message      The EE_Message object required to generate correct urls for some types.
714
-     * @param array      $query_params Any additional query_params to be included with the generated url.
715
-     *
716
-     * @return array
717
-     * @throws EE_Error
718
-     * @throws ReflectionException
719
-     */
720
-    public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
721
-    {
722
-        EE_Registry::instance()->load_helper('URL');
723
-        // if $message is not an instance of EE_Message then let's just do a dummy.
724
-        $message = empty($message) ? EE_Message_Factory::create() : $message;
725
-        $action_urls =  apply_filters(
726
-            'FHEE__EEH_MSG_Template__get_message_action_url',
727
-            array(
728
-                'view' => EEH_MSG_Template::generate_browser_trigger($message),
729
-                'error' => EEH_MSG_Template::generate_error_display_trigger($message),
730
-                'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
731
-                    array_merge(
732
-                        array(
733
-                            'page' => 'espresso_messages',
734
-                            'action' => 'default',
735
-                            'filterby' => 1,
736
-                        ),
737
-                        $query_params
738
-                    ),
739
-                    admin_url('admin.php')
740
-                ),
741
-                'generate_now' => EEH_URL::add_query_args_and_nonce(
742
-                    array(
743
-                        'page' => 'espresso_messages',
744
-                        'action' => 'generate_now',
745
-                        'MSG_ID' => $message->ID()
746
-                    ),
747
-                    admin_url('admin.php')
748
-                ),
749
-                'send_now' => EEH_URL::add_query_args_and_nonce(
750
-                    array(
751
-                        'page' => 'espresso_messages',
752
-                        'action' => 'send_now',
753
-                        'MSG_ID' => $message->ID()
754
-                    ),
755
-                    admin_url('admin.php')
756
-                ),
757
-                'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
758
-                    array(
759
-                        'page' => 'espresso_messages',
760
-                        'action' => 'queue_for_resending',
761
-                        'MSG_ID' => $message->ID()
762
-                    ),
763
-                    admin_url('admin.php')
764
-                ),
765
-            )
766
-        );
767
-        if (
768
-            $message->TXN_ID() > 0
769
-            && EE_Registry::instance()->CAP->current_user_can(
770
-                'ee_read_transaction',
771
-                'espresso_transactions_default',
772
-                $message->TXN_ID()
773
-            )
774
-        ) {
775
-            $action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
776
-                array(
777
-                    'page' => 'espresso_transactions',
778
-                    'action' => 'view_transaction',
779
-                    'TXN_ID' => $message->TXN_ID()
780
-                ),
781
-                admin_url('admin.php')
782
-            );
783
-        } else {
784
-            $action_urls['view_transaction'] = '';
785
-        }
786
-        return $action_urls;
787
-    }
788
-
789
-
790
-    /**
791
-     * This returns a generated link html including the icon used for the action link for EE_Message actions.
792
-     *
793
-     * @param string          $type         What type of action the link is for (if invalid type is passed in then an
794
-     *                                      empty string is returned)
795
-     * @param EE_Message|null $message      The EE_Message object (required for some actions to generate correctly)
796
-     * @param array           $query_params Any extra query params to include in the generated link.
797
-     *
798
-     * @return string
799
-     * @throws EE_Error
800
-     * @throws ReflectionException
801
-     * @since 4.9.0
802
-     *
803
-     */
804
-    public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
805
-    {
806
-        $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
807
-        $icon_css = EEH_MSG_Template::get_message_action_icon($type);
808
-        $title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
809
-
810
-        if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
811
-            return '';
812
-        }
813
-
814
-        $icon_css['css_class'] .= esc_attr(
815
-            apply_filters(
816
-                'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
817
-                ' js-ee-message-action-link ee-message-action-link-' . $type,
818
-                $type,
819
-                $message,
820
-                $query_params
821
-            )
822
-        );
823
-
824
-        return '<a href="' . $url . '" ' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
825
-    }
826
-
827
-
828
-
829
-
830
-
831
-    /**
832
-     * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
833
-     *
834
-     * @since 4.9.0
835
-     * @return array
836
-     */
837
-    public static function reg_status_to_message_type_array()
838
-    {
839
-        return (array) apply_filters(
840
-            'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
841
-            array(
842
-                EEM_Registration::status_id_approved => 'registration',
843
-                EEM_Registration::status_id_pending_payment => 'pending_approval',
844
-                EEM_Registration::status_id_not_approved => 'not_approved_registration',
845
-                EEM_Registration::status_id_cancelled => 'cancelled_registration',
846
-                EEM_Registration::status_id_declined => 'declined_registration'
847
-            )
848
-        );
849
-    }
850
-
851
-
852
-
853
-
854
-    /**
855
-     * This returns the corresponding registration message type slug to the given reg status. If there isn't a
856
-     * match, then returns an empty string.
857
-     *
858
-     * @since 4.9.0
859
-     * @param $reg_status
860
-     * @return string
861
-     */
862
-    public static function convert_reg_status_to_message_type($reg_status)
863
-    {
864
-        $reg_status_array = self::reg_status_to_message_type_array();
865
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
866
-    }
867
-
868
-
869
-    /**
870
-     * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
871
-     *
872
-     * @since 4.9.0
873
-     * @return array
874
-     */
875
-    public static function payment_status_to_message_type_array()
876
-    {
877
-        return (array) apply_filters(
878
-            'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
879
-            array(
880
-                EEM_Payment::status_id_approved => 'payment',
881
-                EEM_Payment::status_id_pending => 'payment_pending',
882
-                EEM_Payment::status_id_cancelled => 'payment_cancelled',
883
-                EEM_Payment::status_id_declined => 'payment_declined',
884
-                EEM_Payment::status_id_failed => 'payment_failed'
885
-            )
886
-        );
887
-    }
888
-
889
-
890
-
891
-
892
-    /**
893
-     * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
894
-     * an empty string is returned
895
-     *
896
-     * @since 4.9.0
897
-     * @param $payment_status
898
-     * @return string
899
-     */
900
-    public static function convert_payment_status_to_message_type($payment_status)
901
-    {
902
-        $payment_status_array = self::payment_status_to_message_type_array();
903
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
904
-    }
905
-
906
-
907
-    /**
908
-     * This is used to retrieve the template pack for the given name.
909
-     *
910
-     * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
911
-     *
912
-     * @return EE_Messages_Template_Pack
913
-     */
914
-    public static function get_template_pack($template_pack_name)
915
-    {
916
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
917
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
918
-        }
919
-
920
-        // first see if in collection already
921
-        $template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
922
-
923
-        if ($template_pack instanceof EE_Messages_Template_Pack) {
924
-            return $template_pack;
925
-        }
926
-
927
-        // nope...let's get it.
928
-        // not set yet so let's attempt to get it.
929
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
930
-            ' ',
931
-            '_',
932
-            ucwords(
933
-                str_replace('_', ' ', $template_pack_name)
934
-            )
935
-        );
936
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
937
-            return self::get_template_pack('default');
938
-        } else {
939
-            $template_pack = new $pack_class_name();
940
-            self::$_template_pack_collection->add($template_pack);
941
-            return $template_pack;
942
-        }
943
-    }
944
-
945
-
946
-
947
-
948
-    /**
949
-     * Globs template packs installed in core and returns the template pack collection with all installed template packs
950
-     * in it.
951
-     *
952
-     * @since 4.9.0
953
-     *
954
-     * @return EE_Messages_Template_Pack_Collection
955
-     */
956
-    public static function get_template_pack_collection()
957
-    {
958
-        $new_collection = false;
959
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
960
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
961
-            $new_collection = true;
962
-        }
963
-
964
-        // glob the defaults directory for messages
965
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
966
-        foreach ($templates as $template_path) {
967
-            // grab folder name
968
-            $template = basename($template_path);
969
-
970
-            if (! $new_collection) {
971
-                // already have it?
972
-                if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
973
-                    continue;
974
-                }
975
-            }
976
-
977
-            // setup classname.
978
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
979
-                ' ',
980
-                '_',
981
-                ucwords(
982
-                    str_replace(
983
-                        '_',
984
-                        ' ',
985
-                        $template
986
-                    )
987
-                )
988
-            );
989
-            if (! class_exists($template_pack_class_name)) {
990
-                continue;
991
-            }
992
-            self::$_template_pack_collection->add(new $template_pack_class_name());
993
-        }
994
-
995
-        /**
996
-         * Filter for plugins to add in any additional template packs
997
-         * Note the filter name here is for backward compat, this used to be found in EED_Messages.
998
-         */
999
-        $additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
1000
-        foreach ((array) $additional_template_packs as $template_pack) {
1001
-            if (
1002
-                self::$_template_pack_collection->get_by_name(
1003
-                    $template_pack->dbref
1004
-                ) instanceof EE_Messages_Template_Pack
1005
-            ) {
1006
-                continue;
1007
-            }
1008
-            self::$_template_pack_collection->add($template_pack);
1009
-        }
1010
-        return self::$_template_pack_collection;
1011
-    }
1012
-
1013
-
1014
-    /**
1015
-     * This is a wrapper for the protected _create_new_templates function
1016
-     *
1017
-     * @param string $messenger_name
1018
-     * @param string $message_type_name message type that the templates are being created for
1019
-     * @param int    $GRP_ID
1020
-     * @param bool   $global
1021
-     * @return array
1022
-     * @throws EE_Error
1023
-     * @throws ReflectionException
1024
-     */
1025
-    public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1026
-    {
1027
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1028
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1029
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1030
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1031
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1032
-            return array();
1033
-        }
1034
-        // whew made it this far!  Okay, let's go ahead and create the templates then
1035
-        return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * @param EE_messenger     $messenger
1041
-     * @param EE_message_type  $message_type
1042
-     * @param                  $GRP_ID
1043
-     * @param                  $global
1044
-     * @return array|mixed
1045
-     * @throws EE_Error
1046
-     * @throws ReflectionException
1047
-     */
1048
-    protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1049
-    {
1050
-        // if we're creating a custom template then we don't need to use the defaults class
1051
-        if (! $global) {
1052
-            return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1053
-        }
1054
-        /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1055
-        $Message_Template_Defaults = EE_Registry::factory(
1056
-            'EE_Messages_Template_Defaults',
1057
-            array( $messenger, $message_type, $GRP_ID )
1058
-        );
1059
-        // generate templates
1060
-        $success = $Message_Template_Defaults->create_new_templates();
1061
-
1062
-        // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1063
-        // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1064
-        // attempts.
1065
-        if (! $success) {
1066
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
1067
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1068
-            $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1069
-        }
1070
-
1071
-        /**
1072
-         * $success is in an array in the following format
1073
-         * array(
1074
-         *    'GRP_ID' => $new_grp_id,
1075
-         *    'MTP_context' => $first_context_in_new_templates,
1076
-         * )
1077
-         */
1078
-        return $success;
1079
-    }
1080
-
1081
-
1082
-    /**
1083
-     * This creates a custom template using the incoming GRP_ID
1084
-     *
1085
-     * @param EE_messenger    $messenger
1086
-     * @param EE_message_type $message_type
1087
-     * @param int             $GRP_ID           GRP_ID for the template_group being used as the base
1088
-     * @return  array $success              This will be an array in the format:
1089
-     *                                          array(
1090
-     *                                          'GRP_ID' => $new_grp_id,
1091
-     *                                          'MTP_context' => $first_context_in_created_template
1092
-     *                                          )
1093
-     * @throws EE_Error
1094
-     * @throws ReflectionException
1095
-     * @access private
1096
-     */
1097
-    private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1098
-    {
1099
-        // defaults
1100
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1101
-        // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1102
-        $Message_Template_Group = empty($GRP_ID)
1103
-            ? EEM_Message_Template_Group::instance()->get_one(
1104
-                array(
1105
-                    array(
1106
-                        'MTP_messenger'    => $messenger->name,
1107
-                        'MTP_message_type' => $message_type->name,
1108
-                        'MTP_is_global'    => true
1109
-                    )
1110
-                )
1111
-            )
1112
-            : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1113
-        // if we don't have a mtg at this point then we need to bail.
1114
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1115
-            EE_Error::add_error(
1116
-                sprintf(
1117
-                    esc_html__(
1118
-                        'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1119
-                        'event_espresso'
1120
-                    ),
1121
-                    $GRP_ID
1122
-                ),
1123
-                __FILE__,
1124
-                __FUNCTION__,
1125
-                __LINE__
1126
-            );
1127
-            return $success;
1128
-        }
1129
-        // let's get all the related message_template objects for this group.
1130
-        $message_templates = $Message_Template_Group->message_templates();
1131
-        // now we have what we need to setup the new template
1132
-        $new_mtg = clone $Message_Template_Group;
1133
-        $new_mtg->set('GRP_ID', 0);
1134
-        $new_mtg->set('MTP_is_global', false);
1135
-
1136
-        /** @var RequestInterface $request */
1137
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1138
-        $template_name = $request->isAjax() && $request->requestParamIsSet('templateName')
1139
-            ? $request->getRequestParam('templateName')
1140
-            : esc_html__('New Custom Template', 'event_espresso');
1141
-        $template_description = $request->isAjax() && $request->requestParamIsSet('templateDescription')
1142
-            ? $request->getRequestParam('templateDescription')
1143
-            : sprintf(
1144
-                esc_html__(
1145
-                    'This is a custom template that was created for the %s messenger and %s message type.',
1146
-                    'event_espresso'
1147
-                ),
1148
-                $new_mtg->messenger_obj()->label['singular'],
1149
-                $new_mtg->message_type_obj()->label['singular']
1150
-            );
1151
-        $new_mtg->set('MTP_name', $template_name);
1152
-        $new_mtg->set('MTP_description', $template_description);
1153
-        // remove ALL relations on this template group so they don't get saved!
1154
-        $new_mtg->_remove_relations('Message_Template');
1155
-        $new_mtg->save();
1156
-        $success['GRP_ID'] = $new_mtg->ID();
1157
-        $success['template_name'] = $template_name;
1158
-        // add new message templates and add relation to.
1159
-        foreach ($message_templates as $message_template) {
1160
-            if (! $message_template instanceof EE_Message_Template) {
1161
-                continue;
1162
-            }
1163
-            $new_message_template = clone $message_template;
1164
-            $new_message_template->set('MTP_ID', 0);
1165
-            $new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1166
-            $new_message_template->save();
1167
-            if (empty($success['MTP_context'])) {
1168
-                $success['MTP_context'] = $new_message_template->get('MTP_context');
1169
-            }
1170
-        }
1171
-        return $success;
1172
-    }
1173
-
1174
-
1175
-    /**
1176
-     * message_type_has_active_templates_for_messenger
1177
-     *
1178
-     * @param EE_messenger    $messenger
1179
-     * @param EE_message_type $message_type
1180
-     * @param bool            $global
1181
-     * @return bool
1182
-     * @throws EE_Error
1183
-     */
1184
-    public static function message_type_has_active_templates_for_messenger(
1185
-        EE_messenger $messenger,
1186
-        EE_message_type $message_type,
1187
-        $global = false
1188
-    ) {
1189
-        // is given message_type valid for given messenger (if this is not a global save)
1190
-        if ($global) {
1191
-            return true;
1192
-        }
1193
-        $active_templates = EEM_Message_Template_Group::instance()->count(
1194
-            array(
1195
-                array(
1196
-                    'MTP_is_active'    => true,
1197
-                    'MTP_messenger'    => $messenger->name,
1198
-                    'MTP_message_type' => $message_type->name
1199
-                )
1200
-            )
1201
-        );
1202
-        if ($active_templates > 0) {
1203
-            return true;
1204
-        }
1205
-        EE_Error::add_error(
1206
-            sprintf(
1207
-                esc_html__(
1208
-                    'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1209
-                    'event_espresso'
1210
-                ),
1211
-                $message_type->name,
1212
-                $messenger->name
1213
-            ),
1214
-            __FILE__,
1215
-            __FUNCTION__,
1216
-            __LINE__
1217
-        );
1218
-        return false;
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * get_fields
1224
-     * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1225
-     *
1226
-     * @param string $messenger_name    name of EE_messenger
1227
-     * @param string $message_type_name name of EE_message_type
1228
-     * @return array
1229
-     * @throws EE_Error
1230
-     * @throws ReflectionException
1231
-     */
1232
-    public static function get_fields($messenger_name, $message_type_name)
1233
-    {
1234
-        $template_fields = array();
1235
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1236
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1237
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1238
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1239
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1240
-            return array();
1241
-        }
1242
-
1243
-        $excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1244
-
1245
-        // okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1246
-        foreach ($message_type->get_contexts() as $context => $details) {
1247
-            foreach ($messenger->get_template_fields() as $field => $value) {
1248
-                if (in_array($field, $excluded_fields_for_messenger, true)) {
1249
-                    continue;
1250
-                }
1251
-                $template_fields[ $context ][ $field ] = $value;
1252
-            }
1253
-        }
1254
-        if (empty($template_fields)) {
1255
-            EE_Error::add_error(
1256
-                esc_html__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1257
-                __FILE__,
1258
-                __FUNCTION__,
1259
-                __LINE__
1260
-            );
1261
-            return array();
1262
-        }
1263
-        return $template_fields;
1264
-    }
18
+	/**
19
+	 * Holds a collection of EE_Message_Template_Pack objects.
20
+	 * @type EE_Messages_Template_Pack_Collection
21
+	 */
22
+	protected static $_template_pack_collection;
23
+
24
+
25
+	/**
26
+	 * @throws EE_Error
27
+	 */
28
+	private static function _set_autoloader()
29
+	{
30
+		EED_Messages::set_autoloaders();
31
+	}
32
+
33
+
34
+	/**
35
+	 * generate_new_templates
36
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
37
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
38
+	 * for the event.
39
+	 *
40
+	 * @access protected
41
+	 * @param string $messenger     the messenger we are generating templates for
42
+	 * @param array  $message_types array of message types that the templates are generated for.
43
+	 * @param int    $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID
44
+	 *                              to use as the base for the new generated template.
45
+	 * @param bool   $global        true indicates generating templates on messenger activation. false requires GRP_ID
46
+	 *                              for event specific template generation.
47
+	 * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array
48
+	 *                for templates that are generated.  If this is an empty array then it means no templates were
49
+	 *                generated which usually means there was an error.  Anything in the array with an empty value for
50
+	 *                `MTP_context` means that it was not a new generated template but just reactivated (which only
51
+	 *                happens for global templates that already exist in the database.
52
+	 * @throws EE_Error
53
+	 * @throws ReflectionException
54
+	 */
55
+	public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
56
+	{
57
+		// make sure message_type is an array.
58
+		$message_types = (array) $message_types;
59
+		$templates = array();
60
+
61
+		if (empty($messenger)) {
62
+			throw new EE_Error(esc_html__('We need a messenger to generate templates!', 'event_espresso'));
63
+		}
64
+
65
+		// if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
66
+		if (empty($message_types)) {
67
+			throw new EE_Error(esc_html__('We need at least one message type to generate templates!', 'event_espresso'));
68
+		}
69
+
70
+		EEH_MSG_Template::_set_autoloader();
71
+		foreach ($message_types as $message_type) {
72
+			// if global then let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
73
+			if ($global && empty($GRP_ID)) {
74
+				$GRP_ID = EEM_Message_Template_Group::instance()->get_one(
75
+					array(
76
+						array(
77
+							'MTP_messenger'    => $messenger,
78
+							'MTP_message_type' => $message_type,
79
+							'MTP_is_global'    => true,
80
+						),
81
+					)
82
+				);
83
+				$GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
84
+			}
85
+			// if this is global template generation.
86
+			// First let's determine if we already HAVE global templates for this messenger and message_type combination.
87
+			//  If we do then NO generation!!
88
+			if ($global && EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
89
+				$templates[] = array(
90
+					'GRP_ID' => $GRP_ID,
91
+					'MTP_context' => '',
92
+				);
93
+				// we already have generated templates for this so let's go to the next message type.
94
+				continue;
95
+			}
96
+			$new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
97
+
98
+			if (! $new_message_template_group) {
99
+				continue;
100
+			}
101
+			$templates[] = $new_message_template_group;
102
+		}
103
+
104
+		return $templates;
105
+	}
106
+
107
+
108
+	/**
109
+	 * The purpose of this method is to determine if there are already generated templates in the database for the
110
+	 * given variables.
111
+	 *
112
+	 * @param string $messenger    messenger
113
+	 * @param string $message_type message type
114
+	 * @param int    $GRP_ID       GRP ID ( if a custom template) (if not provided then we're just doing global
115
+	 *                             template check)
116
+	 * @return bool                true = generated, false = hasn't been generated.
117
+	 * @throws EE_Error
118
+	 */
119
+	public static function already_generated($messenger, $message_type, $GRP_ID = 0)
120
+	{
121
+		EEH_MSG_Template::_set_autoloader();
122
+		// what method we use depends on whether we have an GRP_ID or not
123
+		$count = empty($GRP_ID)
124
+			? EEM_Message_Template::instance()->count(
125
+				array(
126
+					array(
127
+						'Message_Template_Group.MTP_messenger'    => $messenger,
128
+						'Message_Template_Group.MTP_message_type' => $message_type,
129
+						'Message_Template_Group.MTP_is_global'    => true
130
+					)
131
+				)
132
+			)
133
+			: EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
134
+
135
+		return $count > 0;
136
+	}
137
+
138
+
139
+	/**
140
+	 * Updates all message templates matching the incoming messengers and message types to active status.
141
+	 *
142
+	 * @static
143
+	 * @param array $messenger_names    Messenger slug
144
+	 * @param array $message_type_names Message type slug
145
+	 * @return  int                         count of updated records.
146
+	 * @throws EE_Error
147
+	 */
148
+	public static function update_to_active($messenger_names, $message_type_names)
149
+	{
150
+		$messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
151
+		$message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
152
+		return EEM_Message_Template_Group::instance()->update(
153
+			array( 'MTP_is_active' => 1 ),
154
+			array(
155
+				array(
156
+					'MTP_messenger'     => array( 'IN', $messenger_names ),
157
+					'MTP_message_type'  => array( 'IN', $message_type_names )
158
+				)
159
+			)
160
+		);
161
+	}
162
+
163
+
164
+	/**
165
+	 * Updates all message template groups matching the incoming arguments to inactive status.
166
+	 *
167
+	 * @static
168
+	 * @param array $messenger_names    The messenger slugs.
169
+	 *                                  If empty then all templates matching the message types are marked inactive.
170
+	 *                                  Otherwise only templates matching the messengers and message types.
171
+	 * @param array $message_type_names The message type slugs.
172
+	 *                                  If empty then all templates matching the messengers are marked inactive.
173
+	 *                                  Otherwise only templates matching the messengers and message types.
174
+	 *
175
+	 * @return int  count of updated records.
176
+	 * @throws EE_Error
177
+	 */
178
+	public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
179
+	{
180
+		return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
181
+			$messenger_names,
182
+			$message_type_names
183
+		);
184
+	}
185
+
186
+
187
+	/**
188
+	 * The purpose of this function is to return all installed message objects
189
+	 * (messengers and message type regardless of whether they are ACTIVE or not)
190
+	 *
191
+	 * @param string $type
192
+	 * @return array array consisting of installed messenger objects and installed message type objects.
193
+	 * @throws EE_Error
194
+	 * @throws ReflectionException
195
+	 * @deprecated 4.9.0
196
+	 * @static
197
+	 */
198
+	public static function get_installed_message_objects($type = 'all')
199
+	{
200
+		self::_set_autoloader();
201
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
202
+		return array(
203
+			'messenger' => $message_resource_manager->installed_messengers(),
204
+			'message_type' => $message_resource_manager->installed_message_types()
205
+		);
206
+	}
207
+
208
+
209
+	/**
210
+	 * This will return an array of shortcodes => labels from the
211
+	 * messenger and message_type objects associated with this
212
+	 * template.
213
+	 *
214
+	 * @param string $message_type
215
+	 * @param string $messenger
216
+	 * @param array  $fields                        What fields we're returning valid shortcodes for.
217
+	 *                                              If empty then we assume all fields are to be returned. Optional.
218
+	 * @param string $context                       What context we're going to return shortcodes for. Optional.
219
+	 * @param bool   $merged                        If TRUE then we don't return shortcodes indexed by field,
220
+	 *                                              but instead an array of the unique shortcodes for all the given (
221
+	 *                                              or all) fields. Optional.
222
+	 * @return array                                an array of shortcodes in the format
223
+	 *                                              array( '[shortcode] => 'label')
224
+	 *                                              OR
225
+	 *                                              FALSE if no shortcodes found.
226
+	 * @throws ReflectionException
227
+	 * @throws EE_Error*@since 4.3.0
228
+	 *
229
+	 */
230
+	public static function get_shortcodes(
231
+		$message_type,
232
+		$messenger,
233
+		$fields = array(),
234
+		$context = 'admin',
235
+		$merged = false
236
+	) {
237
+		$messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
238
+		$mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
239
+		/** @var EE_Message_Resource_Manager $message_resource_manager */
240
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
241
+		// convert slug to object
242
+		$messenger = $message_resource_manager->get_messenger($messenger);
243
+
244
+		// if messenger isn't a EE_messenger resource then bail.
245
+		if (! $messenger instanceof EE_messenger) {
246
+			return array();
247
+		}
248
+
249
+		// validate class for getting our list of shortcodes
250
+		$classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
251
+		if (! class_exists($classname)) {
252
+			$msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
253
+			$msg[] = sprintf(
254
+				esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
255
+				$classname
256
+			);
257
+			throw new EE_Error(implode('||', $msg));
258
+		}
259
+
260
+		/** @type EE_Messages_Validator $_VLD */
261
+		$_VLD = new $classname(array(), $context);
262
+		$valid_shortcodes = $_VLD->get_validators();
263
+
264
+		// let's make sure we're only getting the shortcode part of the validators
265
+		$shortcodes = array();
266
+		foreach ($valid_shortcodes as $field => $validators) {
267
+			$shortcodes[ $field ] = $validators['shortcodes'];
268
+		}
269
+		$valid_shortcodes = $shortcodes;
270
+
271
+		// if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
272
+		if (! empty($fields)) {
273
+			$specified_shortcodes = array();
274
+			foreach ($fields as $field) {
275
+				if (isset($valid_shortcodes[ $field ])) {
276
+					$specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
277
+				}
278
+			}
279
+			$valid_shortcodes = $specified_shortcodes;
280
+		}
281
+
282
+		// if not merged then let's replace the fields with the localized fields
283
+		if (! $merged) {
284
+			// let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
285
+			$field_settings = $messenger->get_template_fields();
286
+			$localized = array();
287
+			foreach ($valid_shortcodes as $field => $shortcodes) {
288
+				// get localized field label
289
+				if (isset($field_settings[ $field ])) {
290
+					// possible that this is used as a main field.
291
+					if (empty($field_settings[ $field ])) {
292
+						if (isset($field_settings['extra'][ $field ])) {
293
+							$_field = $field_settings['extra'][ $field ]['main']['label'];
294
+						} else {
295
+							$_field = $field;
296
+						}
297
+					} else {
298
+						$_field = $field_settings[ $field ]['label'];
299
+					}
300
+				} elseif (isset($field_settings['extra'])) {
301
+					// loop through extra "main fields" and see if any of their children have our field
302
+					foreach ($field_settings['extra'] as $fields) {
303
+						if (isset($fields[ $field ])) {
304
+							$_field = $fields[ $field ]['label'];
305
+						} else {
306
+							$_field = $field;
307
+						}
308
+					}
309
+				} else {
310
+					$_field = $field;
311
+				}
312
+				if (isset($_field)) {
313
+					$localized[ (string) $_field ] = $shortcodes;
314
+				}
315
+			}
316
+			$valid_shortcodes = $localized;
317
+		}
318
+
319
+		// if $merged then let's merge all the shortcodes into one list NOT indexed by field.
320
+		if ($merged) {
321
+			$merged_codes = array();
322
+			foreach ($valid_shortcodes as $shortcode) {
323
+				foreach ($shortcode as $code => $label) {
324
+					if (isset($merged_codes[ $code ])) {
325
+						continue;
326
+					} else {
327
+						$merged_codes[ $code ] = $label;
328
+					}
329
+				}
330
+			}
331
+			$valid_shortcodes = $merged_codes;
332
+		}
333
+
334
+		return $valid_shortcodes;
335
+	}
336
+
337
+
338
+	/**
339
+	 * Get Messenger object.
340
+	 *
341
+	 * @param string $messenger messenger slug for the messenger object we want to retrieve.
342
+	 * @return EE_messenger
343
+	 * @throws ReflectionException
344
+	 * @throws EE_Error*@since 4.3.0
345
+	 * @deprecated 4.9.0
346
+	 */
347
+	public static function messenger_obj($messenger)
348
+	{
349
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
350
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
351
+		return $Message_Resource_Manager->get_messenger($messenger);
352
+	}
353
+
354
+
355
+	/**
356
+	 * get Message type object
357
+	 *
358
+	 * @param string $message_type the slug for the message type object to retrieve
359
+	 * @return EE_message_type
360
+	 * @throws ReflectionException
361
+	 * @throws EE_Error*@since 4.3.0
362
+	 * @deprecated 4.9.0
363
+	 */
364
+	public static function message_type_obj($message_type)
365
+	{
366
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
367
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
368
+		return $Message_Resource_Manager->get_message_type($message_type);
369
+	}
370
+
371
+
372
+	/**
373
+	 * Given a message_type slug, will return whether that message type is active in the system or not.
374
+	 *
375
+	 * @since    4.3.0
376
+	 * @param string $message_type message type to check for.
377
+	 * @return boolean
378
+	 * @throws EE_Error
379
+	 * @throws ReflectionException
380
+	 */
381
+	public static function is_mt_active($message_type)
382
+	{
383
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
384
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
385
+		$active_mts = $Message_Resource_Manager->list_of_active_message_types();
386
+		return in_array($message_type, $active_mts);
387
+	}
388
+
389
+
390
+	/**
391
+	 * Given a messenger slug, will return whether that messenger is active in the system or not.
392
+	 *
393
+	 * @since    4.3.0
394
+	 *
395
+	 * @param string $messenger slug for messenger to check.
396
+	 * @return boolean
397
+	 * @throws EE_Error
398
+	 * @throws ReflectionException
399
+	 */
400
+	public static function is_messenger_active($messenger)
401
+	{
402
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
403
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
404
+		$active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
405
+		return $active_messenger instanceof EE_messenger;
406
+	}
407
+
408
+
409
+	/**
410
+	 * Used to return active messengers array stored in the wp options table.
411
+	 * If no value is present in the option then an empty array is returned.
412
+	 *
413
+	 * @deprecated 4.9
414
+	 * @since      4.3.1
415
+	 *
416
+	 * @return array
417
+	 * @throws EE_Error
418
+	 * @throws ReflectionException
419
+	 */
420
+	public static function get_active_messengers_in_db()
421
+	{
422
+		EE_Error::doing_it_wrong(
423
+			__METHOD__,
424
+			esc_html__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
425
+			'4.9.0'
426
+		);
427
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
428
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
429
+		return $Message_Resource_Manager->get_active_messengers_option();
430
+	}
431
+
432
+
433
+	/**
434
+	 * Used to update the active messengers array stored in the wp options table.
435
+	 *
436
+	 * @since      4.3.1
437
+	 * @deprecated 4.9.0
438
+	 *
439
+	 * @param array $data_to_save Incoming data to save.
440
+	 *
441
+	 * @return bool FALSE if not updated, TRUE if updated.
442
+	 * @throws EE_Error
443
+	 * @throws ReflectionException
444
+	 */
445
+	public static function update_active_messengers_in_db($data_to_save)
446
+	{
447
+		EE_Error::doing_it_wrong(
448
+			__METHOD__,
449
+			esc_html__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
450
+			'4.9.0'
451
+		);
452
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
453
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
454
+		return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
455
+	}
456
+
457
+
458
+	/**
459
+	 * This does some validation of incoming params, determines what type of url is being prepped and returns the
460
+	 * appropriate url trigger
461
+	 *
462
+	 * @param EE_message_type $message_type
463
+	 * @param EE_Message $message
464
+	 * @param EE_Registration | null $registration  The registration object must be included if this
465
+	 *                                              is going to be a registration trigger url.
466
+	 * @param string $sending_messenger             The (optional) sending messenger for the url.
467
+	 *
468
+	 * @return string
469
+	 * @throws EE_Error
470
+	 */
471
+	public static function get_url_trigger(
472
+		EE_message_type $message_type,
473
+		EE_Message $message,
474
+		$registration = null,
475
+		$sending_messenger = ''
476
+	) {
477
+		// first determine if the url can be to the EE_Message object.
478
+		if (! $message_type->always_generate()) {
479
+			return EEH_MSG_Template::generate_browser_trigger($message);
480
+		}
481
+
482
+		// if $registration object is not valid then exit early because there's nothing that can be generated.
483
+		if (! $registration instanceof EE_Registration) {
484
+			throw new EE_Error(
485
+				esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
486
+			);
487
+		}
488
+
489
+		// validate given context
490
+		$contexts = $message_type->get_contexts();
491
+		if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
492
+			throw new EE_Error(
493
+				sprintf(
494
+					esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
495
+					$message->context(),
496
+					get_class($message_type)
497
+				)
498
+			);
499
+		}
500
+
501
+		// valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
502
+		if (! empty($sending_messenger)) {
503
+			$with_messengers = $message_type->with_messengers();
504
+			if (
505
+				! isset($with_messengers[ $message->messenger() ])
506
+				 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
507
+			) {
508
+				throw new EE_Error(
509
+					sprintf(
510
+						esc_html__(
511
+							'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
512
+							'event_espresso'
513
+						),
514
+						$sending_messenger,
515
+						get_class($message_type)
516
+					)
517
+				);
518
+			}
519
+		} else {
520
+			$sending_messenger = $message->messenger();
521
+		}
522
+		return EEH_MSG_Template::generate_url_trigger(
523
+			$sending_messenger,
524
+			$message->messenger(),
525
+			$message->context(),
526
+			$message->message_type(),
527
+			$registration,
528
+			$message->GRP_ID()
529
+		);
530
+	}
531
+
532
+
533
+	/**
534
+	 * This returns the url for triggering a in browser view of a specific EE_Message object.
535
+	 * @param EE_Message $message
536
+	 * @return string.
537
+	 */
538
+	public static function generate_browser_trigger(EE_Message $message)
539
+	{
540
+		$query_args = array(
541
+			'ee' => 'msg_browser_trigger',
542
+			'token' => $message->MSG_token()
543
+		);
544
+		return apply_filters(
545
+			'FHEE__EEH_MSG_Template__generate_browser_trigger',
546
+			add_query_arg($query_args, site_url()),
547
+			$message
548
+		);
549
+	}
550
+
551
+
552
+
553
+
554
+
555
+
556
+	/**
557
+	 * This returns the url for triggering an in browser view of the error saved on the incoming message object.
558
+	 * @param EE_Message $message
559
+	 * @return string
560
+	 */
561
+	public static function generate_error_display_trigger(EE_Message $message)
562
+	{
563
+		return apply_filters(
564
+			'FHEE__EEH_MSG_Template__generate_error_display_trigger',
565
+			add_query_arg(
566
+				array(
567
+					'ee' => 'msg_browser_error_trigger',
568
+					'token' => $message->MSG_token()
569
+				),
570
+				site_url()
571
+			),
572
+			$message
573
+		);
574
+	}
575
+
576
+
577
+	/**
578
+	 * This generates a url trigger for the msg_url_trigger route using the given arguments
579
+	 *
580
+	 * @param string          $sending_messenger      The sending messenger slug.
581
+	 * @param string          $generating_messenger   The generating messenger slug.
582
+	 * @param string          $context                The context for the template.
583
+	 * @param string          $message_type           The message type slug
584
+	 * @param EE_Registration $registration
585
+	 * @param integer         $message_template_group id   The EE_Message_Template_Group ID for the template.
586
+	 * @param integer         $data_id                The id to the EE_Base_Class for getting the data used by the
587
+	 *                                                trigger.
588
+	 * @return string          The generated url.
589
+	 * @throws EE_Error
590
+	 */
591
+	public static function generate_url_trigger(
592
+		$sending_messenger,
593
+		$generating_messenger,
594
+		$context,
595
+		$message_type,
596
+		EE_Registration $registration,
597
+		$message_template_group,
598
+		$data_id = 0
599
+	) {
600
+		$query_args = array(
601
+			'ee' => 'msg_url_trigger',
602
+			'snd_msgr' => $sending_messenger,
603
+			'gen_msgr' => $generating_messenger,
604
+			'message_type' => $message_type,
605
+			'context' => $context,
606
+			'token' => $registration->reg_url_link(),
607
+			'GRP_ID' => $message_template_group,
608
+			'id' => $data_id
609
+			);
610
+		$url = add_query_arg($query_args, get_home_url());
611
+
612
+		// made it here so now we can just get the url and filter it.  Filtered globally and by message type.
613
+		return apply_filters(
614
+			'FHEE__EEH_MSG_Template__generate_url_trigger',
615
+			$url,
616
+			$sending_messenger,
617
+			$generating_messenger,
618
+			$context,
619
+			$message_type,
620
+			$registration,
621
+			$message_template_group,
622
+			$data_id
623
+		);
624
+	}
625
+
626
+
627
+
628
+
629
+	/**
630
+	 * Return the specific css for the action icon given.
631
+	 *
632
+	 * @param string $type  What action to return.
633
+	 * @return string[]
634
+	 * @since 4.9.0
635
+	 */
636
+	public static function get_message_action_icon($type)
637
+	{
638
+		$action_icons = self::get_message_action_icons();
639
+		return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
640
+	}
641
+
642
+
643
+	/**
644
+	 * This is used for retrieving the css classes used for the icons representing message actions.
645
+	 *
646
+	 * @since 4.9.0
647
+	 *
648
+	 * @return array
649
+	 */
650
+	public static function get_message_action_icons()
651
+	{
652
+		return apply_filters(
653
+			'FHEE__EEH_MSG_Template__message_action_icons',
654
+			array(
655
+				'view' => array(
656
+					'label' => esc_html__('View Message', 'event_espresso'),
657
+					'css_class' => 'dashicons dashicons-welcome-view-site',
658
+				),
659
+				'error' => array(
660
+					'label' => esc_html__('View Error Message', 'event_espresso'),
661
+					'css_class' => 'dashicons dashicons-info',
662
+				),
663
+				'see_notifications_for' => array(
664
+					'label' => esc_html__('View Related Messages', 'event_espresso'),
665
+					'css_class' => 'dashicons dashicons-megaphone',
666
+				),
667
+				'generate_now' => array(
668
+					'label' => esc_html__('Generate the message now.', 'event_espresso'),
669
+					'css_class' => 'dashicons dashicons-admin-tools',
670
+				),
671
+				'send_now' => array(
672
+					'label' => esc_html__('Send Immediately', 'event_espresso'),
673
+					'css_class' => 'dashicons dashicons-controls-forward',
674
+				),
675
+				'queue_for_resending' => array(
676
+					'label' => esc_html__('Queue for Resending', 'event_espresso'),
677
+					'css_class' => 'dashicons dashicons-controls-repeat',
678
+				),
679
+				'view_transaction' => array(
680
+					'label' => esc_html__('View related Transaction', 'event_espresso'),
681
+					'css_class' => 'dashicons dashicons-cart',
682
+				)
683
+			)
684
+		);
685
+	}
686
+
687
+
688
+	/**
689
+	 * This returns the url for a given action related to EE_Message.
690
+	 *
691
+	 * @param string     $type         What type of action to return the url for.
692
+	 * @param EE_Message $message      Required for generating the correct url for some types.
693
+	 * @param array      $query_params Any additional query params to be included with the generated url.
694
+	 *
695
+	 * @return string
696
+	 * @throws EE_Error
697
+	 * @throws ReflectionException
698
+	 * @since 4.9.0
699
+	 *
700
+	 */
701
+	public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
702
+	{
703
+		$action_urls = self::get_message_action_urls($message, $query_params);
704
+		return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
705
+	}
706
+
707
+
708
+	/**
709
+	 * This returns all the current urls for EE_Message actions.
710
+	 *
711
+	 * @since 4.9.0
712
+	 *
713
+	 * @param EE_Message $message      The EE_Message object required to generate correct urls for some types.
714
+	 * @param array      $query_params Any additional query_params to be included with the generated url.
715
+	 *
716
+	 * @return array
717
+	 * @throws EE_Error
718
+	 * @throws ReflectionException
719
+	 */
720
+	public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
721
+	{
722
+		EE_Registry::instance()->load_helper('URL');
723
+		// if $message is not an instance of EE_Message then let's just do a dummy.
724
+		$message = empty($message) ? EE_Message_Factory::create() : $message;
725
+		$action_urls =  apply_filters(
726
+			'FHEE__EEH_MSG_Template__get_message_action_url',
727
+			array(
728
+				'view' => EEH_MSG_Template::generate_browser_trigger($message),
729
+				'error' => EEH_MSG_Template::generate_error_display_trigger($message),
730
+				'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
731
+					array_merge(
732
+						array(
733
+							'page' => 'espresso_messages',
734
+							'action' => 'default',
735
+							'filterby' => 1,
736
+						),
737
+						$query_params
738
+					),
739
+					admin_url('admin.php')
740
+				),
741
+				'generate_now' => EEH_URL::add_query_args_and_nonce(
742
+					array(
743
+						'page' => 'espresso_messages',
744
+						'action' => 'generate_now',
745
+						'MSG_ID' => $message->ID()
746
+					),
747
+					admin_url('admin.php')
748
+				),
749
+				'send_now' => EEH_URL::add_query_args_and_nonce(
750
+					array(
751
+						'page' => 'espresso_messages',
752
+						'action' => 'send_now',
753
+						'MSG_ID' => $message->ID()
754
+					),
755
+					admin_url('admin.php')
756
+				),
757
+				'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
758
+					array(
759
+						'page' => 'espresso_messages',
760
+						'action' => 'queue_for_resending',
761
+						'MSG_ID' => $message->ID()
762
+					),
763
+					admin_url('admin.php')
764
+				),
765
+			)
766
+		);
767
+		if (
768
+			$message->TXN_ID() > 0
769
+			&& EE_Registry::instance()->CAP->current_user_can(
770
+				'ee_read_transaction',
771
+				'espresso_transactions_default',
772
+				$message->TXN_ID()
773
+			)
774
+		) {
775
+			$action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
776
+				array(
777
+					'page' => 'espresso_transactions',
778
+					'action' => 'view_transaction',
779
+					'TXN_ID' => $message->TXN_ID()
780
+				),
781
+				admin_url('admin.php')
782
+			);
783
+		} else {
784
+			$action_urls['view_transaction'] = '';
785
+		}
786
+		return $action_urls;
787
+	}
788
+
789
+
790
+	/**
791
+	 * This returns a generated link html including the icon used for the action link for EE_Message actions.
792
+	 *
793
+	 * @param string          $type         What type of action the link is for (if invalid type is passed in then an
794
+	 *                                      empty string is returned)
795
+	 * @param EE_Message|null $message      The EE_Message object (required for some actions to generate correctly)
796
+	 * @param array           $query_params Any extra query params to include in the generated link.
797
+	 *
798
+	 * @return string
799
+	 * @throws EE_Error
800
+	 * @throws ReflectionException
801
+	 * @since 4.9.0
802
+	 *
803
+	 */
804
+	public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
805
+	{
806
+		$url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
807
+		$icon_css = EEH_MSG_Template::get_message_action_icon($type);
808
+		$title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
809
+
810
+		if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
811
+			return '';
812
+		}
813
+
814
+		$icon_css['css_class'] .= esc_attr(
815
+			apply_filters(
816
+				'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
817
+				' js-ee-message-action-link ee-message-action-link-' . $type,
818
+				$type,
819
+				$message,
820
+				$query_params
821
+			)
822
+		);
823
+
824
+		return '<a href="' . $url . '" ' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
825
+	}
826
+
827
+
828
+
829
+
830
+
831
+	/**
832
+	 * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
833
+	 *
834
+	 * @since 4.9.0
835
+	 * @return array
836
+	 */
837
+	public static function reg_status_to_message_type_array()
838
+	{
839
+		return (array) apply_filters(
840
+			'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
841
+			array(
842
+				EEM_Registration::status_id_approved => 'registration',
843
+				EEM_Registration::status_id_pending_payment => 'pending_approval',
844
+				EEM_Registration::status_id_not_approved => 'not_approved_registration',
845
+				EEM_Registration::status_id_cancelled => 'cancelled_registration',
846
+				EEM_Registration::status_id_declined => 'declined_registration'
847
+			)
848
+		);
849
+	}
850
+
851
+
852
+
853
+
854
+	/**
855
+	 * This returns the corresponding registration message type slug to the given reg status. If there isn't a
856
+	 * match, then returns an empty string.
857
+	 *
858
+	 * @since 4.9.0
859
+	 * @param $reg_status
860
+	 * @return string
861
+	 */
862
+	public static function convert_reg_status_to_message_type($reg_status)
863
+	{
864
+		$reg_status_array = self::reg_status_to_message_type_array();
865
+		return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
866
+	}
867
+
868
+
869
+	/**
870
+	 * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
871
+	 *
872
+	 * @since 4.9.0
873
+	 * @return array
874
+	 */
875
+	public static function payment_status_to_message_type_array()
876
+	{
877
+		return (array) apply_filters(
878
+			'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
879
+			array(
880
+				EEM_Payment::status_id_approved => 'payment',
881
+				EEM_Payment::status_id_pending => 'payment_pending',
882
+				EEM_Payment::status_id_cancelled => 'payment_cancelled',
883
+				EEM_Payment::status_id_declined => 'payment_declined',
884
+				EEM_Payment::status_id_failed => 'payment_failed'
885
+			)
886
+		);
887
+	}
888
+
889
+
890
+
891
+
892
+	/**
893
+	 * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
894
+	 * an empty string is returned
895
+	 *
896
+	 * @since 4.9.0
897
+	 * @param $payment_status
898
+	 * @return string
899
+	 */
900
+	public static function convert_payment_status_to_message_type($payment_status)
901
+	{
902
+		$payment_status_array = self::payment_status_to_message_type_array();
903
+		return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
904
+	}
905
+
906
+
907
+	/**
908
+	 * This is used to retrieve the template pack for the given name.
909
+	 *
910
+	 * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
911
+	 *
912
+	 * @return EE_Messages_Template_Pack
913
+	 */
914
+	public static function get_template_pack($template_pack_name)
915
+	{
916
+		if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
917
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
918
+		}
919
+
920
+		// first see if in collection already
921
+		$template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
922
+
923
+		if ($template_pack instanceof EE_Messages_Template_Pack) {
924
+			return $template_pack;
925
+		}
926
+
927
+		// nope...let's get it.
928
+		// not set yet so let's attempt to get it.
929
+		$pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
930
+			' ',
931
+			'_',
932
+			ucwords(
933
+				str_replace('_', ' ', $template_pack_name)
934
+			)
935
+		);
936
+		if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
937
+			return self::get_template_pack('default');
938
+		} else {
939
+			$template_pack = new $pack_class_name();
940
+			self::$_template_pack_collection->add($template_pack);
941
+			return $template_pack;
942
+		}
943
+	}
944
+
945
+
946
+
947
+
948
+	/**
949
+	 * Globs template packs installed in core and returns the template pack collection with all installed template packs
950
+	 * in it.
951
+	 *
952
+	 * @since 4.9.0
953
+	 *
954
+	 * @return EE_Messages_Template_Pack_Collection
955
+	 */
956
+	public static function get_template_pack_collection()
957
+	{
958
+		$new_collection = false;
959
+		if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
960
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
961
+			$new_collection = true;
962
+		}
963
+
964
+		// glob the defaults directory for messages
965
+		$templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
966
+		foreach ($templates as $template_path) {
967
+			// grab folder name
968
+			$template = basename($template_path);
969
+
970
+			if (! $new_collection) {
971
+				// already have it?
972
+				if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
973
+					continue;
974
+				}
975
+			}
976
+
977
+			// setup classname.
978
+			$template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
979
+				' ',
980
+				'_',
981
+				ucwords(
982
+					str_replace(
983
+						'_',
984
+						' ',
985
+						$template
986
+					)
987
+				)
988
+			);
989
+			if (! class_exists($template_pack_class_name)) {
990
+				continue;
991
+			}
992
+			self::$_template_pack_collection->add(new $template_pack_class_name());
993
+		}
994
+
995
+		/**
996
+		 * Filter for plugins to add in any additional template packs
997
+		 * Note the filter name here is for backward compat, this used to be found in EED_Messages.
998
+		 */
999
+		$additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
1000
+		foreach ((array) $additional_template_packs as $template_pack) {
1001
+			if (
1002
+				self::$_template_pack_collection->get_by_name(
1003
+					$template_pack->dbref
1004
+				) instanceof EE_Messages_Template_Pack
1005
+			) {
1006
+				continue;
1007
+			}
1008
+			self::$_template_pack_collection->add($template_pack);
1009
+		}
1010
+		return self::$_template_pack_collection;
1011
+	}
1012
+
1013
+
1014
+	/**
1015
+	 * This is a wrapper for the protected _create_new_templates function
1016
+	 *
1017
+	 * @param string $messenger_name
1018
+	 * @param string $message_type_name message type that the templates are being created for
1019
+	 * @param int    $GRP_ID
1020
+	 * @param bool   $global
1021
+	 * @return array
1022
+	 * @throws EE_Error
1023
+	 * @throws ReflectionException
1024
+	 */
1025
+	public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1026
+	{
1027
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1028
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1029
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1030
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1031
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1032
+			return array();
1033
+		}
1034
+		// whew made it this far!  Okay, let's go ahead and create the templates then
1035
+		return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * @param EE_messenger     $messenger
1041
+	 * @param EE_message_type  $message_type
1042
+	 * @param                  $GRP_ID
1043
+	 * @param                  $global
1044
+	 * @return array|mixed
1045
+	 * @throws EE_Error
1046
+	 * @throws ReflectionException
1047
+	 */
1048
+	protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1049
+	{
1050
+		// if we're creating a custom template then we don't need to use the defaults class
1051
+		if (! $global) {
1052
+			return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1053
+		}
1054
+		/** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1055
+		$Message_Template_Defaults = EE_Registry::factory(
1056
+			'EE_Messages_Template_Defaults',
1057
+			array( $messenger, $message_type, $GRP_ID )
1058
+		);
1059
+		// generate templates
1060
+		$success = $Message_Template_Defaults->create_new_templates();
1061
+
1062
+		// if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1063
+		// its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1064
+		// attempts.
1065
+		if (! $success) {
1066
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
1067
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1068
+			$message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1069
+		}
1070
+
1071
+		/**
1072
+		 * $success is in an array in the following format
1073
+		 * array(
1074
+		 *    'GRP_ID' => $new_grp_id,
1075
+		 *    'MTP_context' => $first_context_in_new_templates,
1076
+		 * )
1077
+		 */
1078
+		return $success;
1079
+	}
1080
+
1081
+
1082
+	/**
1083
+	 * This creates a custom template using the incoming GRP_ID
1084
+	 *
1085
+	 * @param EE_messenger    $messenger
1086
+	 * @param EE_message_type $message_type
1087
+	 * @param int             $GRP_ID           GRP_ID for the template_group being used as the base
1088
+	 * @return  array $success              This will be an array in the format:
1089
+	 *                                          array(
1090
+	 *                                          'GRP_ID' => $new_grp_id,
1091
+	 *                                          'MTP_context' => $first_context_in_created_template
1092
+	 *                                          )
1093
+	 * @throws EE_Error
1094
+	 * @throws ReflectionException
1095
+	 * @access private
1096
+	 */
1097
+	private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1098
+	{
1099
+		// defaults
1100
+		$success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1101
+		// get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1102
+		$Message_Template_Group = empty($GRP_ID)
1103
+			? EEM_Message_Template_Group::instance()->get_one(
1104
+				array(
1105
+					array(
1106
+						'MTP_messenger'    => $messenger->name,
1107
+						'MTP_message_type' => $message_type->name,
1108
+						'MTP_is_global'    => true
1109
+					)
1110
+				)
1111
+			)
1112
+			: EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1113
+		// if we don't have a mtg at this point then we need to bail.
1114
+		if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1115
+			EE_Error::add_error(
1116
+				sprintf(
1117
+					esc_html__(
1118
+						'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1119
+						'event_espresso'
1120
+					),
1121
+					$GRP_ID
1122
+				),
1123
+				__FILE__,
1124
+				__FUNCTION__,
1125
+				__LINE__
1126
+			);
1127
+			return $success;
1128
+		}
1129
+		// let's get all the related message_template objects for this group.
1130
+		$message_templates = $Message_Template_Group->message_templates();
1131
+		// now we have what we need to setup the new template
1132
+		$new_mtg = clone $Message_Template_Group;
1133
+		$new_mtg->set('GRP_ID', 0);
1134
+		$new_mtg->set('MTP_is_global', false);
1135
+
1136
+		/** @var RequestInterface $request */
1137
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1138
+		$template_name = $request->isAjax() && $request->requestParamIsSet('templateName')
1139
+			? $request->getRequestParam('templateName')
1140
+			: esc_html__('New Custom Template', 'event_espresso');
1141
+		$template_description = $request->isAjax() && $request->requestParamIsSet('templateDescription')
1142
+			? $request->getRequestParam('templateDescription')
1143
+			: sprintf(
1144
+				esc_html__(
1145
+					'This is a custom template that was created for the %s messenger and %s message type.',
1146
+					'event_espresso'
1147
+				),
1148
+				$new_mtg->messenger_obj()->label['singular'],
1149
+				$new_mtg->message_type_obj()->label['singular']
1150
+			);
1151
+		$new_mtg->set('MTP_name', $template_name);
1152
+		$new_mtg->set('MTP_description', $template_description);
1153
+		// remove ALL relations on this template group so they don't get saved!
1154
+		$new_mtg->_remove_relations('Message_Template');
1155
+		$new_mtg->save();
1156
+		$success['GRP_ID'] = $new_mtg->ID();
1157
+		$success['template_name'] = $template_name;
1158
+		// add new message templates and add relation to.
1159
+		foreach ($message_templates as $message_template) {
1160
+			if (! $message_template instanceof EE_Message_Template) {
1161
+				continue;
1162
+			}
1163
+			$new_message_template = clone $message_template;
1164
+			$new_message_template->set('MTP_ID', 0);
1165
+			$new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1166
+			$new_message_template->save();
1167
+			if (empty($success['MTP_context'])) {
1168
+				$success['MTP_context'] = $new_message_template->get('MTP_context');
1169
+			}
1170
+		}
1171
+		return $success;
1172
+	}
1173
+
1174
+
1175
+	/**
1176
+	 * message_type_has_active_templates_for_messenger
1177
+	 *
1178
+	 * @param EE_messenger    $messenger
1179
+	 * @param EE_message_type $message_type
1180
+	 * @param bool            $global
1181
+	 * @return bool
1182
+	 * @throws EE_Error
1183
+	 */
1184
+	public static function message_type_has_active_templates_for_messenger(
1185
+		EE_messenger $messenger,
1186
+		EE_message_type $message_type,
1187
+		$global = false
1188
+	) {
1189
+		// is given message_type valid for given messenger (if this is not a global save)
1190
+		if ($global) {
1191
+			return true;
1192
+		}
1193
+		$active_templates = EEM_Message_Template_Group::instance()->count(
1194
+			array(
1195
+				array(
1196
+					'MTP_is_active'    => true,
1197
+					'MTP_messenger'    => $messenger->name,
1198
+					'MTP_message_type' => $message_type->name
1199
+				)
1200
+			)
1201
+		);
1202
+		if ($active_templates > 0) {
1203
+			return true;
1204
+		}
1205
+		EE_Error::add_error(
1206
+			sprintf(
1207
+				esc_html__(
1208
+					'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1209
+					'event_espresso'
1210
+				),
1211
+				$message_type->name,
1212
+				$messenger->name
1213
+			),
1214
+			__FILE__,
1215
+			__FUNCTION__,
1216
+			__LINE__
1217
+		);
1218
+		return false;
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * get_fields
1224
+	 * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1225
+	 *
1226
+	 * @param string $messenger_name    name of EE_messenger
1227
+	 * @param string $message_type_name name of EE_message_type
1228
+	 * @return array
1229
+	 * @throws EE_Error
1230
+	 * @throws ReflectionException
1231
+	 */
1232
+	public static function get_fields($messenger_name, $message_type_name)
1233
+	{
1234
+		$template_fields = array();
1235
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1236
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1237
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1238
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1239
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1240
+			return array();
1241
+		}
1242
+
1243
+		$excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1244
+
1245
+		// okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1246
+		foreach ($message_type->get_contexts() as $context => $details) {
1247
+			foreach ($messenger->get_template_fields() as $field => $value) {
1248
+				if (in_array($field, $excluded_fields_for_messenger, true)) {
1249
+					continue;
1250
+				}
1251
+				$template_fields[ $context ][ $field ] = $value;
1252
+			}
1253
+		}
1254
+		if (empty($template_fields)) {
1255
+			EE_Error::add_error(
1256
+				esc_html__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1257
+				__FILE__,
1258
+				__FUNCTION__,
1259
+				__LINE__
1260
+			);
1261
+			return array();
1262
+		}
1263
+		return $template_fields;
1264
+	}
1265 1265
 }
Please login to merge, or discard this patch.
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
             }
96 96
             $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
97 97
 
98
-            if (! $new_message_template_group) {
98
+            if ( ! $new_message_template_group) {
99 99
                 continue;
100 100
             }
101 101
             $templates[] = $new_message_template_group;
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
                     )
131 131
                 )
132 132
             )
133
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
133
+            : EEM_Message_Template::instance()->count(array(array('GRP_ID' => $GRP_ID)));
134 134
 
135 135
         return $count > 0;
136 136
     }
@@ -147,14 +147,14 @@  discard block
 block discarded – undo
147 147
      */
148 148
     public static function update_to_active($messenger_names, $message_type_names)
149 149
     {
150
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
151
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
150
+        $messenger_names = is_array($messenger_names) ? $messenger_names : array($messenger_names);
151
+        $message_type_names = is_array($message_type_names) ? $message_type_names : array($message_type_names);
152 152
         return EEM_Message_Template_Group::instance()->update(
153
-            array( 'MTP_is_active' => 1 ),
153
+            array('MTP_is_active' => 1),
154 154
             array(
155 155
                 array(
156
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
157
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
156
+                    'MTP_messenger'     => array('IN', $messenger_names),
157
+                    'MTP_message_type'  => array('IN', $message_type_names)
158 158
                 )
159 159
             )
160 160
         );
@@ -242,13 +242,13 @@  discard block
 block discarded – undo
242 242
         $messenger = $message_resource_manager->get_messenger($messenger);
243 243
 
244 244
         // if messenger isn't a EE_messenger resource then bail.
245
-        if (! $messenger instanceof EE_messenger) {
245
+        if ( ! $messenger instanceof EE_messenger) {
246 246
             return array();
247 247
         }
248 248
 
249 249
         // validate class for getting our list of shortcodes
250
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
251
-        if (! class_exists($classname)) {
250
+        $classname = 'EE_Messages_'.$messenger_name.'_'.$mt_name.'_Validator';
251
+        if ( ! class_exists($classname)) {
252 252
             $msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
253 253
             $msg[] = sprintf(
254 254
                 esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
@@ -264,44 +264,44 @@  discard block
 block discarded – undo
264 264
         // let's make sure we're only getting the shortcode part of the validators
265 265
         $shortcodes = array();
266 266
         foreach ($valid_shortcodes as $field => $validators) {
267
-            $shortcodes[ $field ] = $validators['shortcodes'];
267
+            $shortcodes[$field] = $validators['shortcodes'];
268 268
         }
269 269
         $valid_shortcodes = $shortcodes;
270 270
 
271 271
         // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
272
-        if (! empty($fields)) {
272
+        if ( ! empty($fields)) {
273 273
             $specified_shortcodes = array();
274 274
             foreach ($fields as $field) {
275
-                if (isset($valid_shortcodes[ $field ])) {
276
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
275
+                if (isset($valid_shortcodes[$field])) {
276
+                    $specified_shortcodes[$field] = $valid_shortcodes[$field];
277 277
                 }
278 278
             }
279 279
             $valid_shortcodes = $specified_shortcodes;
280 280
         }
281 281
 
282 282
         // if not merged then let's replace the fields with the localized fields
283
-        if (! $merged) {
283
+        if ( ! $merged) {
284 284
             // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
285 285
             $field_settings = $messenger->get_template_fields();
286 286
             $localized = array();
287 287
             foreach ($valid_shortcodes as $field => $shortcodes) {
288 288
                 // get localized field label
289
-                if (isset($field_settings[ $field ])) {
289
+                if (isset($field_settings[$field])) {
290 290
                     // possible that this is used as a main field.
291
-                    if (empty($field_settings[ $field ])) {
292
-                        if (isset($field_settings['extra'][ $field ])) {
293
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
291
+                    if (empty($field_settings[$field])) {
292
+                        if (isset($field_settings['extra'][$field])) {
293
+                            $_field = $field_settings['extra'][$field]['main']['label'];
294 294
                         } else {
295 295
                             $_field = $field;
296 296
                         }
297 297
                     } else {
298
-                        $_field = $field_settings[ $field ]['label'];
298
+                        $_field = $field_settings[$field]['label'];
299 299
                     }
300 300
                 } elseif (isset($field_settings['extra'])) {
301 301
                     // loop through extra "main fields" and see if any of their children have our field
302 302
                     foreach ($field_settings['extra'] as $fields) {
303
-                        if (isset($fields[ $field ])) {
304
-                            $_field = $fields[ $field ]['label'];
303
+                        if (isset($fields[$field])) {
304
+                            $_field = $fields[$field]['label'];
305 305
                         } else {
306 306
                             $_field = $field;
307 307
                         }
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
                     $_field = $field;
311 311
                 }
312 312
                 if (isset($_field)) {
313
-                    $localized[ (string) $_field ] = $shortcodes;
313
+                    $localized[(string) $_field] = $shortcodes;
314 314
                 }
315 315
             }
316 316
             $valid_shortcodes = $localized;
@@ -321,10 +321,10 @@  discard block
 block discarded – undo
321 321
             $merged_codes = array();
322 322
             foreach ($valid_shortcodes as $shortcode) {
323 323
                 foreach ($shortcode as $code => $label) {
324
-                    if (isset($merged_codes[ $code ])) {
324
+                    if (isset($merged_codes[$code])) {
325 325
                         continue;
326 326
                     } else {
327
-                        $merged_codes[ $code ] = $label;
327
+                        $merged_codes[$code] = $label;
328 328
                     }
329 329
                 }
330 330
             }
@@ -475,12 +475,12 @@  discard block
 block discarded – undo
475 475
         $sending_messenger = ''
476 476
     ) {
477 477
         // first determine if the url can be to the EE_Message object.
478
-        if (! $message_type->always_generate()) {
478
+        if ( ! $message_type->always_generate()) {
479 479
             return EEH_MSG_Template::generate_browser_trigger($message);
480 480
         }
481 481
 
482 482
         // if $registration object is not valid then exit early because there's nothing that can be generated.
483
-        if (! $registration instanceof EE_Registration) {
483
+        if ( ! $registration instanceof EE_Registration) {
484 484
             throw new EE_Error(
485 485
                 esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
486 486
             );
@@ -488,7 +488,7 @@  discard block
 block discarded – undo
488 488
 
489 489
         // validate given context
490 490
         $contexts = $message_type->get_contexts();
491
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
491
+        if ($message->context() !== '' && ! isset($contexts[$message->context()])) {
492 492
             throw new EE_Error(
493 493
                 sprintf(
494 494
                     esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
@@ -499,11 +499,11 @@  discard block
 block discarded – undo
499 499
         }
500 500
 
501 501
         // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
502
-        if (! empty($sending_messenger)) {
502
+        if ( ! empty($sending_messenger)) {
503 503
             $with_messengers = $message_type->with_messengers();
504 504
             if (
505
-                ! isset($with_messengers[ $message->messenger() ])
506
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
505
+                ! isset($with_messengers[$message->messenger()])
506
+                 || ! in_array($sending_messenger, $with_messengers[$message->messenger()])
507 507
             ) {
508 508
                 throw new EE_Error(
509 509
                     sprintf(
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
     public static function get_message_action_icon($type)
637 637
     {
638 638
         $action_icons = self::get_message_action_icons();
639
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
639
+        return isset($action_icons[$type]) ? $action_icons[$type] : [];
640 640
     }
641 641
 
642 642
 
@@ -701,7 +701,7 @@  discard block
 block discarded – undo
701 701
     public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
702 702
     {
703 703
         $action_urls = self::get_message_action_urls($message, $query_params);
704
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
704
+        return isset($action_urls[$type]) ? $action_urls[$type] : '';
705 705
     }
706 706
 
707 707
 
@@ -722,7 +722,7 @@  discard block
 block discarded – undo
722 722
         EE_Registry::instance()->load_helper('URL');
723 723
         // if $message is not an instance of EE_Message then let's just do a dummy.
724 724
         $message = empty($message) ? EE_Message_Factory::create() : $message;
725
-        $action_urls =  apply_filters(
725
+        $action_urls = apply_filters(
726 726
             'FHEE__EEH_MSG_Template__get_message_action_url',
727 727
             array(
728 728
                 'view' => EEH_MSG_Template::generate_browser_trigger($message),
@@ -805,7 +805,7 @@  discard block
 block discarded – undo
805 805
     {
806 806
         $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
807 807
         $icon_css = EEH_MSG_Template::get_message_action_icon($type);
808
-        $title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
808
+        $title = isset($icon_css['label']) ? 'title="'.$icon_css['label'].'"' : '';
809 809
 
810 810
         if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
811 811
             return '';
@@ -814,14 +814,14 @@  discard block
 block discarded – undo
814 814
         $icon_css['css_class'] .= esc_attr(
815 815
             apply_filters(
816 816
                 'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
817
-                ' js-ee-message-action-link ee-message-action-link-' . $type,
817
+                ' js-ee-message-action-link ee-message-action-link-'.$type,
818 818
                 $type,
819 819
                 $message,
820 820
                 $query_params
821 821
             )
822 822
         );
823 823
 
824
-        return '<a href="' . $url . '" ' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
824
+        return '<a href="'.$url.'" '.$title.'><span class="'.esc_attr($icon_css['css_class']).'"></span></a>';
825 825
     }
826 826
 
827 827
 
@@ -862,7 +862,7 @@  discard block
 block discarded – undo
862 862
     public static function convert_reg_status_to_message_type($reg_status)
863 863
     {
864 864
         $reg_status_array = self::reg_status_to_message_type_array();
865
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
865
+        return isset($reg_status_array[$reg_status]) ? $reg_status_array[$reg_status] : '';
866 866
     }
867 867
 
868 868
 
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
     public static function convert_payment_status_to_message_type($payment_status)
901 901
     {
902 902
         $payment_status_array = self::payment_status_to_message_type_array();
903
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
903
+        return isset($payment_status_array[$payment_status]) ? $payment_status_array[$payment_status] : '';
904 904
     }
905 905
 
906 906
 
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
      */
914 914
     public static function get_template_pack($template_pack_name)
915 915
     {
916
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
916
+        if ( ! self::$_template_pack_collection instanceof EE_Object_Collection) {
917 917
             self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
918 918
         }
919 919
 
@@ -926,14 +926,14 @@  discard block
 block discarded – undo
926 926
 
927 927
         // nope...let's get it.
928 928
         // not set yet so let's attempt to get it.
929
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
929
+        $pack_class_name = 'EE_Messages_Template_Pack_'.str_replace(
930 930
             ' ',
931 931
             '_',
932 932
             ucwords(
933 933
                 str_replace('_', ' ', $template_pack_name)
934 934
             )
935 935
         );
936
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
936
+        if ( ! class_exists($pack_class_name) && $template_pack_name !== 'default') {
937 937
             return self::get_template_pack('default');
938 938
         } else {
939 939
             $template_pack = new $pack_class_name();
@@ -956,18 +956,18 @@  discard block
 block discarded – undo
956 956
     public static function get_template_pack_collection()
957 957
     {
958 958
         $new_collection = false;
959
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
959
+        if ( ! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
960 960
             self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
961 961
             $new_collection = true;
962 962
         }
963 963
 
964 964
         // glob the defaults directory for messages
965
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
965
+        $templates = glob(EE_LIBRARIES.'messages/defaults/*', GLOB_ONLYDIR);
966 966
         foreach ($templates as $template_path) {
967 967
             // grab folder name
968 968
             $template = basename($template_path);
969 969
 
970
-            if (! $new_collection) {
970
+            if ( ! $new_collection) {
971 971
                 // already have it?
972 972
                 if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
973 973
                     continue;
@@ -975,7 +975,7 @@  discard block
 block discarded – undo
975 975
             }
976 976
 
977 977
             // setup classname.
978
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
978
+            $template_pack_class_name = 'EE_Messages_Template_Pack_'.str_replace(
979 979
                 ' ',
980 980
                 '_',
981 981
                 ucwords(
@@ -986,7 +986,7 @@  discard block
 block discarded – undo
986 986
                     )
987 987
                 )
988 988
             );
989
-            if (! class_exists($template_pack_class_name)) {
989
+            if ( ! class_exists($template_pack_class_name)) {
990 990
                 continue;
991 991
             }
992 992
             self::$_template_pack_collection->add(new $template_pack_class_name());
@@ -1028,7 +1028,7 @@  discard block
 block discarded – undo
1028 1028
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1029 1029
         $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1030 1030
         $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1031
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1031
+        if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1032 1032
             return array();
1033 1033
         }
1034 1034
         // whew made it this far!  Okay, let's go ahead and create the templates then
@@ -1048,13 +1048,13 @@  discard block
 block discarded – undo
1048 1048
     protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1049 1049
     {
1050 1050
         // if we're creating a custom template then we don't need to use the defaults class
1051
-        if (! $global) {
1051
+        if ( ! $global) {
1052 1052
             return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1053 1053
         }
1054 1054
         /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1055 1055
         $Message_Template_Defaults = EE_Registry::factory(
1056 1056
             'EE_Messages_Template_Defaults',
1057
-            array( $messenger, $message_type, $GRP_ID )
1057
+            array($messenger, $message_type, $GRP_ID)
1058 1058
         );
1059 1059
         // generate templates
1060 1060
         $success = $Message_Template_Defaults->create_new_templates();
@@ -1062,7 +1062,7 @@  discard block
 block discarded – undo
1062 1062
         // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1063 1063
         // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1064 1064
         // attempts.
1065
-        if (! $success) {
1065
+        if ( ! $success) {
1066 1066
             /** @var EE_Message_Resource_Manager $message_resource_manager */
1067 1067
             $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1068 1068
             $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
@@ -1097,7 +1097,7 @@  discard block
 block discarded – undo
1097 1097
     private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1098 1098
     {
1099 1099
         // defaults
1100
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1100
+        $success = array('GRP_ID' => null, 'MTP_context' => '');
1101 1101
         // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1102 1102
         $Message_Template_Group = empty($GRP_ID)
1103 1103
             ? EEM_Message_Template_Group::instance()->get_one(
@@ -1111,7 +1111,7 @@  discard block
 block discarded – undo
1111 1111
             )
1112 1112
             : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1113 1113
         // if we don't have a mtg at this point then we need to bail.
1114
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1114
+        if ( ! $Message_Template_Group instanceof EE_Message_Template_Group) {
1115 1115
             EE_Error::add_error(
1116 1116
                 sprintf(
1117 1117
                     esc_html__(
@@ -1157,7 +1157,7 @@  discard block
 block discarded – undo
1157 1157
         $success['template_name'] = $template_name;
1158 1158
         // add new message templates and add relation to.
1159 1159
         foreach ($message_templates as $message_template) {
1160
-            if (! $message_template instanceof EE_Message_Template) {
1160
+            if ( ! $message_template instanceof EE_Message_Template) {
1161 1161
                 continue;
1162 1162
             }
1163 1163
             $new_message_template = clone $message_template;
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
         $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1237 1237
         $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1238 1238
         $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1239
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1239
+        if ( ! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1240 1240
             return array();
1241 1241
         }
1242 1242
 
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
                 if (in_array($field, $excluded_fields_for_messenger, true)) {
1249 1249
                     continue;
1250 1250
                 }
1251
-                $template_fields[ $context ][ $field ] = $value;
1251
+                $template_fields[$context][$field] = $value;
1252 1252
             }
1253 1253
         }
1254 1254
         if (empty($template_fields)) {
Please login to merge, or discard this patch.
core/helpers/EEH_Autoloader.helper.php 2 patches
Indentation   +292 added lines, -292 removed lines patch added patch discarded remove patch
@@ -15,296 +15,296 @@
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     *    instance of the EE_System object
20
-     *
21
-     * @var    $_instance
22
-     * @access    private
23
-     */
24
-    private static $_instance = null;
25
-
26
-    /**
27
-    *   $_autoloaders
28
-    *   @var array $_autoloaders
29
-    *   @access     private
30
-    */
31
-    private static $_autoloaders;
32
-
33
-    /**
34
-     * set to "paths" to display autoloader class => path mappings
35
-     * set to "times" to display autoloader loading times
36
-     * set to "all" to display both
37
-     *
38
-     * @var string $debug
39
-     * @access    private
40
-     */
41
-    public static $debug = false;
42
-
43
-
44
-    /**
45
-     *    class constructor
46
-     *
47
-     * @access    private
48
-     * @return \EEH_Autoloader
49
-     * @throws Exception
50
-     */
51
-    private function __construct()
52
-    {
53
-        if (self::$_autoloaders === null) {
54
-            self::$_autoloaders = array();
55
-            $this->_register_custom_autoloaders();
56
-            spl_autoload_register(array( $this, 'espresso_autoloader' ));
57
-        }
58
-    }
59
-
60
-
61
-
62
-    /**
63
-     * @access public
64
-     * @return EEH_Autoloader
65
-     */
66
-    public static function instance()
67
-    {
68
-        // check if class object is instantiated
69
-        if (! self::$_instance instanceof EEH_Autoloader) {
70
-            self::$_instance = new self();
71
-        }
72
-        return self::$_instance;
73
-    }
74
-
75
-
76
-
77
-    /**
78
-     *    espresso_autoloader
79
-     *
80
-     * @access    public
81
-     * @param   $class_name
82
-     * @internal  param $className
83
-     * @internal  param string $class_name - simple class name ie: session
84
-     * @return  void
85
-     */
86
-    public static function espresso_autoloader($class_name)
87
-    {
88
-        if (isset(self::$_autoloaders[ $class_name ])) {
89
-            require_once(self::$_autoloaders[ $class_name ]);
90
-        }
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     *    register_autoloader
97
-     *
98
-     * @access    public
99
-     * @param array | string $class_paths - array of key => value pairings between class names and paths
100
-     * @param bool           $read_check  true if we need to check whether the file is readable or not.
101
-     * @param bool           $debug **deprecated**
102
-     * @throws \EE_Error
103
-     */
104
-    public static function register_autoloader($class_paths, $read_check = true, $debug = false)
105
-    {
106
-        $class_paths = is_array($class_paths) ? $class_paths : array( $class_paths );
107
-        foreach ($class_paths as $class => $path) {
108
-            // skip all files that are not PHP
109
-            if (substr($path, strlen($path) - 3) !== 'php') {
110
-                continue;
111
-            }
112
-            // don't give up! you gotta...
113
-            // get some class
114
-            if (empty($class)) {
115
-                throw new EE_Error(sprintf(esc_html__('No Class name was specified while registering an autoloader for the following path: %s.', 'event_espresso'), $path));
116
-            }
117
-            // one day you will find the path young grasshopper
118
-            if (empty($path)) {
119
-                throw new EE_Error(sprintf(esc_html__('No path was specified while registering an autoloader for the %s class.', 'event_espresso'), $class));
120
-            }
121
-            // is file readable ?
122
-            if ($read_check && ! is_readable($path)) {
123
-                throw new EE_Error(sprintf(esc_html__('The file for the %s class could not be found or is not readable due to file permissions. Please ensure the following path is correct: %s', 'event_espresso'), $class, $path));
124
-            }
125
-            if (! isset(self::$_autoloaders[ $class ])) {
126
-                self::$_autoloaders[ $class ] = str_replace(array( '/', '\\' ), '/', $path);
127
-                if (EE_DEBUG && ( EEH_Autoloader::$debug === 'paths' || EEH_Autoloader::$debug === 'all' || $debug )) {
128
-                    EEH_Debug_Tools::printr(self::$_autoloaders[ $class ], $class, __FILE__, __LINE__);
129
-                }
130
-            }
131
-        }
132
-    }
133
-
134
-
135
-
136
-
137
-    /**
138
-     *  get_autoloaders
139
-     *
140
-     *  @access public
141
-     *  @return array
142
-     */
143
-    public static function get_autoloaders()
144
-    {
145
-        return self::$_autoloaders;
146
-    }
147
-
148
-
149
-    /**
150
-     *  register core, model and class 'autoloaders'
151
-     *
152
-     * @access private
153
-     * @return void
154
-     * @throws EE_Error
155
-     */
156
-    private function _register_custom_autoloaders()
157
-    {
158
-        EEH_Autoloader::$debug = '';
159
-        \EEH_Autoloader::register_helpers_autoloaders();
160
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'interfaces');
161
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE);
162
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_INTERFACES, true);
163
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_MODELS, true);
164
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CLASSES);
165
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_FORM_SECTIONS, true);
166
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'messages');
167
-        if (EEH_Autoloader::$debug === 'times' || EEH_Autoloader::$debug === 'all') {
168
-            EEH_Debug_Tools::instance()->show_times();
169
-        }
170
-    }
171
-
172
-
173
-
174
-    /**
175
-     *    register core, model and class 'autoloaders'
176
-     *
177
-     * @access public
178
-     */
179
-    public static function register_helpers_autoloaders()
180
-    {
181
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_HELPERS);
182
-    }
183
-
184
-
185
-
186
-
187
-    /**
188
-     *  register core, model and class 'autoloaders'
189
-     *
190
-     *  @access public
191
-     *  @return void
192
-     */
193
-    public static function register_form_sections_autoloaders()
194
-    {
195
-        // EEH_Autoloader::register_autoloaders_for_each_file_in_folder( EE_FORM_SECTIONS, true );
196
-    }
197
-
198
-
199
-    /**
200
-     *  register core, model and class 'autoloaders'
201
-     *
202
-     * @access public
203
-     * @return void
204
-     * @throws EE_Error
205
-     */
206
-    public static function register_line_item_display_autoloaders()
207
-    {
208
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'line_item_display', true);
209
-    }
210
-
211
-
212
-    /**
213
-     *  register core, model and class 'autoloaders'
214
-     *
215
-     * @access public
216
-     * @return void
217
-     * @throws EE_Error
218
-     */
219
-    public static function register_line_item_filter_autoloaders()
220
-    {
221
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'line_item_filters', true);
222
-    }
223
-
224
-
225
-    /**
226
-     *  register template part 'autoloaders'
227
-     *
228
-     * @access public
229
-     * @return void
230
-     * @throws EE_Error
231
-     */
232
-    public static function register_template_part_autoloaders()
233
-    {
234
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'template_parts', true);
235
-    }
236
-
237
-
238
-    /**
239
-     * @return void
240
-     * @throws EE_Error
241
-     */
242
-    public static function register_business_classes()
243
-    {
244
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'business');
245
-    }
246
-
247
-
248
-
249
-    /**
250
-     * Assumes all the files in this folder have the normal naming scheme (namely that their classname
251
-     * is the file's name, plus ".whatever.php".) and adds each of them to the autoloader list.
252
-     * If that's not the case, you'll need to improve this function or just use EEH_File::get_classname_from_filepath_with_standard_filename() directly.
253
-     * Yes this has to scan the directory for files, but it only does it once -- not on EACH
254
-     * time the autoloader is used
255
-     *
256
-     * @param string $folder name, with or without trailing /, doesn't matter
257
-     * @param bool   $recursive
258
-     * @param bool   $debug  **deprecated**
259
-     * @throws \EE_Error
260
-     */
261
-    public static function register_autoloaders_for_each_file_in_folder($folder, $recursive = false, $debug = false)
262
-    {
263
-        if (EEH_Autoloader::$debug === 'times' || EEH_Autoloader::$debug === 'all' || $debug) {
264
-            EEH_Debug_Tools::instance()->start_timer(basename($folder));
265
-        }
266
-        // make sure last char is a /
267
-        $folder .= $folder[ strlen($folder) - 1 ] !== '/' ? '/' : '';
268
-        $class_to_filepath_map = array();
269
-        $exclude = array( 'index' );
270
-        // get all the files in that folder that end in php
271
-        $filepaths = glob($folder . '*');
272
-
273
-        if (empty($filepaths)) {
274
-            return;
275
-        }
276
-
277
-        foreach ($filepaths as $filepath) {
278
-            if (substr($filepath, -4, 4) === '.php') {
279
-                $class_name = EEH_File::get_classname_from_filepath_with_standard_filename($filepath);
280
-                if (! in_array($class_name, $exclude)) {
281
-                    $class_to_filepath_map [ $class_name ] = $filepath;
282
-                }
283
-            } elseif ($recursive) {
284
-                EEH_Autoloader::register_autoloaders_for_each_file_in_folder($filepath, $recursive, $debug);
285
-            }
286
-        }
287
-        // we remove the necessity to do a is_readable() check via the $read_check flag because glob by nature will not return non_readable files/directories.
288
-        self::register_autoloader($class_to_filepath_map, false, $debug);
289
-        if (EEH_Autoloader::$debug === 'times' || EEH_Autoloader::$debug === 'all') {
290
-            EEH_Debug_Tools::instance()->stop_timer(basename($folder));
291
-        }
292
-    }
293
-
294
-
295
-
296
-    /**
297
-     * add_alias
298
-     * register additional autoloader based on variation of the classname for an existing autoloader
299
-     *
300
-     * @access    public
301
-     * @param string $class_name - simple class name ie: EE_Session
302
-     * @param string $alias - variation on class name ie: EE_session, session, etc
303
-     */
304
-    public static function add_alias($class_name, $alias)
305
-    {
306
-        if (isset(self::$_autoloaders[ $class_name ])) {
307
-            self::$_autoloaders[ $alias ] = self::$_autoloaders[ $class_name ];
308
-        }
309
-    }
18
+	/**
19
+	 *    instance of the EE_System object
20
+	 *
21
+	 * @var    $_instance
22
+	 * @access    private
23
+	 */
24
+	private static $_instance = null;
25
+
26
+	/**
27
+	 *   $_autoloaders
28
+	 *   @var array $_autoloaders
29
+	 *   @access     private
30
+	 */
31
+	private static $_autoloaders;
32
+
33
+	/**
34
+	 * set to "paths" to display autoloader class => path mappings
35
+	 * set to "times" to display autoloader loading times
36
+	 * set to "all" to display both
37
+	 *
38
+	 * @var string $debug
39
+	 * @access    private
40
+	 */
41
+	public static $debug = false;
42
+
43
+
44
+	/**
45
+	 *    class constructor
46
+	 *
47
+	 * @access    private
48
+	 * @return \EEH_Autoloader
49
+	 * @throws Exception
50
+	 */
51
+	private function __construct()
52
+	{
53
+		if (self::$_autoloaders === null) {
54
+			self::$_autoloaders = array();
55
+			$this->_register_custom_autoloaders();
56
+			spl_autoload_register(array( $this, 'espresso_autoloader' ));
57
+		}
58
+	}
59
+
60
+
61
+
62
+	/**
63
+	 * @access public
64
+	 * @return EEH_Autoloader
65
+	 */
66
+	public static function instance()
67
+	{
68
+		// check if class object is instantiated
69
+		if (! self::$_instance instanceof EEH_Autoloader) {
70
+			self::$_instance = new self();
71
+		}
72
+		return self::$_instance;
73
+	}
74
+
75
+
76
+
77
+	/**
78
+	 *    espresso_autoloader
79
+	 *
80
+	 * @access    public
81
+	 * @param   $class_name
82
+	 * @internal  param $className
83
+	 * @internal  param string $class_name - simple class name ie: session
84
+	 * @return  void
85
+	 */
86
+	public static function espresso_autoloader($class_name)
87
+	{
88
+		if (isset(self::$_autoloaders[ $class_name ])) {
89
+			require_once(self::$_autoloaders[ $class_name ]);
90
+		}
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 *    register_autoloader
97
+	 *
98
+	 * @access    public
99
+	 * @param array | string $class_paths - array of key => value pairings between class names and paths
100
+	 * @param bool           $read_check  true if we need to check whether the file is readable or not.
101
+	 * @param bool           $debug **deprecated**
102
+	 * @throws \EE_Error
103
+	 */
104
+	public static function register_autoloader($class_paths, $read_check = true, $debug = false)
105
+	{
106
+		$class_paths = is_array($class_paths) ? $class_paths : array( $class_paths );
107
+		foreach ($class_paths as $class => $path) {
108
+			// skip all files that are not PHP
109
+			if (substr($path, strlen($path) - 3) !== 'php') {
110
+				continue;
111
+			}
112
+			// don't give up! you gotta...
113
+			// get some class
114
+			if (empty($class)) {
115
+				throw new EE_Error(sprintf(esc_html__('No Class name was specified while registering an autoloader for the following path: %s.', 'event_espresso'), $path));
116
+			}
117
+			// one day you will find the path young grasshopper
118
+			if (empty($path)) {
119
+				throw new EE_Error(sprintf(esc_html__('No path was specified while registering an autoloader for the %s class.', 'event_espresso'), $class));
120
+			}
121
+			// is file readable ?
122
+			if ($read_check && ! is_readable($path)) {
123
+				throw new EE_Error(sprintf(esc_html__('The file for the %s class could not be found or is not readable due to file permissions. Please ensure the following path is correct: %s', 'event_espresso'), $class, $path));
124
+			}
125
+			if (! isset(self::$_autoloaders[ $class ])) {
126
+				self::$_autoloaders[ $class ] = str_replace(array( '/', '\\' ), '/', $path);
127
+				if (EE_DEBUG && ( EEH_Autoloader::$debug === 'paths' || EEH_Autoloader::$debug === 'all' || $debug )) {
128
+					EEH_Debug_Tools::printr(self::$_autoloaders[ $class ], $class, __FILE__, __LINE__);
129
+				}
130
+			}
131
+		}
132
+	}
133
+
134
+
135
+
136
+
137
+	/**
138
+	 *  get_autoloaders
139
+	 *
140
+	 *  @access public
141
+	 *  @return array
142
+	 */
143
+	public static function get_autoloaders()
144
+	{
145
+		return self::$_autoloaders;
146
+	}
147
+
148
+
149
+	/**
150
+	 *  register core, model and class 'autoloaders'
151
+	 *
152
+	 * @access private
153
+	 * @return void
154
+	 * @throws EE_Error
155
+	 */
156
+	private function _register_custom_autoloaders()
157
+	{
158
+		EEH_Autoloader::$debug = '';
159
+		\EEH_Autoloader::register_helpers_autoloaders();
160
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'interfaces');
161
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE);
162
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_INTERFACES, true);
163
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_MODELS, true);
164
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CLASSES);
165
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_FORM_SECTIONS, true);
166
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'messages');
167
+		if (EEH_Autoloader::$debug === 'times' || EEH_Autoloader::$debug === 'all') {
168
+			EEH_Debug_Tools::instance()->show_times();
169
+		}
170
+	}
171
+
172
+
173
+
174
+	/**
175
+	 *    register core, model and class 'autoloaders'
176
+	 *
177
+	 * @access public
178
+	 */
179
+	public static function register_helpers_autoloaders()
180
+	{
181
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_HELPERS);
182
+	}
183
+
184
+
185
+
186
+
187
+	/**
188
+	 *  register core, model and class 'autoloaders'
189
+	 *
190
+	 *  @access public
191
+	 *  @return void
192
+	 */
193
+	public static function register_form_sections_autoloaders()
194
+	{
195
+		// EEH_Autoloader::register_autoloaders_for_each_file_in_folder( EE_FORM_SECTIONS, true );
196
+	}
197
+
198
+
199
+	/**
200
+	 *  register core, model and class 'autoloaders'
201
+	 *
202
+	 * @access public
203
+	 * @return void
204
+	 * @throws EE_Error
205
+	 */
206
+	public static function register_line_item_display_autoloaders()
207
+	{
208
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'line_item_display', true);
209
+	}
210
+
211
+
212
+	/**
213
+	 *  register core, model and class 'autoloaders'
214
+	 *
215
+	 * @access public
216
+	 * @return void
217
+	 * @throws EE_Error
218
+	 */
219
+	public static function register_line_item_filter_autoloaders()
220
+	{
221
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'line_item_filters', true);
222
+	}
223
+
224
+
225
+	/**
226
+	 *  register template part 'autoloaders'
227
+	 *
228
+	 * @access public
229
+	 * @return void
230
+	 * @throws EE_Error
231
+	 */
232
+	public static function register_template_part_autoloaders()
233
+	{
234
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'template_parts', true);
235
+	}
236
+
237
+
238
+	/**
239
+	 * @return void
240
+	 * @throws EE_Error
241
+	 */
242
+	public static function register_business_classes()
243
+	{
244
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'business');
245
+	}
246
+
247
+
248
+
249
+	/**
250
+	 * Assumes all the files in this folder have the normal naming scheme (namely that their classname
251
+	 * is the file's name, plus ".whatever.php".) and adds each of them to the autoloader list.
252
+	 * If that's not the case, you'll need to improve this function or just use EEH_File::get_classname_from_filepath_with_standard_filename() directly.
253
+	 * Yes this has to scan the directory for files, but it only does it once -- not on EACH
254
+	 * time the autoloader is used
255
+	 *
256
+	 * @param string $folder name, with or without trailing /, doesn't matter
257
+	 * @param bool   $recursive
258
+	 * @param bool   $debug  **deprecated**
259
+	 * @throws \EE_Error
260
+	 */
261
+	public static function register_autoloaders_for_each_file_in_folder($folder, $recursive = false, $debug = false)
262
+	{
263
+		if (EEH_Autoloader::$debug === 'times' || EEH_Autoloader::$debug === 'all' || $debug) {
264
+			EEH_Debug_Tools::instance()->start_timer(basename($folder));
265
+		}
266
+		// make sure last char is a /
267
+		$folder .= $folder[ strlen($folder) - 1 ] !== '/' ? '/' : '';
268
+		$class_to_filepath_map = array();
269
+		$exclude = array( 'index' );
270
+		// get all the files in that folder that end in php
271
+		$filepaths = glob($folder . '*');
272
+
273
+		if (empty($filepaths)) {
274
+			return;
275
+		}
276
+
277
+		foreach ($filepaths as $filepath) {
278
+			if (substr($filepath, -4, 4) === '.php') {
279
+				$class_name = EEH_File::get_classname_from_filepath_with_standard_filename($filepath);
280
+				if (! in_array($class_name, $exclude)) {
281
+					$class_to_filepath_map [ $class_name ] = $filepath;
282
+				}
283
+			} elseif ($recursive) {
284
+				EEH_Autoloader::register_autoloaders_for_each_file_in_folder($filepath, $recursive, $debug);
285
+			}
286
+		}
287
+		// we remove the necessity to do a is_readable() check via the $read_check flag because glob by nature will not return non_readable files/directories.
288
+		self::register_autoloader($class_to_filepath_map, false, $debug);
289
+		if (EEH_Autoloader::$debug === 'times' || EEH_Autoloader::$debug === 'all') {
290
+			EEH_Debug_Tools::instance()->stop_timer(basename($folder));
291
+		}
292
+	}
293
+
294
+
295
+
296
+	/**
297
+	 * add_alias
298
+	 * register additional autoloader based on variation of the classname for an existing autoloader
299
+	 *
300
+	 * @access    public
301
+	 * @param string $class_name - simple class name ie: EE_Session
302
+	 * @param string $alias - variation on class name ie: EE_session, session, etc
303
+	 */
304
+	public static function add_alias($class_name, $alias)
305
+	{
306
+		if (isset(self::$_autoloaders[ $class_name ])) {
307
+			self::$_autoloaders[ $alias ] = self::$_autoloaders[ $class_name ];
308
+		}
309
+	}
310 310
 }
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
         if (self::$_autoloaders === null) {
54 54
             self::$_autoloaders = array();
55 55
             $this->_register_custom_autoloaders();
56
-            spl_autoload_register(array( $this, 'espresso_autoloader' ));
56
+            spl_autoload_register(array($this, 'espresso_autoloader'));
57 57
         }
58 58
     }
59 59
 
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
     public static function instance()
67 67
     {
68 68
         // check if class object is instantiated
69
-        if (! self::$_instance instanceof EEH_Autoloader) {
69
+        if ( ! self::$_instance instanceof EEH_Autoloader) {
70 70
             self::$_instance = new self();
71 71
         }
72 72
         return self::$_instance;
@@ -85,8 +85,8 @@  discard block
 block discarded – undo
85 85
      */
86 86
     public static function espresso_autoloader($class_name)
87 87
     {
88
-        if (isset(self::$_autoloaders[ $class_name ])) {
89
-            require_once(self::$_autoloaders[ $class_name ]);
88
+        if (isset(self::$_autoloaders[$class_name])) {
89
+            require_once(self::$_autoloaders[$class_name]);
90 90
         }
91 91
     }
92 92
 
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
      */
104 104
     public static function register_autoloader($class_paths, $read_check = true, $debug = false)
105 105
     {
106
-        $class_paths = is_array($class_paths) ? $class_paths : array( $class_paths );
106
+        $class_paths = is_array($class_paths) ? $class_paths : array($class_paths);
107 107
         foreach ($class_paths as $class => $path) {
108 108
             // skip all files that are not PHP
109 109
             if (substr($path, strlen($path) - 3) !== 'php') {
@@ -122,10 +122,10 @@  discard block
 block discarded – undo
122 122
             if ($read_check && ! is_readable($path)) {
123 123
                 throw new EE_Error(sprintf(esc_html__('The file for the %s class could not be found or is not readable due to file permissions. Please ensure the following path is correct: %s', 'event_espresso'), $class, $path));
124 124
             }
125
-            if (! isset(self::$_autoloaders[ $class ])) {
126
-                self::$_autoloaders[ $class ] = str_replace(array( '/', '\\' ), '/', $path);
127
-                if (EE_DEBUG && ( EEH_Autoloader::$debug === 'paths' || EEH_Autoloader::$debug === 'all' || $debug )) {
128
-                    EEH_Debug_Tools::printr(self::$_autoloaders[ $class ], $class, __FILE__, __LINE__);
125
+            if ( ! isset(self::$_autoloaders[$class])) {
126
+                self::$_autoloaders[$class] = str_replace(array('/', '\\'), '/', $path);
127
+                if (EE_DEBUG && (EEH_Autoloader::$debug === 'paths' || EEH_Autoloader::$debug === 'all' || $debug)) {
128
+                    EEH_Debug_Tools::printr(self::$_autoloaders[$class], $class, __FILE__, __LINE__);
129 129
                 }
130 130
             }
131 131
         }
@@ -157,13 +157,13 @@  discard block
 block discarded – undo
157 157
     {
158 158
         EEH_Autoloader::$debug = '';
159 159
         \EEH_Autoloader::register_helpers_autoloaders();
160
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'interfaces');
160
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE.'interfaces');
161 161
         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE);
162 162
         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_INTERFACES, true);
163 163
         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_MODELS, true);
164 164
         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CLASSES);
165 165
         EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_FORM_SECTIONS, true);
166
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'messages');
166
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'messages');
167 167
         if (EEH_Autoloader::$debug === 'times' || EEH_Autoloader::$debug === 'all') {
168 168
             EEH_Debug_Tools::instance()->show_times();
169 169
         }
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
      */
206 206
     public static function register_line_item_display_autoloaders()
207 207
     {
208
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'line_item_display', true);
208
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'line_item_display', true);
209 209
     }
210 210
 
211 211
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
      */
219 219
     public static function register_line_item_filter_autoloaders()
220 220
     {
221
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'line_item_filters', true);
221
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'line_item_filters', true);
222 222
     }
223 223
 
224 224
 
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
      */
232 232
     public static function register_template_part_autoloaders()
233 233
     {
234
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'template_parts', true);
234
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'template_parts', true);
235 235
     }
236 236
 
237 237
 
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
      */
242 242
     public static function register_business_classes()
243 243
     {
244
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE . 'business');
244
+        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(EE_CORE.'business');
245 245
     }
246 246
 
247 247
 
@@ -264,11 +264,11 @@  discard block
 block discarded – undo
264 264
             EEH_Debug_Tools::instance()->start_timer(basename($folder));
265 265
         }
266 266
         // make sure last char is a /
267
-        $folder .= $folder[ strlen($folder) - 1 ] !== '/' ? '/' : '';
267
+        $folder .= $folder[strlen($folder) - 1] !== '/' ? '/' : '';
268 268
         $class_to_filepath_map = array();
269
-        $exclude = array( 'index' );
269
+        $exclude = array('index');
270 270
         // get all the files in that folder that end in php
271
-        $filepaths = glob($folder . '*');
271
+        $filepaths = glob($folder.'*');
272 272
 
273 273
         if (empty($filepaths)) {
274 274
             return;
@@ -277,8 +277,8 @@  discard block
 block discarded – undo
277 277
         foreach ($filepaths as $filepath) {
278 278
             if (substr($filepath, -4, 4) === '.php') {
279 279
                 $class_name = EEH_File::get_classname_from_filepath_with_standard_filename($filepath);
280
-                if (! in_array($class_name, $exclude)) {
281
-                    $class_to_filepath_map [ $class_name ] = $filepath;
280
+                if ( ! in_array($class_name, $exclude)) {
281
+                    $class_to_filepath_map [$class_name] = $filepath;
282 282
                 }
283 283
             } elseif ($recursive) {
284 284
                 EEH_Autoloader::register_autoloaders_for_each_file_in_folder($filepath, $recursive, $debug);
@@ -303,8 +303,8 @@  discard block
 block discarded – undo
303 303
      */
304 304
     public static function add_alias($class_name, $alias)
305 305
     {
306
-        if (isset(self::$_autoloaders[ $class_name ])) {
307
-            self::$_autoloaders[ $alias ] = self::$_autoloaders[ $class_name ];
306
+        if (isset(self::$_autoloaders[$class_name])) {
307
+            self::$_autoloaders[$alias] = self::$_autoloaders[$class_name];
308 308
         }
309 309
     }
310 310
 }
Please login to merge, or discard this patch.
core/helpers/EEH_Activation.helper.php 2 patches
Indentation   +1588 added lines, -1588 removed lines patch added patch discarded remove patch
@@ -17,237 +17,237 @@  discard block
 block discarded – undo
17 17
 class EEH_Activation implements ResettableInterface
18 18
 {
19 19
 
20
-    /**
21
-     * constant used to indicate a cron task is no longer in use
22
-     */
23
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
24
-
25
-    /**
26
-     * WP_User->ID
27
-     *
28
-     * @var int
29
-     */
30
-    private static $_default_creator_id;
31
-
32
-    /**
33
-     * indicates whether or not we've already verified core's default data during this request,
34
-     * because after migrations are done, any addons activated while in maintenance mode
35
-     * will want to setup their own default data, and they might hook into core's default data
36
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
37
-     * This prevents doing that for EVERY single addon.
38
-     *
39
-     * @var boolean
40
-     */
41
-    protected static $_initialized_db_content_already_in_this_request = false;
42
-
43
-    /**
44
-     * @var TableAnalysis $table_analysis
45
-     */
46
-    private static $table_analysis;
47
-
48
-    /**
49
-     * @var TableManager $table_manager
50
-     */
51
-    private static $table_manager;
52
-
53
-
54
-    /**
55
-     * @return TableAnalysis
56
-     * @throws EE_Error
57
-     * @throws ReflectionException
58
-     */
59
-    public static function getTableAnalysis()
60
-    {
61
-        if (! self::$table_analysis instanceof TableAnalysis) {
62
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', [], true);
63
-        }
64
-        return self::$table_analysis;
65
-    }
66
-
67
-
68
-    /**
69
-     * @return TableManager
70
-     * @throws EE_Error
71
-     * @throws ReflectionException
72
-     */
73
-    public static function getTableManager()
74
-    {
75
-        if (! self::$table_manager instanceof TableManager) {
76
-            self::$table_manager = EE_Registry::instance()->create('TableManager', [], true);
77
-        }
78
-        return self::$table_manager;
79
-    }
80
-
81
-
82
-    /**
83
-     * @param $table_name
84
-     * @return string
85
-     * @throws EE_Error
86
-     * @throws ReflectionException
87
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
88
-     */
89
-    public static function ensure_table_name_has_prefix($table_name)
90
-    {
91
-        return EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
92
-    }
93
-
94
-
95
-    /**
96
-     * ensures the EE configuration settings are loaded with at least default options set
97
-     * and that all critical EE pages have been generated with the appropriate shortcodes in place
98
-     *
99
-     * @return void
100
-     */
101
-    public static function system_initialization()
102
-    {
103
-        EEH_Activation::reset_and_update_config();
104
-        // which is fired BEFORE activation of plugin anyways
105
-        EEH_Activation::verify_default_pages_exist();
106
-    }
107
-
108
-
109
-    /**
110
-     * Sets the database schema and creates folders. This should
111
-     * be called on plugin activation and reactivation
112
-     *
113
-     * @return boolean success, whether the database and folders are setup properly
114
-     * @throws EE_Error
115
-     * @throws ReflectionException
116
-     */
117
-    public static function initialize_db_and_folders()
118
-    {
119
-        return EEH_Activation::create_database_tables();
120
-    }
121
-
122
-
123
-    /**
124
-     * assuming we have an up-to-date database schema, this will populate it
125
-     * with default and initial data. This should be called
126
-     * upon activation of a new plugin, reactivation, and at the end
127
-     * of running migration scripts
128
-     *
129
-     * @throws EE_Error
130
-     * @throws ReflectionException
131
-     */
132
-    public static function initialize_db_content()
133
-    {
134
-        // let's avoid doing all this logic repeatedly, especially when addons are requesting it
135
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
136
-            return;
137
-        }
138
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
139
-
140
-        EEH_Activation::initialize_system_questions();
141
-        EEH_Activation::insert_default_status_codes();
142
-        EEH_Activation::generate_default_message_templates();
143
-        EEH_Activation::create_no_ticket_prices_array();
144
-        EEH_Activation::removeEmailConfirmFromAddressGroup();
145
-
146
-        EEH_Activation::validate_messages_system();
147
-        EEH_Activation::insert_default_payment_methods();
148
-        // in case we've
149
-        EEH_Activation::remove_cron_tasks();
150
-        EEH_Activation::create_cron_tasks();
151
-        // remove all TXN locks since that is being done via extra meta now
152
-        delete_option('ee_locked_transactions');
153
-        // also, check for CAF default db content
154
-        do_action('AHEE__EEH_Activation__initialize_db_content');
155
-        // also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
156
-        // which users really won't care about on initial activation
157
-        EE_Error::overwrite_success();
158
-    }
159
-
160
-
161
-    /**
162
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
163
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
164
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
165
-     * (null)
166
-     *
167
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
168
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
169
-     * @return array
170
-     * @throws EE_Error
171
-     */
172
-    public static function get_cron_tasks($which_to_include)
173
-    {
174
-        $cron_tasks = apply_filters(
175
-            'FHEE__EEH_Activation__get_cron_tasks',
176
-            [
177
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
178
-                // 'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' =>
179
-                // EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
180
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
181
-                // there may have been a bug which prevented from these cron tasks from getting unscheduled,
182
-                // so we might want to remove these for a few updates
183
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
184
-            ]
185
-        );
186
-        if ($which_to_include === 'old') {
187
-            $cron_tasks = array_filter(
188
-                $cron_tasks,
189
-                function ($value) {
190
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
191
-                }
192
-            );
193
-        } elseif ($which_to_include === 'current') {
194
-            $cron_tasks = array_filter($cron_tasks);
195
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
196
-            throw new EE_Error(
197
-                sprintf(
198
-                    esc_html__(
199
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
200
-                        'event_espresso'
201
-                    ),
202
-                    $which_to_include
203
-                )
204
-            );
205
-        }
206
-        return $cron_tasks;
207
-    }
208
-
209
-
210
-    /**
211
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
212
-     *
213
-     * @throws EE_Error
214
-     */
215
-    public static function create_cron_tasks()
216
-    {
217
-
218
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
219
-            if (! wp_next_scheduled($hook_name)) {
220
-                /**
221
-                 * This allows client code to define the initial start timestamp for this schedule.
222
-                 */
223
-                if (
224
-                    is_array($frequency)
225
-                    && count($frequency) === 2
226
-                    && isset($frequency[0], $frequency[1])
227
-                ) {
228
-                    $start_timestamp = $frequency[0];
229
-                    $frequency       = $frequency[1];
230
-                } else {
231
-                    $start_timestamp = time();
232
-                }
233
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
234
-            }
235
-        }
236
-    }
237
-
238
-
239
-    /**
240
-     * Remove the currently-existing and now-removed cron tasks.
241
-     *
242
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
243
-     * @throws EE_Error
244
-     */
245
-    public static function remove_cron_tasks($remove_all = true)
246
-    {
247
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
248
-        $crons                = _get_cron_array();
249
-        $crons                = is_array($crons) ? $crons : [];
250
-        /* reminder of what $crons look like:
20
+	/**
21
+	 * constant used to indicate a cron task is no longer in use
22
+	 */
23
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
24
+
25
+	/**
26
+	 * WP_User->ID
27
+	 *
28
+	 * @var int
29
+	 */
30
+	private static $_default_creator_id;
31
+
32
+	/**
33
+	 * indicates whether or not we've already verified core's default data during this request,
34
+	 * because after migrations are done, any addons activated while in maintenance mode
35
+	 * will want to setup their own default data, and they might hook into core's default data
36
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
37
+	 * This prevents doing that for EVERY single addon.
38
+	 *
39
+	 * @var boolean
40
+	 */
41
+	protected static $_initialized_db_content_already_in_this_request = false;
42
+
43
+	/**
44
+	 * @var TableAnalysis $table_analysis
45
+	 */
46
+	private static $table_analysis;
47
+
48
+	/**
49
+	 * @var TableManager $table_manager
50
+	 */
51
+	private static $table_manager;
52
+
53
+
54
+	/**
55
+	 * @return TableAnalysis
56
+	 * @throws EE_Error
57
+	 * @throws ReflectionException
58
+	 */
59
+	public static function getTableAnalysis()
60
+	{
61
+		if (! self::$table_analysis instanceof TableAnalysis) {
62
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', [], true);
63
+		}
64
+		return self::$table_analysis;
65
+	}
66
+
67
+
68
+	/**
69
+	 * @return TableManager
70
+	 * @throws EE_Error
71
+	 * @throws ReflectionException
72
+	 */
73
+	public static function getTableManager()
74
+	{
75
+		if (! self::$table_manager instanceof TableManager) {
76
+			self::$table_manager = EE_Registry::instance()->create('TableManager', [], true);
77
+		}
78
+		return self::$table_manager;
79
+	}
80
+
81
+
82
+	/**
83
+	 * @param $table_name
84
+	 * @return string
85
+	 * @throws EE_Error
86
+	 * @throws ReflectionException
87
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
88
+	 */
89
+	public static function ensure_table_name_has_prefix($table_name)
90
+	{
91
+		return EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
92
+	}
93
+
94
+
95
+	/**
96
+	 * ensures the EE configuration settings are loaded with at least default options set
97
+	 * and that all critical EE pages have been generated with the appropriate shortcodes in place
98
+	 *
99
+	 * @return void
100
+	 */
101
+	public static function system_initialization()
102
+	{
103
+		EEH_Activation::reset_and_update_config();
104
+		// which is fired BEFORE activation of plugin anyways
105
+		EEH_Activation::verify_default_pages_exist();
106
+	}
107
+
108
+
109
+	/**
110
+	 * Sets the database schema and creates folders. This should
111
+	 * be called on plugin activation and reactivation
112
+	 *
113
+	 * @return boolean success, whether the database and folders are setup properly
114
+	 * @throws EE_Error
115
+	 * @throws ReflectionException
116
+	 */
117
+	public static function initialize_db_and_folders()
118
+	{
119
+		return EEH_Activation::create_database_tables();
120
+	}
121
+
122
+
123
+	/**
124
+	 * assuming we have an up-to-date database schema, this will populate it
125
+	 * with default and initial data. This should be called
126
+	 * upon activation of a new plugin, reactivation, and at the end
127
+	 * of running migration scripts
128
+	 *
129
+	 * @throws EE_Error
130
+	 * @throws ReflectionException
131
+	 */
132
+	public static function initialize_db_content()
133
+	{
134
+		// let's avoid doing all this logic repeatedly, especially when addons are requesting it
135
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
136
+			return;
137
+		}
138
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
139
+
140
+		EEH_Activation::initialize_system_questions();
141
+		EEH_Activation::insert_default_status_codes();
142
+		EEH_Activation::generate_default_message_templates();
143
+		EEH_Activation::create_no_ticket_prices_array();
144
+		EEH_Activation::removeEmailConfirmFromAddressGroup();
145
+
146
+		EEH_Activation::validate_messages_system();
147
+		EEH_Activation::insert_default_payment_methods();
148
+		// in case we've
149
+		EEH_Activation::remove_cron_tasks();
150
+		EEH_Activation::create_cron_tasks();
151
+		// remove all TXN locks since that is being done via extra meta now
152
+		delete_option('ee_locked_transactions');
153
+		// also, check for CAF default db content
154
+		do_action('AHEE__EEH_Activation__initialize_db_content');
155
+		// also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
156
+		// which users really won't care about on initial activation
157
+		EE_Error::overwrite_success();
158
+	}
159
+
160
+
161
+	/**
162
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
163
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
164
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
165
+	 * (null)
166
+	 *
167
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
168
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
169
+	 * @return array
170
+	 * @throws EE_Error
171
+	 */
172
+	public static function get_cron_tasks($which_to_include)
173
+	{
174
+		$cron_tasks = apply_filters(
175
+			'FHEE__EEH_Activation__get_cron_tasks',
176
+			[
177
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
178
+				// 'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' =>
179
+				// EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
180
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
181
+				// there may have been a bug which prevented from these cron tasks from getting unscheduled,
182
+				// so we might want to remove these for a few updates
183
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
184
+			]
185
+		);
186
+		if ($which_to_include === 'old') {
187
+			$cron_tasks = array_filter(
188
+				$cron_tasks,
189
+				function ($value) {
190
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
191
+				}
192
+			);
193
+		} elseif ($which_to_include === 'current') {
194
+			$cron_tasks = array_filter($cron_tasks);
195
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
196
+			throw new EE_Error(
197
+				sprintf(
198
+					esc_html__(
199
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
200
+						'event_espresso'
201
+					),
202
+					$which_to_include
203
+				)
204
+			);
205
+		}
206
+		return $cron_tasks;
207
+	}
208
+
209
+
210
+	/**
211
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
212
+	 *
213
+	 * @throws EE_Error
214
+	 */
215
+	public static function create_cron_tasks()
216
+	{
217
+
218
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
219
+			if (! wp_next_scheduled($hook_name)) {
220
+				/**
221
+				 * This allows client code to define the initial start timestamp for this schedule.
222
+				 */
223
+				if (
224
+					is_array($frequency)
225
+					&& count($frequency) === 2
226
+					&& isset($frequency[0], $frequency[1])
227
+				) {
228
+					$start_timestamp = $frequency[0];
229
+					$frequency       = $frequency[1];
230
+				} else {
231
+					$start_timestamp = time();
232
+				}
233
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
234
+			}
235
+		}
236
+	}
237
+
238
+
239
+	/**
240
+	 * Remove the currently-existing and now-removed cron tasks.
241
+	 *
242
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
243
+	 * @throws EE_Error
244
+	 */
245
+	public static function remove_cron_tasks($remove_all = true)
246
+	{
247
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
248
+		$crons                = _get_cron_array();
249
+		$crons                = is_array($crons) ? $crons : [];
250
+		/* reminder of what $crons look like:
251 251
          * Top-level keys are timestamps, and their values are arrays.
252 252
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
253 253
          * and their values are arrays.
@@ -264,893 +264,893 @@  discard block
 block discarded – undo
264 264
          *                  ...
265 265
          *      ...
266 266
          */
267
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
268
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
269
-            if (is_array($hooks_to_fire_at_time)) {
270
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
271
-                    if (
272
-                        isset($ee_cron_tasks_to_remove[ $hook_name ])
273
-                        && is_array($ee_cron_tasks_to_remove[ $hook_name ])
274
-                    ) {
275
-                        unset($crons[ $timestamp ][ $hook_name ]);
276
-                    }
277
-                }
278
-                // also take care of any empty cron timestamps.
279
-                if (empty($hooks_to_fire_at_time)) {
280
-                    unset($crons[ $timestamp ]);
281
-                }
282
-            }
283
-        }
284
-        _set_cron_array($crons);
285
-    }
286
-
287
-
288
-    /**
289
-     * registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
290
-     *
291
-     * @return void
292
-     * @throws EE_Error
293
-     * @throws ReflectionException
294
-     */
295
-    public static function CPT_initialization()
296
-    {
297
-        // register Custom Post Types
298
-        EE_Registry::instance()->load_core('Register_CPTs');
299
-        flush_rewrite_rules();
300
-    }
301
-
302
-
303
-    /**
304
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
305
-     * If there is old calendar config data saved, then it will get converted on activation.
306
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
307
-     *
308
-     * @return void
309
-     */
310
-    public static function reset_and_update_config()
311
-    {
312
-        do_action('AHEE__EE_Config___load_core_config__start', ['EEH_Activation', 'load_calendar_config']);
313
-        add_filter(
314
-            'FHEE__EE_Config___load_core_config__config_settings',
315
-            ['EEH_Activation', 'migrate_old_config_data'],
316
-            10,
317
-            3
318
-        );
319
-        if (! EE_Config::logging_enabled()) {
320
-            delete_option(EE_Config::LOG_NAME);
321
-        }
322
-    }
323
-
324
-
325
-    /**
326
-     * @return    void
327
-     */
328
-    public static function load_calendar_config()
329
-    {
330
-        // grab array of all plugin folders and loop thru it
331
-        $plugins = glob(WP_PLUGIN_DIR . '/*', GLOB_ONLYDIR);
332
-        if (empty($plugins)) {
333
-            return;
334
-        }
335
-        foreach ($plugins as $plugin_path) {
336
-            // grab plugin folder name from path
337
-            $plugin = basename($plugin_path);
338
-            // drill down to Espresso plugins
339
-            // then to calendar related plugins
340
-            if (
341
-                strpos($plugin, 'espresso') !== false
342
-                || strpos($plugin, 'Espresso') !== false
343
-                || strpos($plugin, 'ee4') !== false
344
-                || strpos($plugin, 'EE4') !== false
345
-                || strpos($plugin, 'calendar') !== false
346
-            ) {
347
-                // this is what we are looking for
348
-                $calendar_config = $plugin_path . '/EE_Calendar_Config.php';
349
-                // does it exist in this folder ?
350
-                if (is_readable($calendar_config)) {
351
-                    // YEAH! let's load it
352
-                    require_once($calendar_config);
353
-                }
354
-            }
355
-        }
356
-    }
357
-
358
-
359
-    /**
360
-     * @param array|stdClass $settings
361
-     * @param string         $config
362
-     * @param EE_Config      $EE_Config
363
-     * @return stdClass
364
-     */
365
-    public static function migrate_old_config_data($settings = [], $config = '', EE_Config $EE_Config)
366
-    {
367
-        $convert_from_array = ['addons'];
368
-        // in case old settings were saved as an array
369
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
370
-            // convert existing settings to an object
371
-            $config_array = $settings;
372
-            $settings     = new stdClass();
373
-            foreach ($config_array as $key => $value) {
374
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
375
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
376
-                } else {
377
-                    $settings->{$key} = $value;
378
-                }
379
-            }
380
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
381
-        }
382
-        return $settings;
383
-    }
384
-
385
-
386
-    /**
387
-     * @return void
388
-     */
389
-    public static function deactivate_event_espresso()
390
-    {
391
-        // check permissions
392
-        if (current_user_can('activate_plugins')) {
393
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
394
-        }
395
-    }
396
-
397
-
398
-    /**
399
-     * @return void
400
-     * @throws InvalidDataTypeException
401
-     */
402
-    public static function verify_default_pages_exist()
403
-    {
404
-        $critical_page_problem = false;
405
-        $critical_pages        = [
406
-            [
407
-                'id'   => 'reg_page_id',
408
-                'name' => esc_html__('Registration Checkout', 'event_espresso'),
409
-                'post' => null,
410
-                'code' => 'ESPRESSO_CHECKOUT',
411
-            ],
412
-            [
413
-                'id'   => 'txn_page_id',
414
-                'name' => esc_html__('Transactions', 'event_espresso'),
415
-                'post' => null,
416
-                'code' => 'ESPRESSO_TXN_PAGE',
417
-            ],
418
-            [
419
-                'id'   => 'thank_you_page_id',
420
-                'name' => esc_html__('Thank You', 'event_espresso'),
421
-                'post' => null,
422
-                'code' => 'ESPRESSO_THANK_YOU',
423
-            ],
424
-            [
425
-                'id'   => 'cancel_page_id',
426
-                'name' => esc_html__('Registration Cancelled', 'event_espresso'),
427
-                'post' => null,
428
-                'code' => 'ESPRESSO_CANCELLED',
429
-            ],
430
-        ];
431
-        $EE_Core_Config        = EE_Registry::instance()->CFG->core;
432
-        foreach ($critical_pages as $critical_page) {
433
-            // is critical page ID set in config ?
434
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
435
-                // attempt to find post by ID
436
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
437
-            }
438
-            // no dice?
439
-            if ($critical_page['post'] === null) {
440
-                // attempt to find post by title
441
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
442
-                // still nothing?
443
-                if ($critical_page['post'] === null) {
444
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
445
-                    // REALLY? Still nothing ??!?!?
446
-                    if ($critical_page['post'] === null) {
447
-                        $msg = esc_html__(
448
-                            'The Event Espresso critical page configuration settings could not be updated.',
449
-                            'event_espresso'
450
-                        );
451
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
452
-                        break;
453
-                    }
454
-                }
455
-            }
456
-            // check that Post ID matches critical page ID in config
457
-            if (
458
-                isset($critical_page['post']->ID)
459
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
460
-            ) {
461
-                // update Config with post ID
462
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
463
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
464
-                    $msg = esc_html__(
465
-                        'The Event Espresso critical page configuration settings could not be updated.',
466
-                        'event_espresso'
467
-                    );
468
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
469
-                }
470
-            }
471
-            $critical_page_problem =
472
-                ! isset($critical_page['post']->post_status)
473
-                || $critical_page['post']->post_status !== 'publish'
474
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
475
-                    ? true
476
-                    : $critical_page_problem;
477
-        }
478
-        if ($critical_page_problem) {
479
-            new PersistentAdminNotice(
480
-                'critical_page_problem',
481
-                sprintf(
482
-                    esc_html__(
483
-                        'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
484
-                        'event_espresso'
485
-                    ),
486
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
487
-                    . esc_html__('Event Espresso Critical Pages Settings', 'event_espresso')
488
-                    . '</a>'
489
-                )
490
-            );
491
-        }
492
-        if (EE_Error::has_notices()) {
493
-            EE_Error::get_notices(false, true);
494
-        }
495
-    }
496
-
497
-
498
-    /**
499
-     * Returns the first post which uses the specified shortcode
500
-     *
501
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
502
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
503
-     *                             "[ESPRESSO_THANK_YOU"
504
-     *                             (we don't search for the closing shortcode bracket because they might have added
505
-     *                             parameter to the shortcode
506
-     * @return WP_Post or NULl
507
-     */
508
-    public static function get_page_by_ee_shortcode($ee_shortcode)
509
-    {
510
-        global $wpdb;
511
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
512
-        $post_id                       =
513
-            $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
514
-        if ($post_id) {
515
-            return get_post($post_id);
516
-        } else {
517
-            return null;
518
-        }
519
-    }
520
-
521
-
522
-    /**
523
-     * This function generates a post for critical espresso pages
524
-     *
525
-     * @param array $critical_page
526
-     * @return array
527
-     */
528
-    public static function create_critical_page($critical_page)
529
-    {
530
-
531
-        $post_args = [
532
-            'post_title'     => $critical_page['name'],
533
-            'post_status'    => 'publish',
534
-            'post_type'      => 'page',
535
-            'comment_status' => 'closed',
536
-            'post_content'   => '[' . $critical_page['code'] . ']',
537
-        ];
538
-
539
-        $post_id = wp_insert_post($post_args);
540
-        if (! $post_id) {
541
-            $msg = sprintf(
542
-                esc_html__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
543
-                $critical_page['name']
544
-            );
545
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
546
-            return $critical_page;
547
-        }
548
-        // get newly created post's details
549
-        if (! $critical_page['post'] = get_post($post_id)) {
550
-            $msg = sprintf(
551
-                esc_html__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
552
-                $critical_page['name']
553
-            );
554
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
555
-        }
556
-
557
-        return $critical_page;
558
-    }
559
-
560
-
561
-    /**
562
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
563
-     * The role being used to check is filterable.
564
-     *
565
-     * @return int|null WP_user ID or NULL
566
-     * @throws EE_Error
567
-     * @throws ReflectionException
568
-     * @since  4.6.0
569
-     * @global WPDB $wpdb
570
-     */
571
-    public static function get_default_creator_id()
572
-    {
573
-        global $wpdb;
574
-        if (! empty(self::$_default_creator_id)) {
575
-            return self::$_default_creator_id;
576
-        }/**/
577
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
578
-        // let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
579
-        $pre_filtered_id = apply_filters(
580
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
581
-            false,
582
-            $role_to_check
583
-        );
584
-        if ($pre_filtered_id !== false) {
585
-            return (int) $pre_filtered_id;
586
-        }
587
-        $capabilities_key = EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
588
-        $query            = $wpdb->prepare(
589
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
590
-            '%' . $role_to_check . '%'
591
-        );
592
-        $user_id          = $wpdb->get_var($query);
593
-        $user_id          = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
594
-        if ($user_id && (int) $user_id) {
595
-            self::$_default_creator_id = (int) $user_id;
596
-            return self::$_default_creator_id;
597
-        } else {
598
-            return null;
599
-        }
600
-    }
601
-
602
-
603
-    /**
604
-     * used by EE and EE addons during plugin activation to create tables.
605
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
606
-     * but includes extra logic regarding activations.
607
-     *
608
-     * @param string  $table_name              without the $wpdb->prefix
609
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
610
-     *                                         table query)
611
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
612
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
613
-     *                                         and new once this function is done (ie, you really do want to CREATE a
614
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
615
-     *                                         you just want to verify the table exists and matches this definition
616
-     *                                         (and if it HAS data in it you want to leave it be)
617
-     * @return void
618
-     * @throws EE_Error if there are database errors
619
-     * @throws ReflectionException
620
-     */
621
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
622
-    {
623
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
624
-            return;
625
-        }
626
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
627
-        if (! function_exists('dbDelta')) {
628
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
629
-        }
630
-        $tableAnalysis = EEH_Activation::getTableAnalysis();
631
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
632
-        // do we need to first delete an existing version of this table ?
633
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
634
-            // ok, delete the table... but ONLY if it's empty
635
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
636
-            // table is NOT empty, are you SURE you want to delete this table ???
637
-            if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
638
-                EEH_Activation::getTableManager()->dropTable($wp_table_name);
639
-            } elseif (! $deleted_safely) {
640
-                // so we should be more cautious rather than just dropping tables so easily
641
-                error_log(
642
-                    sprintf(
643
-                        esc_html__(
644
-                            'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
645
-                            'event_espresso'
646
-                        ),
647
-                        $wp_table_name,
648
-                        '<br/>',
649
-                        'espresso_db_update'
650
-                    )
651
-                );
652
-            }
653
-        }
654
-        $engine = str_replace('ENGINE=', '', $engine);
655
-        EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
656
-    }
657
-
658
-
659
-    /**
660
-     * Checks if this column already exists on the specified table. Handy for addons which want to add a column
661
-     *
662
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
663
-     * @param string $column_name
664
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
665
-     *                            'VARCHAR(10)'
666
-     * @return bool|int
667
-     * @throws EE_Error
668
-     * @throws ReflectionException
669
-     * @deprecated instead use TableManager::addColumn()
670
-     */
671
-    public static function add_column_if_it_doesnt_exist(
672
-        $table_name,
673
-        $column_name,
674
-        $column_info = 'INT UNSIGNED NOT NULL'
675
-    ) {
676
-        return EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
677
-    }
678
-
679
-
680
-    /**
681
-     * Gets all the fields on the database table.
682
-     *
683
-     * @param string $table_name , without prefixed $wpdb->prefix
684
-     * @return array of database column names
685
-     * @throws EE_Error
686
-     * @throws ReflectionException
687
-     * @deprecated instead use TableManager::getTableColumns()
688
-     */
689
-    public static function get_fields_on_table($table_name = null)
690
-    {
691
-        return EEH_Activation::getTableManager()->getTableColumns($table_name);
692
-    }
693
-
694
-
695
-    /**
696
-     * @param string $table_name
697
-     * @return bool
698
-     * @throws EE_Error
699
-     * @throws ReflectionException
700
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
701
-     */
702
-    public static function db_table_is_empty($table_name)
703
-    {
704
-        return EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
705
-    }
706
-
707
-
708
-    /**
709
-     * @param string $table_name
710
-     * @return bool | int
711
-     * @throws EE_Error
712
-     * @throws ReflectionException
713
-     */
714
-    public static function delete_db_table_if_empty($table_name)
715
-    {
716
-        if (EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
717
-            return EEH_Activation::getTableManager()->dropTable($table_name);
718
-        }
719
-        return false;
720
-    }
721
-
722
-
723
-    /**
724
-     * @param string $table_name
725
-     * @return int
726
-     * @throws EE_Error
727
-     * @throws ReflectionException
728
-     * @deprecated instead use TableManager::dropTable()
729
-     */
730
-    public static function delete_unused_db_table($table_name)
731
-    {
732
-        return EEH_Activation::getTableManager()->dropTable($table_name);
733
-    }
734
-
735
-
736
-    /**
737
-     * @param string $table_name
738
-     * @param string $index_name
739
-     * @return int
740
-     * @throws EE_Error
741
-     * @throws ReflectionException
742
-     * @deprecated instead use TableManager::dropIndex()
743
-     */
744
-    public static function drop_index($table_name, $index_name)
745
-    {
746
-        return EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
747
-    }
748
-
749
-
750
-    /**
751
-     * @return boolean success (whether database is setup properly or not)
752
-     * @throws EE_Error
753
-     * @throws ReflectionException
754
-     */
755
-    public static function create_database_tables()
756
-    {
757
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
758
-        // find the migration script that sets the database to be compatible with the code
759
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
760
-        if (! $dms_name) {
761
-            EE_Error::add_error(
762
-                esc_html__(
763
-                    'Could not determine most up-to-date data migration script from which to pull database schema
267
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
268
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
269
+			if (is_array($hooks_to_fire_at_time)) {
270
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
271
+					if (
272
+						isset($ee_cron_tasks_to_remove[ $hook_name ])
273
+						&& is_array($ee_cron_tasks_to_remove[ $hook_name ])
274
+					) {
275
+						unset($crons[ $timestamp ][ $hook_name ]);
276
+					}
277
+				}
278
+				// also take care of any empty cron timestamps.
279
+				if (empty($hooks_to_fire_at_time)) {
280
+					unset($crons[ $timestamp ]);
281
+				}
282
+			}
283
+		}
284
+		_set_cron_array($crons);
285
+	}
286
+
287
+
288
+	/**
289
+	 * registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
290
+	 *
291
+	 * @return void
292
+	 * @throws EE_Error
293
+	 * @throws ReflectionException
294
+	 */
295
+	public static function CPT_initialization()
296
+	{
297
+		// register Custom Post Types
298
+		EE_Registry::instance()->load_core('Register_CPTs');
299
+		flush_rewrite_rules();
300
+	}
301
+
302
+
303
+	/**
304
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
305
+	 * If there is old calendar config data saved, then it will get converted on activation.
306
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
307
+	 *
308
+	 * @return void
309
+	 */
310
+	public static function reset_and_update_config()
311
+	{
312
+		do_action('AHEE__EE_Config___load_core_config__start', ['EEH_Activation', 'load_calendar_config']);
313
+		add_filter(
314
+			'FHEE__EE_Config___load_core_config__config_settings',
315
+			['EEH_Activation', 'migrate_old_config_data'],
316
+			10,
317
+			3
318
+		);
319
+		if (! EE_Config::logging_enabled()) {
320
+			delete_option(EE_Config::LOG_NAME);
321
+		}
322
+	}
323
+
324
+
325
+	/**
326
+	 * @return    void
327
+	 */
328
+	public static function load_calendar_config()
329
+	{
330
+		// grab array of all plugin folders and loop thru it
331
+		$plugins = glob(WP_PLUGIN_DIR . '/*', GLOB_ONLYDIR);
332
+		if (empty($plugins)) {
333
+			return;
334
+		}
335
+		foreach ($plugins as $plugin_path) {
336
+			// grab plugin folder name from path
337
+			$plugin = basename($plugin_path);
338
+			// drill down to Espresso plugins
339
+			// then to calendar related plugins
340
+			if (
341
+				strpos($plugin, 'espresso') !== false
342
+				|| strpos($plugin, 'Espresso') !== false
343
+				|| strpos($plugin, 'ee4') !== false
344
+				|| strpos($plugin, 'EE4') !== false
345
+				|| strpos($plugin, 'calendar') !== false
346
+			) {
347
+				// this is what we are looking for
348
+				$calendar_config = $plugin_path . '/EE_Calendar_Config.php';
349
+				// does it exist in this folder ?
350
+				if (is_readable($calendar_config)) {
351
+					// YEAH! let's load it
352
+					require_once($calendar_config);
353
+				}
354
+			}
355
+		}
356
+	}
357
+
358
+
359
+	/**
360
+	 * @param array|stdClass $settings
361
+	 * @param string         $config
362
+	 * @param EE_Config      $EE_Config
363
+	 * @return stdClass
364
+	 */
365
+	public static function migrate_old_config_data($settings = [], $config = '', EE_Config $EE_Config)
366
+	{
367
+		$convert_from_array = ['addons'];
368
+		// in case old settings were saved as an array
369
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
370
+			// convert existing settings to an object
371
+			$config_array = $settings;
372
+			$settings     = new stdClass();
373
+			foreach ($config_array as $key => $value) {
374
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
375
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
376
+				} else {
377
+					$settings->{$key} = $value;
378
+				}
379
+			}
380
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
381
+		}
382
+		return $settings;
383
+	}
384
+
385
+
386
+	/**
387
+	 * @return void
388
+	 */
389
+	public static function deactivate_event_espresso()
390
+	{
391
+		// check permissions
392
+		if (current_user_can('activate_plugins')) {
393
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
394
+		}
395
+	}
396
+
397
+
398
+	/**
399
+	 * @return void
400
+	 * @throws InvalidDataTypeException
401
+	 */
402
+	public static function verify_default_pages_exist()
403
+	{
404
+		$critical_page_problem = false;
405
+		$critical_pages        = [
406
+			[
407
+				'id'   => 'reg_page_id',
408
+				'name' => esc_html__('Registration Checkout', 'event_espresso'),
409
+				'post' => null,
410
+				'code' => 'ESPRESSO_CHECKOUT',
411
+			],
412
+			[
413
+				'id'   => 'txn_page_id',
414
+				'name' => esc_html__('Transactions', 'event_espresso'),
415
+				'post' => null,
416
+				'code' => 'ESPRESSO_TXN_PAGE',
417
+			],
418
+			[
419
+				'id'   => 'thank_you_page_id',
420
+				'name' => esc_html__('Thank You', 'event_espresso'),
421
+				'post' => null,
422
+				'code' => 'ESPRESSO_THANK_YOU',
423
+			],
424
+			[
425
+				'id'   => 'cancel_page_id',
426
+				'name' => esc_html__('Registration Cancelled', 'event_espresso'),
427
+				'post' => null,
428
+				'code' => 'ESPRESSO_CANCELLED',
429
+			],
430
+		];
431
+		$EE_Core_Config        = EE_Registry::instance()->CFG->core;
432
+		foreach ($critical_pages as $critical_page) {
433
+			// is critical page ID set in config ?
434
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
435
+				// attempt to find post by ID
436
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
437
+			}
438
+			// no dice?
439
+			if ($critical_page['post'] === null) {
440
+				// attempt to find post by title
441
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
442
+				// still nothing?
443
+				if ($critical_page['post'] === null) {
444
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
445
+					// REALLY? Still nothing ??!?!?
446
+					if ($critical_page['post'] === null) {
447
+						$msg = esc_html__(
448
+							'The Event Espresso critical page configuration settings could not be updated.',
449
+							'event_espresso'
450
+						);
451
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
452
+						break;
453
+					}
454
+				}
455
+			}
456
+			// check that Post ID matches critical page ID in config
457
+			if (
458
+				isset($critical_page['post']->ID)
459
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
460
+			) {
461
+				// update Config with post ID
462
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
463
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
464
+					$msg = esc_html__(
465
+						'The Event Espresso critical page configuration settings could not be updated.',
466
+						'event_espresso'
467
+					);
468
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
469
+				}
470
+			}
471
+			$critical_page_problem =
472
+				! isset($critical_page['post']->post_status)
473
+				|| $critical_page['post']->post_status !== 'publish'
474
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
475
+					? true
476
+					: $critical_page_problem;
477
+		}
478
+		if ($critical_page_problem) {
479
+			new PersistentAdminNotice(
480
+				'critical_page_problem',
481
+				sprintf(
482
+					esc_html__(
483
+						'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
484
+						'event_espresso'
485
+					),
486
+					'<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
487
+					. esc_html__('Event Espresso Critical Pages Settings', 'event_espresso')
488
+					. '</a>'
489
+				)
490
+			);
491
+		}
492
+		if (EE_Error::has_notices()) {
493
+			EE_Error::get_notices(false, true);
494
+		}
495
+	}
496
+
497
+
498
+	/**
499
+	 * Returns the first post which uses the specified shortcode
500
+	 *
501
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
502
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
503
+	 *                             "[ESPRESSO_THANK_YOU"
504
+	 *                             (we don't search for the closing shortcode bracket because they might have added
505
+	 *                             parameter to the shortcode
506
+	 * @return WP_Post or NULl
507
+	 */
508
+	public static function get_page_by_ee_shortcode($ee_shortcode)
509
+	{
510
+		global $wpdb;
511
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
512
+		$post_id                       =
513
+			$wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
514
+		if ($post_id) {
515
+			return get_post($post_id);
516
+		} else {
517
+			return null;
518
+		}
519
+	}
520
+
521
+
522
+	/**
523
+	 * This function generates a post for critical espresso pages
524
+	 *
525
+	 * @param array $critical_page
526
+	 * @return array
527
+	 */
528
+	public static function create_critical_page($critical_page)
529
+	{
530
+
531
+		$post_args = [
532
+			'post_title'     => $critical_page['name'],
533
+			'post_status'    => 'publish',
534
+			'post_type'      => 'page',
535
+			'comment_status' => 'closed',
536
+			'post_content'   => '[' . $critical_page['code'] . ']',
537
+		];
538
+
539
+		$post_id = wp_insert_post($post_args);
540
+		if (! $post_id) {
541
+			$msg = sprintf(
542
+				esc_html__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
543
+				$critical_page['name']
544
+			);
545
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
546
+			return $critical_page;
547
+		}
548
+		// get newly created post's details
549
+		if (! $critical_page['post'] = get_post($post_id)) {
550
+			$msg = sprintf(
551
+				esc_html__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
552
+				$critical_page['name']
553
+			);
554
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
555
+		}
556
+
557
+		return $critical_page;
558
+	}
559
+
560
+
561
+	/**
562
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
563
+	 * The role being used to check is filterable.
564
+	 *
565
+	 * @return int|null WP_user ID or NULL
566
+	 * @throws EE_Error
567
+	 * @throws ReflectionException
568
+	 * @since  4.6.0
569
+	 * @global WPDB $wpdb
570
+	 */
571
+	public static function get_default_creator_id()
572
+	{
573
+		global $wpdb;
574
+		if (! empty(self::$_default_creator_id)) {
575
+			return self::$_default_creator_id;
576
+		}/**/
577
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
578
+		// let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
579
+		$pre_filtered_id = apply_filters(
580
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
581
+			false,
582
+			$role_to_check
583
+		);
584
+		if ($pre_filtered_id !== false) {
585
+			return (int) $pre_filtered_id;
586
+		}
587
+		$capabilities_key = EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
588
+		$query            = $wpdb->prepare(
589
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
590
+			'%' . $role_to_check . '%'
591
+		);
592
+		$user_id          = $wpdb->get_var($query);
593
+		$user_id          = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
594
+		if ($user_id && (int) $user_id) {
595
+			self::$_default_creator_id = (int) $user_id;
596
+			return self::$_default_creator_id;
597
+		} else {
598
+			return null;
599
+		}
600
+	}
601
+
602
+
603
+	/**
604
+	 * used by EE and EE addons during plugin activation to create tables.
605
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
606
+	 * but includes extra logic regarding activations.
607
+	 *
608
+	 * @param string  $table_name              without the $wpdb->prefix
609
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
610
+	 *                                         table query)
611
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
612
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
613
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
614
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
615
+	 *                                         you just want to verify the table exists and matches this definition
616
+	 *                                         (and if it HAS data in it you want to leave it be)
617
+	 * @return void
618
+	 * @throws EE_Error if there are database errors
619
+	 * @throws ReflectionException
620
+	 */
621
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
622
+	{
623
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
624
+			return;
625
+		}
626
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
627
+		if (! function_exists('dbDelta')) {
628
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
629
+		}
630
+		$tableAnalysis = EEH_Activation::getTableAnalysis();
631
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
632
+		// do we need to first delete an existing version of this table ?
633
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
634
+			// ok, delete the table... but ONLY if it's empty
635
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
636
+			// table is NOT empty, are you SURE you want to delete this table ???
637
+			if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
638
+				EEH_Activation::getTableManager()->dropTable($wp_table_name);
639
+			} elseif (! $deleted_safely) {
640
+				// so we should be more cautious rather than just dropping tables so easily
641
+				error_log(
642
+					sprintf(
643
+						esc_html__(
644
+							'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
645
+							'event_espresso'
646
+						),
647
+						$wp_table_name,
648
+						'<br/>',
649
+						'espresso_db_update'
650
+					)
651
+				);
652
+			}
653
+		}
654
+		$engine = str_replace('ENGINE=', '', $engine);
655
+		EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
656
+	}
657
+
658
+
659
+	/**
660
+	 * Checks if this column already exists on the specified table. Handy for addons which want to add a column
661
+	 *
662
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
663
+	 * @param string $column_name
664
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
665
+	 *                            'VARCHAR(10)'
666
+	 * @return bool|int
667
+	 * @throws EE_Error
668
+	 * @throws ReflectionException
669
+	 * @deprecated instead use TableManager::addColumn()
670
+	 */
671
+	public static function add_column_if_it_doesnt_exist(
672
+		$table_name,
673
+		$column_name,
674
+		$column_info = 'INT UNSIGNED NOT NULL'
675
+	) {
676
+		return EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
677
+	}
678
+
679
+
680
+	/**
681
+	 * Gets all the fields on the database table.
682
+	 *
683
+	 * @param string $table_name , without prefixed $wpdb->prefix
684
+	 * @return array of database column names
685
+	 * @throws EE_Error
686
+	 * @throws ReflectionException
687
+	 * @deprecated instead use TableManager::getTableColumns()
688
+	 */
689
+	public static function get_fields_on_table($table_name = null)
690
+	{
691
+		return EEH_Activation::getTableManager()->getTableColumns($table_name);
692
+	}
693
+
694
+
695
+	/**
696
+	 * @param string $table_name
697
+	 * @return bool
698
+	 * @throws EE_Error
699
+	 * @throws ReflectionException
700
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
701
+	 */
702
+	public static function db_table_is_empty($table_name)
703
+	{
704
+		return EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
705
+	}
706
+
707
+
708
+	/**
709
+	 * @param string $table_name
710
+	 * @return bool | int
711
+	 * @throws EE_Error
712
+	 * @throws ReflectionException
713
+	 */
714
+	public static function delete_db_table_if_empty($table_name)
715
+	{
716
+		if (EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
717
+			return EEH_Activation::getTableManager()->dropTable($table_name);
718
+		}
719
+		return false;
720
+	}
721
+
722
+
723
+	/**
724
+	 * @param string $table_name
725
+	 * @return int
726
+	 * @throws EE_Error
727
+	 * @throws ReflectionException
728
+	 * @deprecated instead use TableManager::dropTable()
729
+	 */
730
+	public static function delete_unused_db_table($table_name)
731
+	{
732
+		return EEH_Activation::getTableManager()->dropTable($table_name);
733
+	}
734
+
735
+
736
+	/**
737
+	 * @param string $table_name
738
+	 * @param string $index_name
739
+	 * @return int
740
+	 * @throws EE_Error
741
+	 * @throws ReflectionException
742
+	 * @deprecated instead use TableManager::dropIndex()
743
+	 */
744
+	public static function drop_index($table_name, $index_name)
745
+	{
746
+		return EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
747
+	}
748
+
749
+
750
+	/**
751
+	 * @return boolean success (whether database is setup properly or not)
752
+	 * @throws EE_Error
753
+	 * @throws ReflectionException
754
+	 */
755
+	public static function create_database_tables()
756
+	{
757
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
758
+		// find the migration script that sets the database to be compatible with the code
759
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
760
+		if (! $dms_name) {
761
+			EE_Error::add_error(
762
+				esc_html__(
763
+					'Could not determine most up-to-date data migration script from which to pull database schema
764 764
                      structure. So database is probably not setup properly',
765
-                    'event_espresso'
766
-                ),
767
-                __FILE__,
768
-                __FUNCTION__,
769
-                __LINE__
770
-            );
771
-            return false;
772
-        }
773
-        $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
774
-        $current_data_migration_script->set_migrating(false);
775
-        $current_data_migration_script->schema_changes_before_migration();
776
-        $current_data_migration_script->schema_changes_after_migration();
777
-        if ($current_data_migration_script->get_errors()) {
778
-            if (WP_DEBUG) {
779
-                foreach ($current_data_migration_script->get_errors() as $error) {
780
-                    EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
781
-                }
782
-            } else {
783
-                EE_Error::add_error(
784
-                    esc_html__(
785
-                        'There were errors creating the Event Espresso database tables and Event Espresso has been 
765
+					'event_espresso'
766
+				),
767
+				__FILE__,
768
+				__FUNCTION__,
769
+				__LINE__
770
+			);
771
+			return false;
772
+		}
773
+		$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
774
+		$current_data_migration_script->set_migrating(false);
775
+		$current_data_migration_script->schema_changes_before_migration();
776
+		$current_data_migration_script->schema_changes_after_migration();
777
+		if ($current_data_migration_script->get_errors()) {
778
+			if (WP_DEBUG) {
779
+				foreach ($current_data_migration_script->get_errors() as $error) {
780
+					EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
781
+				}
782
+			} else {
783
+				EE_Error::add_error(
784
+					esc_html__(
785
+						'There were errors creating the Event Espresso database tables and Event Espresso has been 
786 786
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
787
-                        'event_espresso'
788
-                    )
789
-                );
790
-            }
791
-            return false;
792
-        }
793
-        EE_Data_Migration_Manager::instance()->update_current_database_state_to();
794
-        return true;
795
-    }
796
-
797
-
798
-    /**
799
-     * @return void
800
-     * @throws EE_Error
801
-     * @throws ReflectionException
802
-     */
803
-    public static function initialize_system_questions()
804
-    {
805
-        // QUESTION GROUPS
806
-        global $wpdb;
807
-        $table_name = EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
808
-        $SQL        = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
809
-        // what we have
810
-        $question_groups = $wpdb->get_col($SQL);
811
-        // check the response
812
-        $question_groups = is_array($question_groups) ? $question_groups : [];
813
-        // what we should have
814
-        $QSG_systems = [1, 2];
815
-        // loop thru what we should have and compare to what we have
816
-        foreach ($QSG_systems as $QSG_system) {
817
-            // reset values array
818
-            $QSG_values = [];
819
-            // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
820
-            if (! in_array("$QSG_system", $question_groups)) {
821
-                // add it
822
-                switch ($QSG_system) {
823
-                    case 1:
824
-                        $QSG_values = [
825
-                            'QSG_name'            => esc_html__('Personal Information', 'event_espresso'),
826
-                            'QSG_identifier'      => 'personal-information-' . time(),
827
-                            'QSG_desc'            => '',
828
-                            'QSG_order'           => 1,
829
-                            'QSG_show_group_name' => 1,
830
-                            'QSG_show_group_desc' => 1,
831
-                            'QSG_system'          => EEM_Question_Group::system_personal,
832
-                            'QSG_deleted'         => 0,
833
-                        ];
834
-                        break;
835
-                    case 2:
836
-                        $QSG_values = [
837
-                            'QSG_name'            => esc_html__('Address Information', 'event_espresso'),
838
-                            'QSG_identifier'      => 'address-information-' . time(),
839
-                            'QSG_desc'            => '',
840
-                            'QSG_order'           => 2,
841
-                            'QSG_show_group_name' => 1,
842
-                            'QSG_show_group_desc' => 1,
843
-                            'QSG_system'          => EEM_Question_Group::system_address,
844
-                            'QSG_deleted'         => 0,
845
-                        ];
846
-                        break;
847
-                }
848
-                // make sure we have some values before inserting them
849
-                if (! empty($QSG_values)) {
850
-                    // insert system question
851
-                    $wpdb->insert(
852
-                        $table_name,
853
-                        $QSG_values,
854
-                        ['%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d']
855
-                    );
856
-                    $QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
857
-                }
858
-            }
859
-        }
860
-        // QUESTIONS
861
-        global $wpdb;
862
-        $table_name = EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
863
-        $SQL        = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
864
-        // what we have
865
-        $questions = $wpdb->get_col($SQL);
866
-        // all system questions
867
-        $personal_system_group_questions = ['fname', 'lname', 'email'];
868
-        $address_system_group_questions  = ['address', 'address2', 'city', 'country', 'state', 'zip', 'phone'];
869
-        $system_questions_not_in_group   = ['email_confirm'];
870
-        // merge all of the system questions we should have
871
-        $QST_systems       = array_merge(
872
-            $personal_system_group_questions,
873
-            $address_system_group_questions,
874
-            $system_questions_not_in_group
875
-        );
876
-        $order_for_group_1 = 1;
877
-        $order_for_group_2 = 1;
878
-        // loop thru what we should have and compare to what we have
879
-        foreach ($QST_systems as $QST_system) {
880
-            // reset values array
881
-            $QST_values = [];
882
-            // if we don't have what we should have
883
-            if (! in_array($QST_system, $questions)) {
884
-                // add it
885
-                switch ($QST_system) {
886
-                    case 'fname':
887
-                        $QST_values = [
888
-                            'QST_display_text'  => esc_html__('First Name', 'event_espresso'),
889
-                            'QST_admin_label'   => esc_html__('First Name - System Question', 'event_espresso'),
890
-                            'QST_system'        => 'fname',
891
-                            'QST_type'          => 'TEXT',
892
-                            'QST_required'      => 1,
893
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
894
-                            'QST_order'         => 1,
895
-                            'QST_admin_only'    => 0,
896
-                            'QST_max'           => EEM_Question::instance()
897
-                                                               ->absolute_max_for_system_question($QST_system),
898
-                            'QST_wp_user'       => self::get_default_creator_id(),
899
-                            'QST_deleted'       => 0,
900
-                        ];
901
-                        break;
902
-                    case 'lname':
903
-                        $QST_values = [
904
-                            'QST_display_text'  => esc_html__('Last Name', 'event_espresso'),
905
-                            'QST_admin_label'   => esc_html__('Last Name - System Question', 'event_espresso'),
906
-                            'QST_system'        => 'lname',
907
-                            'QST_type'          => 'TEXT',
908
-                            'QST_required'      => 1,
909
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
910
-                            'QST_order'         => 2,
911
-                            'QST_admin_only'    => 0,
912
-                            'QST_max'           => EEM_Question::instance()
913
-                                                               ->absolute_max_for_system_question($QST_system),
914
-                            'QST_wp_user'       => self::get_default_creator_id(),
915
-                            'QST_deleted'       => 0,
916
-                        ];
917
-                        break;
918
-                    case 'email':
919
-                        $QST_values = [
920
-                            'QST_display_text'  => esc_html__('Email Address', 'event_espresso'),
921
-                            'QST_admin_label'   => esc_html__('Email Address - System Question', 'event_espresso'),
922
-                            'QST_system'        => 'email',
923
-                            'QST_type'          => 'EMAIL',
924
-                            'QST_required'      => 1,
925
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
926
-                            'QST_order'         => 3,
927
-                            'QST_admin_only'    => 0,
928
-                            'QST_max'           => EEM_Question::instance()
929
-                                                               ->absolute_max_for_system_question($QST_system),
930
-                            'QST_wp_user'       => self::get_default_creator_id(),
931
-                            'QST_deleted'       => 0,
932
-                        ];
933
-                        break;
934
-                    case 'email_confirm':
935
-                        $QST_values = [
936
-                            'QST_display_text'  => esc_html__('Confirm Email Address', 'event_espresso'),
937
-                            'QST_admin_label'   => esc_html__('Confirm Email Address - System Question', 'event_espresso'),
938
-                            'QST_system'        => 'email_confirm',
939
-                            'QST_type'          => 'EMAIL_CONFIRM',
940
-                            'QST_required'      => 1,
941
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
942
-                            'QST_order'         => 4,
943
-                            'QST_admin_only'    => 0,
944
-                            'QST_max'           => EEM_Question::instance()
945
-                                                               ->absolute_max_for_system_question($QST_system),
946
-                            'QST_wp_user'       => self::get_default_creator_id(),
947
-                            'QST_deleted'       => 0,
948
-                        ];
949
-                        break;
950
-                    case 'address':
951
-                        $QST_values = [
952
-                            'QST_display_text'  => esc_html__('Address', 'event_espresso'),
953
-                            'QST_admin_label'   => esc_html__('Address - System Question', 'event_espresso'),
954
-                            'QST_system'        => 'address',
955
-                            'QST_type'          => 'TEXT',
956
-                            'QST_required'      => 0,
957
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
958
-                            'QST_order'         => 5,
959
-                            'QST_admin_only'    => 0,
960
-                            'QST_max'           => EEM_Question::instance()
961
-                                                               ->absolute_max_for_system_question($QST_system),
962
-                            'QST_wp_user'       => self::get_default_creator_id(),
963
-                            'QST_deleted'       => 0,
964
-                        ];
965
-                        break;
966
-                    case 'address2':
967
-                        $QST_values = [
968
-                            'QST_display_text'  => esc_html__('Address2', 'event_espresso'),
969
-                            'QST_admin_label'   => esc_html__('Address2 - System Question', 'event_espresso'),
970
-                            'QST_system'        => 'address2',
971
-                            'QST_type'          => 'TEXT',
972
-                            'QST_required'      => 0,
973
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
974
-                            'QST_order'         => 6,
975
-                            'QST_admin_only'    => 0,
976
-                            'QST_max'           => EEM_Question::instance()
977
-                                                               ->absolute_max_for_system_question($QST_system),
978
-                            'QST_wp_user'       => self::get_default_creator_id(),
979
-                            'QST_deleted'       => 0,
980
-                        ];
981
-                        break;
982
-                    case 'city':
983
-                        $QST_values = [
984
-                            'QST_display_text'  => esc_html__('City', 'event_espresso'),
985
-                            'QST_admin_label'   => esc_html__('City - System Question', 'event_espresso'),
986
-                            'QST_system'        => 'city',
987
-                            'QST_type'          => 'TEXT',
988
-                            'QST_required'      => 0,
989
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
990
-                            'QST_order'         => 7,
991
-                            'QST_admin_only'    => 0,
992
-                            'QST_max'           => EEM_Question::instance()
993
-                                                               ->absolute_max_for_system_question($QST_system),
994
-                            'QST_wp_user'       => self::get_default_creator_id(),
995
-                            'QST_deleted'       => 0,
996
-                        ];
997
-                        break;
998
-                    case 'country':
999
-                        $QST_values = [
1000
-                            'QST_display_text'  => esc_html__('Country', 'event_espresso'),
1001
-                            'QST_admin_label'   => esc_html__('Country - System Question', 'event_espresso'),
1002
-                            'QST_system'        => 'country',
1003
-                            'QST_type'          => 'COUNTRY',
1004
-                            'QST_required'      => 0,
1005
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
1006
-                            'QST_order'         => 8,
1007
-                            'QST_admin_only'    => 0,
1008
-                            'QST_wp_user'       => self::get_default_creator_id(),
1009
-                            'QST_deleted'       => 0,
1010
-                        ];
1011
-                        break;
1012
-                    case 'state':
1013
-                        $QST_values = [
1014
-                            'QST_display_text'  => esc_html__('State/Province', 'event_espresso'),
1015
-                            'QST_admin_label'   => esc_html__('State/Province - System Question', 'event_espresso'),
1016
-                            'QST_system'        => 'state',
1017
-                            'QST_type'          => 'STATE',
1018
-                            'QST_required'      => 0,
1019
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
1020
-                            'QST_order'         => 9,
1021
-                            'QST_admin_only'    => 0,
1022
-                            'QST_wp_user'       => self::get_default_creator_id(),
1023
-                            'QST_deleted'       => 0,
1024
-                        ];
1025
-                        break;
1026
-                    case 'zip':
1027
-                        $QST_values = [
1028
-                            'QST_display_text'  => esc_html__('Zip/Postal Code', 'event_espresso'),
1029
-                            'QST_admin_label'   => esc_html__('Zip/Postal Code - System Question', 'event_espresso'),
1030
-                            'QST_system'        => 'zip',
1031
-                            'QST_type'          => 'TEXT',
1032
-                            'QST_required'      => 0,
1033
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
1034
-                            'QST_order'         => 10,
1035
-                            'QST_admin_only'    => 0,
1036
-                            'QST_max'           => EEM_Question::instance()
1037
-                                                               ->absolute_max_for_system_question($QST_system),
1038
-                            'QST_wp_user'       => self::get_default_creator_id(),
1039
-                            'QST_deleted'       => 0,
1040
-                        ];
1041
-                        break;
1042
-                    case 'phone':
1043
-                        $QST_values = [
1044
-                            'QST_display_text'  => esc_html__('Phone Number', 'event_espresso'),
1045
-                            'QST_admin_label'   => esc_html__('Phone Number - System Question', 'event_espresso'),
1046
-                            'QST_system'        => 'phone',
1047
-                            'QST_type'          => 'TEXT',
1048
-                            'QST_required'      => 0,
1049
-                            'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
1050
-                            'QST_order'         => 11,
1051
-                            'QST_admin_only'    => 0,
1052
-                            'QST_max'           => EEM_Question::instance()
1053
-                                                               ->absolute_max_for_system_question($QST_system),
1054
-                            'QST_wp_user'       => self::get_default_creator_id(),
1055
-                            'QST_deleted'       => 0,
1056
-                        ];
1057
-                        break;
1058
-                }
1059
-                if (! empty($QST_values)) {
1060
-                    // insert system question
1061
-                    $wpdb->insert(
1062
-                        $table_name,
1063
-                        $QST_values,
1064
-                        ['%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d']
1065
-                    );
1066
-                    $QST_ID = $wpdb->insert_id;
1067
-
1068
-                    // QUESTION GROUP QUESTIONS
1069
-                    if (in_array($QST_system, $personal_system_group_questions)) {
1070
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1071
-                    } elseif (in_array($QST_system, $address_system_group_questions)) {
1072
-                        $system_question_we_want = EEM_Question_Group::system_address;
1073
-                    } else {
1074
-                        // QST_system should not be assigned to any group
1075
-                        continue;
1076
-                    }
1077
-                    if (isset($QSG_IDs[ $system_question_we_want ])) {
1078
-                        $QSG_ID = $QSG_IDs[ $system_question_we_want ];
1079
-                    } else {
1080
-                        $id_col = EEM_Question_Group::instance()
1081
-                                                    ->get_col([['QSG_system' => $system_question_we_want]]);
1082
-                        if (is_array($id_col)) {
1083
-                            $QSG_ID = reset($id_col);
1084
-                        } else {
1085
-                            // ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1086
-                            EE_Log::instance()->log(
1087
-                                __FILE__,
1088
-                                __FUNCTION__,
1089
-                                sprintf(
1090
-                                    esc_html__(
1091
-                                        'Could not associate question %1$s to a question group because no system question
787
+						'event_espresso'
788
+					)
789
+				);
790
+			}
791
+			return false;
792
+		}
793
+		EE_Data_Migration_Manager::instance()->update_current_database_state_to();
794
+		return true;
795
+	}
796
+
797
+
798
+	/**
799
+	 * @return void
800
+	 * @throws EE_Error
801
+	 * @throws ReflectionException
802
+	 */
803
+	public static function initialize_system_questions()
804
+	{
805
+		// QUESTION GROUPS
806
+		global $wpdb;
807
+		$table_name = EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
808
+		$SQL        = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
809
+		// what we have
810
+		$question_groups = $wpdb->get_col($SQL);
811
+		// check the response
812
+		$question_groups = is_array($question_groups) ? $question_groups : [];
813
+		// what we should have
814
+		$QSG_systems = [1, 2];
815
+		// loop thru what we should have and compare to what we have
816
+		foreach ($QSG_systems as $QSG_system) {
817
+			// reset values array
818
+			$QSG_values = [];
819
+			// if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
820
+			if (! in_array("$QSG_system", $question_groups)) {
821
+				// add it
822
+				switch ($QSG_system) {
823
+					case 1:
824
+						$QSG_values = [
825
+							'QSG_name'            => esc_html__('Personal Information', 'event_espresso'),
826
+							'QSG_identifier'      => 'personal-information-' . time(),
827
+							'QSG_desc'            => '',
828
+							'QSG_order'           => 1,
829
+							'QSG_show_group_name' => 1,
830
+							'QSG_show_group_desc' => 1,
831
+							'QSG_system'          => EEM_Question_Group::system_personal,
832
+							'QSG_deleted'         => 0,
833
+						];
834
+						break;
835
+					case 2:
836
+						$QSG_values = [
837
+							'QSG_name'            => esc_html__('Address Information', 'event_espresso'),
838
+							'QSG_identifier'      => 'address-information-' . time(),
839
+							'QSG_desc'            => '',
840
+							'QSG_order'           => 2,
841
+							'QSG_show_group_name' => 1,
842
+							'QSG_show_group_desc' => 1,
843
+							'QSG_system'          => EEM_Question_Group::system_address,
844
+							'QSG_deleted'         => 0,
845
+						];
846
+						break;
847
+				}
848
+				// make sure we have some values before inserting them
849
+				if (! empty($QSG_values)) {
850
+					// insert system question
851
+					$wpdb->insert(
852
+						$table_name,
853
+						$QSG_values,
854
+						['%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d']
855
+					);
856
+					$QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
857
+				}
858
+			}
859
+		}
860
+		// QUESTIONS
861
+		global $wpdb;
862
+		$table_name = EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
863
+		$SQL        = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
864
+		// what we have
865
+		$questions = $wpdb->get_col($SQL);
866
+		// all system questions
867
+		$personal_system_group_questions = ['fname', 'lname', 'email'];
868
+		$address_system_group_questions  = ['address', 'address2', 'city', 'country', 'state', 'zip', 'phone'];
869
+		$system_questions_not_in_group   = ['email_confirm'];
870
+		// merge all of the system questions we should have
871
+		$QST_systems       = array_merge(
872
+			$personal_system_group_questions,
873
+			$address_system_group_questions,
874
+			$system_questions_not_in_group
875
+		);
876
+		$order_for_group_1 = 1;
877
+		$order_for_group_2 = 1;
878
+		// loop thru what we should have and compare to what we have
879
+		foreach ($QST_systems as $QST_system) {
880
+			// reset values array
881
+			$QST_values = [];
882
+			// if we don't have what we should have
883
+			if (! in_array($QST_system, $questions)) {
884
+				// add it
885
+				switch ($QST_system) {
886
+					case 'fname':
887
+						$QST_values = [
888
+							'QST_display_text'  => esc_html__('First Name', 'event_espresso'),
889
+							'QST_admin_label'   => esc_html__('First Name - System Question', 'event_espresso'),
890
+							'QST_system'        => 'fname',
891
+							'QST_type'          => 'TEXT',
892
+							'QST_required'      => 1,
893
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
894
+							'QST_order'         => 1,
895
+							'QST_admin_only'    => 0,
896
+							'QST_max'           => EEM_Question::instance()
897
+															   ->absolute_max_for_system_question($QST_system),
898
+							'QST_wp_user'       => self::get_default_creator_id(),
899
+							'QST_deleted'       => 0,
900
+						];
901
+						break;
902
+					case 'lname':
903
+						$QST_values = [
904
+							'QST_display_text'  => esc_html__('Last Name', 'event_espresso'),
905
+							'QST_admin_label'   => esc_html__('Last Name - System Question', 'event_espresso'),
906
+							'QST_system'        => 'lname',
907
+							'QST_type'          => 'TEXT',
908
+							'QST_required'      => 1,
909
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
910
+							'QST_order'         => 2,
911
+							'QST_admin_only'    => 0,
912
+							'QST_max'           => EEM_Question::instance()
913
+															   ->absolute_max_for_system_question($QST_system),
914
+							'QST_wp_user'       => self::get_default_creator_id(),
915
+							'QST_deleted'       => 0,
916
+						];
917
+						break;
918
+					case 'email':
919
+						$QST_values = [
920
+							'QST_display_text'  => esc_html__('Email Address', 'event_espresso'),
921
+							'QST_admin_label'   => esc_html__('Email Address - System Question', 'event_espresso'),
922
+							'QST_system'        => 'email',
923
+							'QST_type'          => 'EMAIL',
924
+							'QST_required'      => 1,
925
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
926
+							'QST_order'         => 3,
927
+							'QST_admin_only'    => 0,
928
+							'QST_max'           => EEM_Question::instance()
929
+															   ->absolute_max_for_system_question($QST_system),
930
+							'QST_wp_user'       => self::get_default_creator_id(),
931
+							'QST_deleted'       => 0,
932
+						];
933
+						break;
934
+					case 'email_confirm':
935
+						$QST_values = [
936
+							'QST_display_text'  => esc_html__('Confirm Email Address', 'event_espresso'),
937
+							'QST_admin_label'   => esc_html__('Confirm Email Address - System Question', 'event_espresso'),
938
+							'QST_system'        => 'email_confirm',
939
+							'QST_type'          => 'EMAIL_CONFIRM',
940
+							'QST_required'      => 1,
941
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
942
+							'QST_order'         => 4,
943
+							'QST_admin_only'    => 0,
944
+							'QST_max'           => EEM_Question::instance()
945
+															   ->absolute_max_for_system_question($QST_system),
946
+							'QST_wp_user'       => self::get_default_creator_id(),
947
+							'QST_deleted'       => 0,
948
+						];
949
+						break;
950
+					case 'address':
951
+						$QST_values = [
952
+							'QST_display_text'  => esc_html__('Address', 'event_espresso'),
953
+							'QST_admin_label'   => esc_html__('Address - System Question', 'event_espresso'),
954
+							'QST_system'        => 'address',
955
+							'QST_type'          => 'TEXT',
956
+							'QST_required'      => 0,
957
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
958
+							'QST_order'         => 5,
959
+							'QST_admin_only'    => 0,
960
+							'QST_max'           => EEM_Question::instance()
961
+															   ->absolute_max_for_system_question($QST_system),
962
+							'QST_wp_user'       => self::get_default_creator_id(),
963
+							'QST_deleted'       => 0,
964
+						];
965
+						break;
966
+					case 'address2':
967
+						$QST_values = [
968
+							'QST_display_text'  => esc_html__('Address2', 'event_espresso'),
969
+							'QST_admin_label'   => esc_html__('Address2 - System Question', 'event_espresso'),
970
+							'QST_system'        => 'address2',
971
+							'QST_type'          => 'TEXT',
972
+							'QST_required'      => 0,
973
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
974
+							'QST_order'         => 6,
975
+							'QST_admin_only'    => 0,
976
+							'QST_max'           => EEM_Question::instance()
977
+															   ->absolute_max_for_system_question($QST_system),
978
+							'QST_wp_user'       => self::get_default_creator_id(),
979
+							'QST_deleted'       => 0,
980
+						];
981
+						break;
982
+					case 'city':
983
+						$QST_values = [
984
+							'QST_display_text'  => esc_html__('City', 'event_espresso'),
985
+							'QST_admin_label'   => esc_html__('City - System Question', 'event_espresso'),
986
+							'QST_system'        => 'city',
987
+							'QST_type'          => 'TEXT',
988
+							'QST_required'      => 0,
989
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
990
+							'QST_order'         => 7,
991
+							'QST_admin_only'    => 0,
992
+							'QST_max'           => EEM_Question::instance()
993
+															   ->absolute_max_for_system_question($QST_system),
994
+							'QST_wp_user'       => self::get_default_creator_id(),
995
+							'QST_deleted'       => 0,
996
+						];
997
+						break;
998
+					case 'country':
999
+						$QST_values = [
1000
+							'QST_display_text'  => esc_html__('Country', 'event_espresso'),
1001
+							'QST_admin_label'   => esc_html__('Country - System Question', 'event_espresso'),
1002
+							'QST_system'        => 'country',
1003
+							'QST_type'          => 'COUNTRY',
1004
+							'QST_required'      => 0,
1005
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
1006
+							'QST_order'         => 8,
1007
+							'QST_admin_only'    => 0,
1008
+							'QST_wp_user'       => self::get_default_creator_id(),
1009
+							'QST_deleted'       => 0,
1010
+						];
1011
+						break;
1012
+					case 'state':
1013
+						$QST_values = [
1014
+							'QST_display_text'  => esc_html__('State/Province', 'event_espresso'),
1015
+							'QST_admin_label'   => esc_html__('State/Province - System Question', 'event_espresso'),
1016
+							'QST_system'        => 'state',
1017
+							'QST_type'          => 'STATE',
1018
+							'QST_required'      => 0,
1019
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
1020
+							'QST_order'         => 9,
1021
+							'QST_admin_only'    => 0,
1022
+							'QST_wp_user'       => self::get_default_creator_id(),
1023
+							'QST_deleted'       => 0,
1024
+						];
1025
+						break;
1026
+					case 'zip':
1027
+						$QST_values = [
1028
+							'QST_display_text'  => esc_html__('Zip/Postal Code', 'event_espresso'),
1029
+							'QST_admin_label'   => esc_html__('Zip/Postal Code - System Question', 'event_espresso'),
1030
+							'QST_system'        => 'zip',
1031
+							'QST_type'          => 'TEXT',
1032
+							'QST_required'      => 0,
1033
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
1034
+							'QST_order'         => 10,
1035
+							'QST_admin_only'    => 0,
1036
+							'QST_max'           => EEM_Question::instance()
1037
+															   ->absolute_max_for_system_question($QST_system),
1038
+							'QST_wp_user'       => self::get_default_creator_id(),
1039
+							'QST_deleted'       => 0,
1040
+						];
1041
+						break;
1042
+					case 'phone':
1043
+						$QST_values = [
1044
+							'QST_display_text'  => esc_html__('Phone Number', 'event_espresso'),
1045
+							'QST_admin_label'   => esc_html__('Phone Number - System Question', 'event_espresso'),
1046
+							'QST_system'        => 'phone',
1047
+							'QST_type'          => 'TEXT',
1048
+							'QST_required'      => 0,
1049
+							'QST_required_text' => esc_html__('This field is required', 'event_espresso'),
1050
+							'QST_order'         => 11,
1051
+							'QST_admin_only'    => 0,
1052
+							'QST_max'           => EEM_Question::instance()
1053
+															   ->absolute_max_for_system_question($QST_system),
1054
+							'QST_wp_user'       => self::get_default_creator_id(),
1055
+							'QST_deleted'       => 0,
1056
+						];
1057
+						break;
1058
+				}
1059
+				if (! empty($QST_values)) {
1060
+					// insert system question
1061
+					$wpdb->insert(
1062
+						$table_name,
1063
+						$QST_values,
1064
+						['%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d']
1065
+					);
1066
+					$QST_ID = $wpdb->insert_id;
1067
+
1068
+					// QUESTION GROUP QUESTIONS
1069
+					if (in_array($QST_system, $personal_system_group_questions)) {
1070
+						$system_question_we_want = EEM_Question_Group::system_personal;
1071
+					} elseif (in_array($QST_system, $address_system_group_questions)) {
1072
+						$system_question_we_want = EEM_Question_Group::system_address;
1073
+					} else {
1074
+						// QST_system should not be assigned to any group
1075
+						continue;
1076
+					}
1077
+					if (isset($QSG_IDs[ $system_question_we_want ])) {
1078
+						$QSG_ID = $QSG_IDs[ $system_question_we_want ];
1079
+					} else {
1080
+						$id_col = EEM_Question_Group::instance()
1081
+													->get_col([['QSG_system' => $system_question_we_want]]);
1082
+						if (is_array($id_col)) {
1083
+							$QSG_ID = reset($id_col);
1084
+						} else {
1085
+							// ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1086
+							EE_Log::instance()->log(
1087
+								__FILE__,
1088
+								__FUNCTION__,
1089
+								sprintf(
1090
+									esc_html__(
1091
+										'Could not associate question %1$s to a question group because no system question
1092 1092
                                          group existed',
1093
-                                        'event_espresso'
1094
-                                    ),
1095
-                                    $QST_ID
1096
-                                ),
1097
-                                'error'
1098
-                            );
1099
-                            continue;
1100
-                        }
1101
-                    }
1102
-                    // add system questions to groups
1103
-                    $wpdb->insert(
1104
-                        EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1105
-                        [
1106
-                            'QSG_ID'    => $QSG_ID,
1107
-                            'QST_ID'    => $QST_ID,
1108
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1109
-                        ],
1110
-                        ['%d', '%d', '%d']
1111
-                    );
1112
-                }
1113
-            }
1114
-        }
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * Makes sure the default payment method (Invoice) is active.
1120
-     * This used to be done automatically as part of constructing the old gateways config
1121
-     *
1122
-     * @throws EE_Error
1123
-     * @throws ReflectionException
1124
-     */
1125
-    public static function insert_default_payment_methods()
1126
-    {
1127
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1128
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1129
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1130
-        } else {
1131
-            EEM_Payment_Method::instance()->verify_button_urls();
1132
-        }
1133
-    }
1134
-
1135
-
1136
-    /**
1137
-     * @return void
1138
-     * @throws EE_Error
1139
-     * @throws ReflectionException
1140
-     */
1141
-    public static function insert_default_status_codes()
1142
-    {
1143
-
1144
-        global $wpdb;
1145
-
1146
-        if (EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1147
-            $table_name = EEM_Status::instance()->table();
1148
-
1149
-            $SQL =
1150
-                "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1151
-            $wpdb->query($SQL);
1152
-
1153
-            $SQL = "INSERT INTO $table_name
1093
+										'event_espresso'
1094
+									),
1095
+									$QST_ID
1096
+								),
1097
+								'error'
1098
+							);
1099
+							continue;
1100
+						}
1101
+					}
1102
+					// add system questions to groups
1103
+					$wpdb->insert(
1104
+						EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1105
+						[
1106
+							'QSG_ID'    => $QSG_ID,
1107
+							'QST_ID'    => $QST_ID,
1108
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1109
+						],
1110
+						['%d', '%d', '%d']
1111
+					);
1112
+				}
1113
+			}
1114
+		}
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * Makes sure the default payment method (Invoice) is active.
1120
+	 * This used to be done automatically as part of constructing the old gateways config
1121
+	 *
1122
+	 * @throws EE_Error
1123
+	 * @throws ReflectionException
1124
+	 */
1125
+	public static function insert_default_payment_methods()
1126
+	{
1127
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1128
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1129
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1130
+		} else {
1131
+			EEM_Payment_Method::instance()->verify_button_urls();
1132
+		}
1133
+	}
1134
+
1135
+
1136
+	/**
1137
+	 * @return void
1138
+	 * @throws EE_Error
1139
+	 * @throws ReflectionException
1140
+	 */
1141
+	public static function insert_default_status_codes()
1142
+	{
1143
+
1144
+		global $wpdb;
1145
+
1146
+		if (EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1147
+			$table_name = EEM_Status::instance()->table();
1148
+
1149
+			$SQL =
1150
+				"DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1151
+			$wpdb->query($SQL);
1152
+
1153
+			$SQL = "INSERT INTO $table_name
1154 1154
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1155 1155
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1156 1156
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1190,480 +1190,480 @@  discard block
 block discarded – undo
1190 1190
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1191 1191
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1192 1192
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1193
-            $wpdb->query($SQL);
1194
-        }
1195
-    }
1196
-
1197
-
1198
-    /**
1199
-     * @return bool     true means new templates were created.
1200
-     *                  false means no templates were created.
1201
-     *                  This is NOT an error flag. To check for errors you will want
1202
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1203
-     * @throws EE_Error
1204
-     * @throws ReflectionException
1205
-     */
1206
-    public static function generate_default_message_templates()
1207
-    {
1208
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1209
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1210
-        /*
1193
+			$wpdb->query($SQL);
1194
+		}
1195
+	}
1196
+
1197
+
1198
+	/**
1199
+	 * @return bool     true means new templates were created.
1200
+	 *                  false means no templates were created.
1201
+	 *                  This is NOT an error flag. To check for errors you will want
1202
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1203
+	 * @throws EE_Error
1204
+	 * @throws ReflectionException
1205
+	 */
1206
+	public static function generate_default_message_templates()
1207
+	{
1208
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1209
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1210
+		/*
1211 1211
          * This first method is taking care of ensuring any default messengers
1212 1212
          * that should be made active and have templates generated are done.
1213 1213
          */
1214
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1215
-            $message_resource_manager
1216
-        );
1217
-        /**
1218
-         * This method is verifying there are no NEW default message types
1219
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1220
-         */
1221
-        $new_templates_created_for_message_type =
1222
-            self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1223
-                $message_resource_manager
1224
-            );
1225
-        // after all is done, let's persist these changes to the db.
1226
-        $message_resource_manager->update_has_activated_messengers_option();
1227
-        $message_resource_manager->update_active_messengers_option();
1228
-        // will return true if either of these are true.  Otherwise will return false.
1229
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1230
-    }
1231
-
1232
-
1233
-    /**
1234
-     * @param EE_Message_Resource_Manager $message_resource_manager
1235
-     * @return array|bool
1236
-     * @throws EE_Error
1237
-     * @throws ReflectionException
1238
-     */
1239
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1240
-        EE_Message_Resource_Manager $message_resource_manager
1241
-    ) {
1242
-        $active_messengers       = $message_resource_manager->active_messengers();
1243
-        $installed_message_types = $message_resource_manager->installed_message_types();
1244
-        $templates_created       = false;
1245
-        foreach ($active_messengers as $active_messenger) {
1246
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1247
-            $default_message_type_names_to_activate   = [];
1248
-            // looping through each default message type reported by the messenger
1249
-            // and setup the actual message types to activate.
1250
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1251
-                // if already active or has already been activated before we skip
1252
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1253
-                // we also skip if the message type is not installed.
1254
-                if (
1255
-                    $message_resource_manager->has_message_type_been_activated_for_messenger(
1256
-                        $default_message_type_name_for_messenger,
1257
-                        $active_messenger->name
1258
-                    )
1259
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1260
-                        $active_messenger->name,
1261
-                        $default_message_type_name_for_messenger
1262
-                    )
1263
-                    || ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1264
-                ) {
1265
-                    continue;
1266
-                }
1267
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1268
-            }
1269
-            // let's activate!
1270
-            $message_resource_manager->ensure_message_types_are_active(
1271
-                $default_message_type_names_to_activate,
1272
-                $active_messenger->name,
1273
-                false
1274
-            );
1275
-            // activate the templates for these message types
1276
-            if (! empty($default_message_type_names_to_activate)) {
1277
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1278
-                    $active_messenger->name,
1279
-                    $default_message_type_names_for_messenger,
1280
-                    '',
1281
-                    true
1282
-                );
1283
-            }
1284
-        }
1285
-        return $templates_created;
1286
-    }
1287
-
1288
-
1289
-    /**
1290
-     * This will activate and generate default messengers and default message types for those messengers.
1291
-     *
1292
-     * @param EE_message_Resource_Manager $message_resource_manager
1293
-     * @return array|bool  True means there were default messengers and message type templates generated.
1294
-     *                     False means that there were no templates generated
1295
-     *                     (which could simply mean there are no default message types for a messenger).
1296
-     * @throws EE_Error
1297
-     * @throws ReflectionException
1298
-     */
1299
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1300
-        EE_Message_Resource_Manager $message_resource_manager
1301
-    ) {
1302
-        $messengers_to_generate  = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1303
-        $installed_message_types = $message_resource_manager->installed_message_types();
1304
-        $templates_generated     = false;
1305
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1306
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1307
-            // verify the default message types match an installed message type.
1308
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1309
-                if (
1310
-                    ! isset($installed_message_types[ $name ])
1311
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1312
-                        $name,
1313
-                        $messenger_to_generate->name
1314
-                    )
1315
-                ) {
1316
-                    unset($default_message_type_names_for_messenger[ $key ]);
1317
-                }
1318
-            }
1319
-            // in previous iterations, the active_messengers option in the db
1320
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1321
-            // This comment is left here just in case we discover that we _do_ need to update before
1322
-            // passing off to create templates (after the refactor is done).
1323
-            // @todo remove this comment when determined not necessary.
1324
-            $message_resource_manager->activate_messenger(
1325
-                $messenger_to_generate,
1326
-                $default_message_type_names_for_messenger,
1327
-                false
1328
-            );
1329
-            // create any templates needing created (or will reactivate templates already generated as necessary).
1330
-            if (! empty($default_message_type_names_for_messenger)) {
1331
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1332
-                    $messenger_to_generate->name,
1333
-                    $default_message_type_names_for_messenger,
1334
-                    '',
1335
-                    true
1336
-                );
1337
-            }
1338
-        }
1339
-        return $templates_generated;
1340
-    }
1341
-
1342
-
1343
-    /**
1344
-     * This returns the default messengers to generate templates for on activation of EE.
1345
-     * It considers:
1346
-     * - whether a messenger is already active in the db.
1347
-     * - whether a messenger has been made active at any time in the past.
1348
-     *
1349
-     * @param EE_Message_Resource_Manager $message_resource_manager
1350
-     * @return EE_messenger[]
1351
-     */
1352
-    protected static function _get_default_messengers_to_generate_on_activation(
1353
-        EE_Message_Resource_Manager $message_resource_manager
1354
-    ) {
1355
-        $active_messengers    = $message_resource_manager->active_messengers();
1356
-        $installed_messengers = $message_resource_manager->installed_messengers();
1357
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1358
-
1359
-        $messengers_to_generate = [];
1360
-        foreach ($installed_messengers as $installed_messenger) {
1361
-            // if installed messenger is a messenger that should be activated on install
1362
-            // and is not already active
1363
-            // and has never been activated
1364
-            if (
1365
-                ! $installed_messenger->activate_on_install
1366
-                || isset($active_messengers[ $installed_messenger->name ])
1367
-                || isset($has_activated[ $installed_messenger->name ])
1368
-            ) {
1369
-                continue;
1370
-            }
1371
-            $messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1372
-        }
1373
-        return $messengers_to_generate;
1374
-    }
1375
-
1376
-
1377
-    /**
1378
-     * This simply validates active message types to ensure they actually match installed
1379
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1380
-     * rows are set inactive.
1381
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1382
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1383
-     * are still handled in here.
1384
-     *
1385
-     * @return void
1386
-     * @throws EE_Error
1387
-     * @throws ReflectionException
1388
-     * @since 4.3.1
1389
-     */
1390
-    public static function validate_messages_system()
1391
-    {
1392
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1393
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1394
-        $message_resource_manager->validate_active_message_types_are_installed();
1395
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1396
-    }
1397
-
1398
-
1399
-    /**
1400
-     * @return void
1401
-     */
1402
-    public static function create_no_ticket_prices_array()
1403
-    {
1404
-        // this creates an array for tracking events that have no active ticket prices created
1405
-        // this allows us to warn admins of the situation so that it can be corrected
1406
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1407
-        if (! $espresso_no_ticket_prices) {
1408
-            add_option('ee_no_ticket_prices', [], '', false);
1409
-        }
1410
-    }
1411
-
1412
-
1413
-    /**
1414
-     * @return void
1415
-     */
1416
-    public static function plugin_deactivation()
1417
-    {
1418
-    }
1419
-
1420
-
1421
-    /**
1422
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1423
-     * (like post meta or term relations)
1424
-     *
1425
-     * @throws EE_Error
1426
-     * @global wpdb $wpdb
1427
-     */
1428
-    public static function delete_all_espresso_cpt_data()
1429
-    {
1430
-        global $wpdb;
1431
-        // get all the CPT post_types
1432
-        $ee_post_types = [];
1433
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1434
-            if (method_exists($model_name, 'instance')) {
1435
-                $model_obj = call_user_func([$model_name, 'instance']);
1436
-                if ($model_obj instanceof EEM_CPT_Base) {
1437
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1438
-                }
1439
-            }
1440
-        }
1441
-        // get all our CPTs
1442
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1443
-        $cpt_ids = $wpdb->get_col($query);
1444
-        // delete each post meta and term relations too
1445
-        foreach ($cpt_ids as $post_id) {
1446
-            wp_delete_post($post_id, true);
1447
-        }
1448
-    }
1449
-
1450
-
1451
-    /**
1452
-     * Deletes all EE custom tables
1453
-     *
1454
-     * @return array
1455
-     * @throws EE_Error
1456
-     * @throws ReflectionException
1457
-     */
1458
-    public static function drop_espresso_tables()
1459
-    {
1460
-        $tables = [];
1461
-        // load registry
1462
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1463
-            if (method_exists($model_name, 'instance')) {
1464
-                $model_obj = call_user_func([$model_name, 'instance']);
1465
-                if ($model_obj instanceof EEM_Base) {
1466
-                    foreach ($model_obj->get_tables() as $table) {
1467
-                        if (
1468
-                            strpos($table->get_table_name(), 'esp_')
1469
-                            && (
1470
-                                is_main_site()// main site? nuke them all
1471
-                                || ! $table->is_global()// not main site,but not global either. nuke it
1472
-                            )
1473
-                        ) {
1474
-                            $tables[ $table->get_table_name() ] = $table->get_table_name();
1475
-                        }
1476
-                    }
1477
-                }
1478
-            }
1479
-        }
1480
-
1481
-        // there are some tables whose models were removed.
1482
-        // they should be removed when removing all EE core's data
1483
-        $tables_without_models = [
1484
-            'esp_promotion',
1485
-            'esp_promotion_applied',
1486
-            'esp_promotion_object',
1487
-            'esp_promotion_rule',
1488
-            'esp_rule',
1489
-        ];
1490
-        foreach ($tables_without_models as $table) {
1491
-            $tables[ $table ] = $table;
1492
-        }
1493
-        return EEH_Activation::getTableManager()->dropTables($tables);
1494
-    }
1495
-
1496
-
1497
-    /**
1498
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1499
-     * each table name provided has a wpdb prefix attached, and that it exists.
1500
-     * Returns the list actually deleted
1501
-     *
1502
-     * @param array $table_names
1503
-     * @return array of table names which we deleted
1504
-     * @throws EE_Error
1505
-     * @throws ReflectionException
1506
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1507
-     * @global WPDB $wpdb
1508
-     */
1509
-    public static function drop_tables($table_names)
1510
-    {
1511
-        return EEH_Activation::getTableManager()->dropTables($table_names);
1512
-    }
1513
-
1514
-
1515
-    /**
1516
-     * plugin_uninstall
1517
-     *
1518
-     * @param bool $remove_all
1519
-     * @return void
1520
-     * @throws EE_Error
1521
-     * @throws ReflectionException
1522
-     */
1523
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1524
-    {
1525
-        global $wpdb;
1526
-        self::drop_espresso_tables();
1527
-        $wp_options_to_delete = [
1528
-            'ee_no_ticket_prices'                        => true,
1529
-            'ee_active_messengers'                       => true,
1530
-            'ee_has_activated_messenger'                 => true,
1531
-            RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1532
-            'ee_config'                                  => false,
1533
-            'ee_data_migration_current_db_state'         => true,
1534
-            'ee_data_migration_mapping_'                 => false,
1535
-            'ee_data_migration_script_'                  => false,
1536
-            'ee_data_migrations'                         => true,
1537
-            'ee_dms_map'                                 => false,
1538
-            'ee_notices'                                 => true,
1539
-            'lang_file_check_'                           => false,
1540
-            'ee_maintenance_mode'                        => true,
1541
-            'ee_ueip_optin'                              => true,
1542
-            'ee_ueip_has_notified'                       => true,
1543
-            'ee_plugin_activation_errors'                => true,
1544
-            'ee_id_mapping_from'                         => false,
1545
-            'espresso_persistent_admin_notices'          => true,
1546
-            'ee_encryption_key'                          => true,
1547
-            'pue_force_upgrade_'                         => false,
1548
-            'pue_json_error_'                            => false,
1549
-            'pue_install_key_'                           => false,
1550
-            'pue_verification_error_'                    => false,
1551
-            'pu_dismissed_upgrade_'                      => false,
1552
-            'external_updates-'                          => false,
1553
-            'ee_extra_data'                              => true,
1554
-            'ee_ssn_'                                    => false,
1555
-            'ee_rss_'                                    => false,
1556
-            'ee_rte_n_tx_'                               => false,
1557
-            'ee_pers_admin_notices'                      => true,
1558
-            'ee_job_parameters_'                         => false,
1559
-            'ee_upload_directories_incomplete'           => true,
1560
-            'ee_verified_db_collations'                  => true,
1561
-        ];
1562
-        if (is_main_site()) {
1563
-            $wp_options_to_delete['ee_network_config'] = true;
1564
-        }
1565
-        $undeleted_options = [];
1566
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1567
-            if ($no_wildcard) {
1568
-                if (! delete_option($option_name)) {
1569
-                    $undeleted_options[] = $option_name;
1570
-                }
1571
-            } else {
1572
-                $option_names_to_delete_from_wildcard =
1573
-                    $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1574
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1575
-                    if (! delete_option($option_name_from_wildcard)) {
1576
-                        $undeleted_options[] = $option_name_from_wildcard;
1577
-                    }
1578
-                }
1579
-            }
1580
-        }
1581
-        // also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1582
-        remove_action('shutdown', [EE_Config::instance(), 'shutdown']);
1583
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1584
-            $db_update_sans_ee4 = [];
1585
-            foreach ($espresso_db_update as $version => $times_activated) {
1586
-                if ((string) $version[0] === '3') {// if its NON EE4
1587
-                    $db_update_sans_ee4[ $version ] = $times_activated;
1588
-                }
1589
-            }
1590
-            update_option('espresso_db_update', $db_update_sans_ee4);
1591
-        }
1592
-        $errors = '';
1593
-        if (! empty($undeleted_options)) {
1594
-            $errors .= sprintf(
1595
-                esc_html__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1596
-                '<br/>',
1597
-                implode(',<br/>', $undeleted_options)
1598
-            );
1599
-        }
1600
-        if (! empty($errors)) {
1601
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1602
-        }
1603
-    }
1604
-
1605
-
1606
-    /**
1607
-     * Gets the mysql error code from the last used query by wpdb
1608
-     *
1609
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1610
-     */
1611
-    public static function last_wpdb_error_code()
1612
-    {
1613
-        // phpcs:disable PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
1614
-        global $wpdb;
1615
-        return $wpdb->use_mysqli ? mysqli_errno($wpdb->dbh) : mysql_errno($wpdb->dbh);
1616
-        // phpcs:enable
1617
-    }
1618
-
1619
-
1620
-    /**
1621
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1622
-     *
1623
-     * @param string $table_name with or without $wpdb->prefix
1624
-     * @return boolean
1625
-     * @throws EE_Error
1626
-     * @throws ReflectionException
1627
-     * @global wpdb  $wpdb
1628
-     * @deprecated instead use TableAnalysis::tableExists()
1629
-     */
1630
-    public static function table_exists($table_name)
1631
-    {
1632
-        return EEH_Activation::getTableAnalysis()->tableExists($table_name);
1633
-    }
1634
-
1635
-
1636
-    /**
1637
-     * Resets the cache on EEH_Activation
1638
-     */
1639
-    public static function reset()
1640
-    {
1641
-        self::$_default_creator_id                             = null;
1642
-        self::$_initialized_db_content_already_in_this_request = false;
1643
-    }
1644
-
1645
-
1646
-    /**
1647
-     * Removes 'email_confirm' from the Address info question group on activation
1648
-     *
1649
-     * @return void
1650
-     * @throws EE_Error
1651
-     */
1652
-    public static function removeEmailConfirmFromAddressGroup()
1653
-    {
1654
-
1655
-        // Pull the email_confirm question ID.
1656
-        $email_confirm_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(
1657
-            EEM_Attendee::system_question_email_confirm
1658
-        );
1659
-        // Remove the email_confirm question group from the address group questions.
1660
-        EEM_Question_Group_Question::instance()->delete(
1661
-            [
1662
-                [
1663
-                    'QST_ID'                    => $email_confirm_question_id,
1664
-                    'Question_Group.QSG_system' => EEM_Question_Group::system_address,
1665
-                ],
1666
-            ]
1667
-        );
1668
-    }
1214
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1215
+			$message_resource_manager
1216
+		);
1217
+		/**
1218
+		 * This method is verifying there are no NEW default message types
1219
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1220
+		 */
1221
+		$new_templates_created_for_message_type =
1222
+			self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1223
+				$message_resource_manager
1224
+			);
1225
+		// after all is done, let's persist these changes to the db.
1226
+		$message_resource_manager->update_has_activated_messengers_option();
1227
+		$message_resource_manager->update_active_messengers_option();
1228
+		// will return true if either of these are true.  Otherwise will return false.
1229
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1230
+	}
1231
+
1232
+
1233
+	/**
1234
+	 * @param EE_Message_Resource_Manager $message_resource_manager
1235
+	 * @return array|bool
1236
+	 * @throws EE_Error
1237
+	 * @throws ReflectionException
1238
+	 */
1239
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1240
+		EE_Message_Resource_Manager $message_resource_manager
1241
+	) {
1242
+		$active_messengers       = $message_resource_manager->active_messengers();
1243
+		$installed_message_types = $message_resource_manager->installed_message_types();
1244
+		$templates_created       = false;
1245
+		foreach ($active_messengers as $active_messenger) {
1246
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1247
+			$default_message_type_names_to_activate   = [];
1248
+			// looping through each default message type reported by the messenger
1249
+			// and setup the actual message types to activate.
1250
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1251
+				// if already active or has already been activated before we skip
1252
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1253
+				// we also skip if the message type is not installed.
1254
+				if (
1255
+					$message_resource_manager->has_message_type_been_activated_for_messenger(
1256
+						$default_message_type_name_for_messenger,
1257
+						$active_messenger->name
1258
+					)
1259
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1260
+						$active_messenger->name,
1261
+						$default_message_type_name_for_messenger
1262
+					)
1263
+					|| ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1264
+				) {
1265
+					continue;
1266
+				}
1267
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1268
+			}
1269
+			// let's activate!
1270
+			$message_resource_manager->ensure_message_types_are_active(
1271
+				$default_message_type_names_to_activate,
1272
+				$active_messenger->name,
1273
+				false
1274
+			);
1275
+			// activate the templates for these message types
1276
+			if (! empty($default_message_type_names_to_activate)) {
1277
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1278
+					$active_messenger->name,
1279
+					$default_message_type_names_for_messenger,
1280
+					'',
1281
+					true
1282
+				);
1283
+			}
1284
+		}
1285
+		return $templates_created;
1286
+	}
1287
+
1288
+
1289
+	/**
1290
+	 * This will activate and generate default messengers and default message types for those messengers.
1291
+	 *
1292
+	 * @param EE_message_Resource_Manager $message_resource_manager
1293
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1294
+	 *                     False means that there were no templates generated
1295
+	 *                     (which could simply mean there are no default message types for a messenger).
1296
+	 * @throws EE_Error
1297
+	 * @throws ReflectionException
1298
+	 */
1299
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1300
+		EE_Message_Resource_Manager $message_resource_manager
1301
+	) {
1302
+		$messengers_to_generate  = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1303
+		$installed_message_types = $message_resource_manager->installed_message_types();
1304
+		$templates_generated     = false;
1305
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1306
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1307
+			// verify the default message types match an installed message type.
1308
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1309
+				if (
1310
+					! isset($installed_message_types[ $name ])
1311
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1312
+						$name,
1313
+						$messenger_to_generate->name
1314
+					)
1315
+				) {
1316
+					unset($default_message_type_names_for_messenger[ $key ]);
1317
+				}
1318
+			}
1319
+			// in previous iterations, the active_messengers option in the db
1320
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1321
+			// This comment is left here just in case we discover that we _do_ need to update before
1322
+			// passing off to create templates (after the refactor is done).
1323
+			// @todo remove this comment when determined not necessary.
1324
+			$message_resource_manager->activate_messenger(
1325
+				$messenger_to_generate,
1326
+				$default_message_type_names_for_messenger,
1327
+				false
1328
+			);
1329
+			// create any templates needing created (or will reactivate templates already generated as necessary).
1330
+			if (! empty($default_message_type_names_for_messenger)) {
1331
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1332
+					$messenger_to_generate->name,
1333
+					$default_message_type_names_for_messenger,
1334
+					'',
1335
+					true
1336
+				);
1337
+			}
1338
+		}
1339
+		return $templates_generated;
1340
+	}
1341
+
1342
+
1343
+	/**
1344
+	 * This returns the default messengers to generate templates for on activation of EE.
1345
+	 * It considers:
1346
+	 * - whether a messenger is already active in the db.
1347
+	 * - whether a messenger has been made active at any time in the past.
1348
+	 *
1349
+	 * @param EE_Message_Resource_Manager $message_resource_manager
1350
+	 * @return EE_messenger[]
1351
+	 */
1352
+	protected static function _get_default_messengers_to_generate_on_activation(
1353
+		EE_Message_Resource_Manager $message_resource_manager
1354
+	) {
1355
+		$active_messengers    = $message_resource_manager->active_messengers();
1356
+		$installed_messengers = $message_resource_manager->installed_messengers();
1357
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1358
+
1359
+		$messengers_to_generate = [];
1360
+		foreach ($installed_messengers as $installed_messenger) {
1361
+			// if installed messenger is a messenger that should be activated on install
1362
+			// and is not already active
1363
+			// and has never been activated
1364
+			if (
1365
+				! $installed_messenger->activate_on_install
1366
+				|| isset($active_messengers[ $installed_messenger->name ])
1367
+				|| isset($has_activated[ $installed_messenger->name ])
1368
+			) {
1369
+				continue;
1370
+			}
1371
+			$messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1372
+		}
1373
+		return $messengers_to_generate;
1374
+	}
1375
+
1376
+
1377
+	/**
1378
+	 * This simply validates active message types to ensure they actually match installed
1379
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1380
+	 * rows are set inactive.
1381
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1382
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1383
+	 * are still handled in here.
1384
+	 *
1385
+	 * @return void
1386
+	 * @throws EE_Error
1387
+	 * @throws ReflectionException
1388
+	 * @since 4.3.1
1389
+	 */
1390
+	public static function validate_messages_system()
1391
+	{
1392
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1393
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1394
+		$message_resource_manager->validate_active_message_types_are_installed();
1395
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1396
+	}
1397
+
1398
+
1399
+	/**
1400
+	 * @return void
1401
+	 */
1402
+	public static function create_no_ticket_prices_array()
1403
+	{
1404
+		// this creates an array for tracking events that have no active ticket prices created
1405
+		// this allows us to warn admins of the situation so that it can be corrected
1406
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1407
+		if (! $espresso_no_ticket_prices) {
1408
+			add_option('ee_no_ticket_prices', [], '', false);
1409
+		}
1410
+	}
1411
+
1412
+
1413
+	/**
1414
+	 * @return void
1415
+	 */
1416
+	public static function plugin_deactivation()
1417
+	{
1418
+	}
1419
+
1420
+
1421
+	/**
1422
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1423
+	 * (like post meta or term relations)
1424
+	 *
1425
+	 * @throws EE_Error
1426
+	 * @global wpdb $wpdb
1427
+	 */
1428
+	public static function delete_all_espresso_cpt_data()
1429
+	{
1430
+		global $wpdb;
1431
+		// get all the CPT post_types
1432
+		$ee_post_types = [];
1433
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1434
+			if (method_exists($model_name, 'instance')) {
1435
+				$model_obj = call_user_func([$model_name, 'instance']);
1436
+				if ($model_obj instanceof EEM_CPT_Base) {
1437
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1438
+				}
1439
+			}
1440
+		}
1441
+		// get all our CPTs
1442
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1443
+		$cpt_ids = $wpdb->get_col($query);
1444
+		// delete each post meta and term relations too
1445
+		foreach ($cpt_ids as $post_id) {
1446
+			wp_delete_post($post_id, true);
1447
+		}
1448
+	}
1449
+
1450
+
1451
+	/**
1452
+	 * Deletes all EE custom tables
1453
+	 *
1454
+	 * @return array
1455
+	 * @throws EE_Error
1456
+	 * @throws ReflectionException
1457
+	 */
1458
+	public static function drop_espresso_tables()
1459
+	{
1460
+		$tables = [];
1461
+		// load registry
1462
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1463
+			if (method_exists($model_name, 'instance')) {
1464
+				$model_obj = call_user_func([$model_name, 'instance']);
1465
+				if ($model_obj instanceof EEM_Base) {
1466
+					foreach ($model_obj->get_tables() as $table) {
1467
+						if (
1468
+							strpos($table->get_table_name(), 'esp_')
1469
+							&& (
1470
+								is_main_site()// main site? nuke them all
1471
+								|| ! $table->is_global()// not main site,but not global either. nuke it
1472
+							)
1473
+						) {
1474
+							$tables[ $table->get_table_name() ] = $table->get_table_name();
1475
+						}
1476
+					}
1477
+				}
1478
+			}
1479
+		}
1480
+
1481
+		// there are some tables whose models were removed.
1482
+		// they should be removed when removing all EE core's data
1483
+		$tables_without_models = [
1484
+			'esp_promotion',
1485
+			'esp_promotion_applied',
1486
+			'esp_promotion_object',
1487
+			'esp_promotion_rule',
1488
+			'esp_rule',
1489
+		];
1490
+		foreach ($tables_without_models as $table) {
1491
+			$tables[ $table ] = $table;
1492
+		}
1493
+		return EEH_Activation::getTableManager()->dropTables($tables);
1494
+	}
1495
+
1496
+
1497
+	/**
1498
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1499
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1500
+	 * Returns the list actually deleted
1501
+	 *
1502
+	 * @param array $table_names
1503
+	 * @return array of table names which we deleted
1504
+	 * @throws EE_Error
1505
+	 * @throws ReflectionException
1506
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1507
+	 * @global WPDB $wpdb
1508
+	 */
1509
+	public static function drop_tables($table_names)
1510
+	{
1511
+		return EEH_Activation::getTableManager()->dropTables($table_names);
1512
+	}
1513
+
1514
+
1515
+	/**
1516
+	 * plugin_uninstall
1517
+	 *
1518
+	 * @param bool $remove_all
1519
+	 * @return void
1520
+	 * @throws EE_Error
1521
+	 * @throws ReflectionException
1522
+	 */
1523
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1524
+	{
1525
+		global $wpdb;
1526
+		self::drop_espresso_tables();
1527
+		$wp_options_to_delete = [
1528
+			'ee_no_ticket_prices'                        => true,
1529
+			'ee_active_messengers'                       => true,
1530
+			'ee_has_activated_messenger'                 => true,
1531
+			RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1532
+			'ee_config'                                  => false,
1533
+			'ee_data_migration_current_db_state'         => true,
1534
+			'ee_data_migration_mapping_'                 => false,
1535
+			'ee_data_migration_script_'                  => false,
1536
+			'ee_data_migrations'                         => true,
1537
+			'ee_dms_map'                                 => false,
1538
+			'ee_notices'                                 => true,
1539
+			'lang_file_check_'                           => false,
1540
+			'ee_maintenance_mode'                        => true,
1541
+			'ee_ueip_optin'                              => true,
1542
+			'ee_ueip_has_notified'                       => true,
1543
+			'ee_plugin_activation_errors'                => true,
1544
+			'ee_id_mapping_from'                         => false,
1545
+			'espresso_persistent_admin_notices'          => true,
1546
+			'ee_encryption_key'                          => true,
1547
+			'pue_force_upgrade_'                         => false,
1548
+			'pue_json_error_'                            => false,
1549
+			'pue_install_key_'                           => false,
1550
+			'pue_verification_error_'                    => false,
1551
+			'pu_dismissed_upgrade_'                      => false,
1552
+			'external_updates-'                          => false,
1553
+			'ee_extra_data'                              => true,
1554
+			'ee_ssn_'                                    => false,
1555
+			'ee_rss_'                                    => false,
1556
+			'ee_rte_n_tx_'                               => false,
1557
+			'ee_pers_admin_notices'                      => true,
1558
+			'ee_job_parameters_'                         => false,
1559
+			'ee_upload_directories_incomplete'           => true,
1560
+			'ee_verified_db_collations'                  => true,
1561
+		];
1562
+		if (is_main_site()) {
1563
+			$wp_options_to_delete['ee_network_config'] = true;
1564
+		}
1565
+		$undeleted_options = [];
1566
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1567
+			if ($no_wildcard) {
1568
+				if (! delete_option($option_name)) {
1569
+					$undeleted_options[] = $option_name;
1570
+				}
1571
+			} else {
1572
+				$option_names_to_delete_from_wildcard =
1573
+					$wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1574
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1575
+					if (! delete_option($option_name_from_wildcard)) {
1576
+						$undeleted_options[] = $option_name_from_wildcard;
1577
+					}
1578
+				}
1579
+			}
1580
+		}
1581
+		// also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1582
+		remove_action('shutdown', [EE_Config::instance(), 'shutdown']);
1583
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1584
+			$db_update_sans_ee4 = [];
1585
+			foreach ($espresso_db_update as $version => $times_activated) {
1586
+				if ((string) $version[0] === '3') {// if its NON EE4
1587
+					$db_update_sans_ee4[ $version ] = $times_activated;
1588
+				}
1589
+			}
1590
+			update_option('espresso_db_update', $db_update_sans_ee4);
1591
+		}
1592
+		$errors = '';
1593
+		if (! empty($undeleted_options)) {
1594
+			$errors .= sprintf(
1595
+				esc_html__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1596
+				'<br/>',
1597
+				implode(',<br/>', $undeleted_options)
1598
+			);
1599
+		}
1600
+		if (! empty($errors)) {
1601
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1602
+		}
1603
+	}
1604
+
1605
+
1606
+	/**
1607
+	 * Gets the mysql error code from the last used query by wpdb
1608
+	 *
1609
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1610
+	 */
1611
+	public static function last_wpdb_error_code()
1612
+	{
1613
+		// phpcs:disable PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
1614
+		global $wpdb;
1615
+		return $wpdb->use_mysqli ? mysqli_errno($wpdb->dbh) : mysql_errno($wpdb->dbh);
1616
+		// phpcs:enable
1617
+	}
1618
+
1619
+
1620
+	/**
1621
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1622
+	 *
1623
+	 * @param string $table_name with or without $wpdb->prefix
1624
+	 * @return boolean
1625
+	 * @throws EE_Error
1626
+	 * @throws ReflectionException
1627
+	 * @global wpdb  $wpdb
1628
+	 * @deprecated instead use TableAnalysis::tableExists()
1629
+	 */
1630
+	public static function table_exists($table_name)
1631
+	{
1632
+		return EEH_Activation::getTableAnalysis()->tableExists($table_name);
1633
+	}
1634
+
1635
+
1636
+	/**
1637
+	 * Resets the cache on EEH_Activation
1638
+	 */
1639
+	public static function reset()
1640
+	{
1641
+		self::$_default_creator_id                             = null;
1642
+		self::$_initialized_db_content_already_in_this_request = false;
1643
+	}
1644
+
1645
+
1646
+	/**
1647
+	 * Removes 'email_confirm' from the Address info question group on activation
1648
+	 *
1649
+	 * @return void
1650
+	 * @throws EE_Error
1651
+	 */
1652
+	public static function removeEmailConfirmFromAddressGroup()
1653
+	{
1654
+
1655
+		// Pull the email_confirm question ID.
1656
+		$email_confirm_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(
1657
+			EEM_Attendee::system_question_email_confirm
1658
+		);
1659
+		// Remove the email_confirm question group from the address group questions.
1660
+		EEM_Question_Group_Question::instance()->delete(
1661
+			[
1662
+				[
1663
+					'QST_ID'                    => $email_confirm_question_id,
1664
+					'Question_Group.QSG_system' => EEM_Question_Group::system_address,
1665
+				],
1666
+			]
1667
+		);
1668
+	}
1669 1669
 }
Please login to merge, or discard this patch.
Spacing   +53 added lines, -53 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
      */
59 59
     public static function getTableAnalysis()
60 60
     {
61
-        if (! self::$table_analysis instanceof TableAnalysis) {
61
+        if ( ! self::$table_analysis instanceof TableAnalysis) {
62 62
             self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', [], true);
63 63
         }
64 64
         return self::$table_analysis;
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
      */
73 73
     public static function getTableManager()
74 74
     {
75
-        if (! self::$table_manager instanceof TableManager) {
75
+        if ( ! self::$table_manager instanceof TableManager) {
76 76
             self::$table_manager = EE_Registry::instance()->create('TableManager', [], true);
77 77
         }
78 78
         return self::$table_manager;
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
         if ($which_to_include === 'old') {
187 187
             $cron_tasks = array_filter(
188 188
                 $cron_tasks,
189
-                function ($value) {
189
+                function($value) {
190 190
                     return $value === EEH_Activation::cron_task_no_longer_in_use;
191 191
                 }
192 192
             );
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
     {
217 217
 
218 218
         foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
219
-            if (! wp_next_scheduled($hook_name)) {
219
+            if ( ! wp_next_scheduled($hook_name)) {
220 220
                 /**
221 221
                  * This allows client code to define the initial start timestamp for this schedule.
222 222
                  */
@@ -269,15 +269,15 @@  discard block
 block discarded – undo
269 269
             if (is_array($hooks_to_fire_at_time)) {
270 270
                 foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
271 271
                     if (
272
-                        isset($ee_cron_tasks_to_remove[ $hook_name ])
273
-                        && is_array($ee_cron_tasks_to_remove[ $hook_name ])
272
+                        isset($ee_cron_tasks_to_remove[$hook_name])
273
+                        && is_array($ee_cron_tasks_to_remove[$hook_name])
274 274
                     ) {
275
-                        unset($crons[ $timestamp ][ $hook_name ]);
275
+                        unset($crons[$timestamp][$hook_name]);
276 276
                     }
277 277
                 }
278 278
                 // also take care of any empty cron timestamps.
279 279
                 if (empty($hooks_to_fire_at_time)) {
280
-                    unset($crons[ $timestamp ]);
280
+                    unset($crons[$timestamp]);
281 281
                 }
282 282
             }
283 283
         }
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
             10,
317 317
             3
318 318
         );
319
-        if (! EE_Config::logging_enabled()) {
319
+        if ( ! EE_Config::logging_enabled()) {
320 320
             delete_option(EE_Config::LOG_NAME);
321 321
         }
322 322
     }
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
     public static function load_calendar_config()
329 329
     {
330 330
         // grab array of all plugin folders and loop thru it
331
-        $plugins = glob(WP_PLUGIN_DIR . '/*', GLOB_ONLYDIR);
331
+        $plugins = glob(WP_PLUGIN_DIR.'/*', GLOB_ONLYDIR);
332 332
         if (empty($plugins)) {
333 333
             return;
334 334
         }
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
                 || strpos($plugin, 'calendar') !== false
346 346
             ) {
347 347
                 // this is what we are looking for
348
-                $calendar_config = $plugin_path . '/EE_Calendar_Config.php';
348
+                $calendar_config = $plugin_path.'/EE_Calendar_Config.php';
349 349
                 // does it exist in this folder ?
350 350
                 if (is_readable($calendar_config)) {
351 351
                     // YEAH! let's load it
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
                 'code' => 'ESPRESSO_CANCELLED',
429 429
             ],
430 430
         ];
431
-        $EE_Core_Config        = EE_Registry::instance()->CFG->core;
431
+        $EE_Core_Config = EE_Registry::instance()->CFG->core;
432 432
         foreach ($critical_pages as $critical_page) {
433 433
             // is critical page ID set in config ?
434 434
             if ($EE_Core_Config->{$critical_page['id']} !== false) {
@@ -460,7 +460,7 @@  discard block
 block discarded – undo
460 460
             ) {
461 461
                 // update Config with post ID
462 462
                 $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
463
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
463
+                if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
464 464
                     $msg = esc_html__(
465 465
                         'The Event Espresso critical page configuration settings could not be updated.',
466 466
                         'event_espresso'
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
                         'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
484 484
                         'event_espresso'
485 485
                     ),
486
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
486
+                    '<a href="'.admin_url('admin.php?page=espresso_general_settings&action=critical_pages').'">'
487 487
                     . esc_html__('Event Espresso Critical Pages Settings', 'event_espresso')
488 488
                     . '</a>'
489 489
                 )
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
     public static function get_page_by_ee_shortcode($ee_shortcode)
509 509
     {
510 510
         global $wpdb;
511
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
511
+        $shortcode_and_opening_bracket = '['.$ee_shortcode;
512 512
         $post_id                       =
513 513
             $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
514 514
         if ($post_id) {
@@ -533,11 +533,11 @@  discard block
 block discarded – undo
533 533
             'post_status'    => 'publish',
534 534
             'post_type'      => 'page',
535 535
             'comment_status' => 'closed',
536
-            'post_content'   => '[' . $critical_page['code'] . ']',
536
+            'post_content'   => '['.$critical_page['code'].']',
537 537
         ];
538 538
 
539 539
         $post_id = wp_insert_post($post_args);
540
-        if (! $post_id) {
540
+        if ( ! $post_id) {
541 541
             $msg = sprintf(
542 542
                 esc_html__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
543 543
                 $critical_page['name']
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
             return $critical_page;
547 547
         }
548 548
         // get newly created post's details
549
-        if (! $critical_page['post'] = get_post($post_id)) {
549
+        if ( ! $critical_page['post'] = get_post($post_id)) {
550 550
             $msg = sprintf(
551 551
                 esc_html__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
552 552
                 $critical_page['name']
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
     public static function get_default_creator_id()
572 572
     {
573 573
         global $wpdb;
574
-        if (! empty(self::$_default_creator_id)) {
574
+        if ( ! empty(self::$_default_creator_id)) {
575 575
             return self::$_default_creator_id;
576 576
         }/**/
577 577
         $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
         $capabilities_key = EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
588 588
         $query            = $wpdb->prepare(
589 589
             "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
590
-            '%' . $role_to_check . '%'
590
+            '%'.$role_to_check.'%'
591 591
         );
592 592
         $user_id          = $wpdb->get_var($query);
593 593
         $user_id          = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
@@ -624,8 +624,8 @@  discard block
 block discarded – undo
624 624
             return;
625 625
         }
626 626
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
627
-        if (! function_exists('dbDelta')) {
628
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
627
+        if ( ! function_exists('dbDelta')) {
628
+            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
629 629
         }
630 630
         $tableAnalysis = EEH_Activation::getTableAnalysis();
631 631
         $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
@@ -634,9 +634,9 @@  discard block
 block discarded – undo
634 634
             // ok, delete the table... but ONLY if it's empty
635 635
             $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
636 636
             // table is NOT empty, are you SURE you want to delete this table ???
637
-            if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
637
+            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
638 638
                 EEH_Activation::getTableManager()->dropTable($wp_table_name);
639
-            } elseif (! $deleted_safely) {
639
+            } elseif ( ! $deleted_safely) {
640 640
                 // so we should be more cautious rather than just dropping tables so easily
641 641
                 error_log(
642 642
                     sprintf(
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
         EE_Registry::instance()->load_core('Data_Migration_Manager');
758 758
         // find the migration script that sets the database to be compatible with the code
759 759
         $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
760
-        if (! $dms_name) {
760
+        if ( ! $dms_name) {
761 761
             EE_Error::add_error(
762 762
                 esc_html__(
763 763
                     'Could not determine most up-to-date data migration script from which to pull database schema
@@ -817,13 +817,13 @@  discard block
 block discarded – undo
817 817
             // reset values array
818 818
             $QSG_values = [];
819 819
             // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
820
-            if (! in_array("$QSG_system", $question_groups)) {
820
+            if ( ! in_array("$QSG_system", $question_groups)) {
821 821
                 // add it
822 822
                 switch ($QSG_system) {
823 823
                     case 1:
824 824
                         $QSG_values = [
825 825
                             'QSG_name'            => esc_html__('Personal Information', 'event_espresso'),
826
-                            'QSG_identifier'      => 'personal-information-' . time(),
826
+                            'QSG_identifier'      => 'personal-information-'.time(),
827 827
                             'QSG_desc'            => '',
828 828
                             'QSG_order'           => 1,
829 829
                             'QSG_show_group_name' => 1,
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
                     case 2:
836 836
                         $QSG_values = [
837 837
                             'QSG_name'            => esc_html__('Address Information', 'event_espresso'),
838
-                            'QSG_identifier'      => 'address-information-' . time(),
838
+                            'QSG_identifier'      => 'address-information-'.time(),
839 839
                             'QSG_desc'            => '',
840 840
                             'QSG_order'           => 2,
841 841
                             'QSG_show_group_name' => 1,
@@ -846,14 +846,14 @@  discard block
 block discarded – undo
846 846
                         break;
847 847
                 }
848 848
                 // make sure we have some values before inserting them
849
-                if (! empty($QSG_values)) {
849
+                if ( ! empty($QSG_values)) {
850 850
                     // insert system question
851 851
                     $wpdb->insert(
852 852
                         $table_name,
853 853
                         $QSG_values,
854 854
                         ['%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d']
855 855
                     );
856
-                    $QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
856
+                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
857 857
                 }
858 858
             }
859 859
         }
@@ -868,7 +868,7 @@  discard block
 block discarded – undo
868 868
         $address_system_group_questions  = ['address', 'address2', 'city', 'country', 'state', 'zip', 'phone'];
869 869
         $system_questions_not_in_group   = ['email_confirm'];
870 870
         // merge all of the system questions we should have
871
-        $QST_systems       = array_merge(
871
+        $QST_systems = array_merge(
872 872
             $personal_system_group_questions,
873 873
             $address_system_group_questions,
874 874
             $system_questions_not_in_group
@@ -880,7 +880,7 @@  discard block
 block discarded – undo
880 880
             // reset values array
881 881
             $QST_values = [];
882 882
             // if we don't have what we should have
883
-            if (! in_array($QST_system, $questions)) {
883
+            if ( ! in_array($QST_system, $questions)) {
884 884
                 // add it
885 885
                 switch ($QST_system) {
886 886
                     case 'fname':
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
                         ];
1057 1057
                         break;
1058 1058
                 }
1059
-                if (! empty($QST_values)) {
1059
+                if ( ! empty($QST_values)) {
1060 1060
                     // insert system question
1061 1061
                     $wpdb->insert(
1062 1062
                         $table_name,
@@ -1074,8 +1074,8 @@  discard block
 block discarded – undo
1074 1074
                         // QST_system should not be assigned to any group
1075 1075
                         continue;
1076 1076
                     }
1077
-                    if (isset($QSG_IDs[ $system_question_we_want ])) {
1078
-                        $QSG_ID = $QSG_IDs[ $system_question_we_want ];
1077
+                    if (isset($QSG_IDs[$system_question_we_want])) {
1078
+                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1079 1079
                     } else {
1080 1080
                         $id_col = EEM_Question_Group::instance()
1081 1081
                                                     ->get_col([['QSG_system' => $system_question_we_want]]);
@@ -1124,7 +1124,7 @@  discard block
 block discarded – undo
1124 1124
      */
1125 1125
     public static function insert_default_payment_methods()
1126 1126
     {
1127
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1127
+        if ( ! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1128 1128
             EE_Registry::instance()->load_lib('Payment_Method_Manager');
1129 1129
             EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1130 1130
         } else {
@@ -1260,7 +1260,7 @@  discard block
 block discarded – undo
1260 1260
                         $active_messenger->name,
1261 1261
                         $default_message_type_name_for_messenger
1262 1262
                     )
1263
-                    || ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1263
+                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1264 1264
                 ) {
1265 1265
                     continue;
1266 1266
                 }
@@ -1273,7 +1273,7 @@  discard block
 block discarded – undo
1273 1273
                 false
1274 1274
             );
1275 1275
             // activate the templates for these message types
1276
-            if (! empty($default_message_type_names_to_activate)) {
1276
+            if ( ! empty($default_message_type_names_to_activate)) {
1277 1277
                 $templates_created = EEH_MSG_Template::generate_new_templates(
1278 1278
                     $active_messenger->name,
1279 1279
                     $default_message_type_names_for_messenger,
@@ -1307,13 +1307,13 @@  discard block
 block discarded – undo
1307 1307
             // verify the default message types match an installed message type.
1308 1308
             foreach ($default_message_type_names_for_messenger as $key => $name) {
1309 1309
                 if (
1310
-                    ! isset($installed_message_types[ $name ])
1310
+                    ! isset($installed_message_types[$name])
1311 1311
                     || $message_resource_manager->has_message_type_been_activated_for_messenger(
1312 1312
                         $name,
1313 1313
                         $messenger_to_generate->name
1314 1314
                     )
1315 1315
                 ) {
1316
-                    unset($default_message_type_names_for_messenger[ $key ]);
1316
+                    unset($default_message_type_names_for_messenger[$key]);
1317 1317
                 }
1318 1318
             }
1319 1319
             // in previous iterations, the active_messengers option in the db
@@ -1327,7 +1327,7 @@  discard block
 block discarded – undo
1327 1327
                 false
1328 1328
             );
1329 1329
             // create any templates needing created (or will reactivate templates already generated as necessary).
1330
-            if (! empty($default_message_type_names_for_messenger)) {
1330
+            if ( ! empty($default_message_type_names_for_messenger)) {
1331 1331
                 $templates_generated = EEH_MSG_Template::generate_new_templates(
1332 1332
                     $messenger_to_generate->name,
1333 1333
                     $default_message_type_names_for_messenger,
@@ -1363,12 +1363,12 @@  discard block
 block discarded – undo
1363 1363
             // and has never been activated
1364 1364
             if (
1365 1365
                 ! $installed_messenger->activate_on_install
1366
-                || isset($active_messengers[ $installed_messenger->name ])
1367
-                || isset($has_activated[ $installed_messenger->name ])
1366
+                || isset($active_messengers[$installed_messenger->name])
1367
+                || isset($has_activated[$installed_messenger->name])
1368 1368
             ) {
1369 1369
                 continue;
1370 1370
             }
1371
-            $messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1371
+            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1372 1372
         }
1373 1373
         return $messengers_to_generate;
1374 1374
     }
@@ -1404,7 +1404,7 @@  discard block
 block discarded – undo
1404 1404
         // this creates an array for tracking events that have no active ticket prices created
1405 1405
         // this allows us to warn admins of the situation so that it can be corrected
1406 1406
         $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1407
-        if (! $espresso_no_ticket_prices) {
1407
+        if ( ! $espresso_no_ticket_prices) {
1408 1408
             add_option('ee_no_ticket_prices', [], '', false);
1409 1409
         }
1410 1410
     }
@@ -1439,7 +1439,7 @@  discard block
 block discarded – undo
1439 1439
             }
1440 1440
         }
1441 1441
         // get all our CPTs
1442
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1442
+        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (".implode(",", $ee_post_types).")";
1443 1443
         $cpt_ids = $wpdb->get_col($query);
1444 1444
         // delete each post meta and term relations too
1445 1445
         foreach ($cpt_ids as $post_id) {
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
                                 || ! $table->is_global()// not main site,but not global either. nuke it
1472 1472
                             )
1473 1473
                         ) {
1474
-                            $tables[ $table->get_table_name() ] = $table->get_table_name();
1474
+                            $tables[$table->get_table_name()] = $table->get_table_name();
1475 1475
                         }
1476 1476
                     }
1477 1477
                 }
@@ -1488,7 +1488,7 @@  discard block
 block discarded – undo
1488 1488
             'esp_rule',
1489 1489
         ];
1490 1490
         foreach ($tables_without_models as $table) {
1491
-            $tables[ $table ] = $table;
1491
+            $tables[$table] = $table;
1492 1492
         }
1493 1493
         return EEH_Activation::getTableManager()->dropTables($tables);
1494 1494
     }
@@ -1565,14 +1565,14 @@  discard block
 block discarded – undo
1565 1565
         $undeleted_options = [];
1566 1566
         foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1567 1567
             if ($no_wildcard) {
1568
-                if (! delete_option($option_name)) {
1568
+                if ( ! delete_option($option_name)) {
1569 1569
                     $undeleted_options[] = $option_name;
1570 1570
                 }
1571 1571
             } else {
1572 1572
                 $option_names_to_delete_from_wildcard =
1573 1573
                     $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1574 1574
                 foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1575
-                    if (! delete_option($option_name_from_wildcard)) {
1575
+                    if ( ! delete_option($option_name_from_wildcard)) {
1576 1576
                         $undeleted_options[] = $option_name_from_wildcard;
1577 1577
                     }
1578 1578
                 }
@@ -1584,20 +1584,20 @@  discard block
 block discarded – undo
1584 1584
             $db_update_sans_ee4 = [];
1585 1585
             foreach ($espresso_db_update as $version => $times_activated) {
1586 1586
                 if ((string) $version[0] === '3') {// if its NON EE4
1587
-                    $db_update_sans_ee4[ $version ] = $times_activated;
1587
+                    $db_update_sans_ee4[$version] = $times_activated;
1588 1588
                 }
1589 1589
             }
1590 1590
             update_option('espresso_db_update', $db_update_sans_ee4);
1591 1591
         }
1592 1592
         $errors = '';
1593
-        if (! empty($undeleted_options)) {
1593
+        if ( ! empty($undeleted_options)) {
1594 1594
             $errors .= sprintf(
1595 1595
                 esc_html__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1596 1596
                 '<br/>',
1597 1597
                 implode(',<br/>', $undeleted_options)
1598 1598
             );
1599 1599
         }
1600
-        if (! empty($errors)) {
1600
+        if ( ! empty($errors)) {
1601 1601
             EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1602 1602
         }
1603 1603
     }
Please login to merge, or discard this patch.
core/helpers/EEH_Line_Item.helper.php 2 patches
Indentation   +2053 added lines, -2053 removed lines patch added patch discarded remove patch
@@ -21,2057 +21,2057 @@
 block discarded – undo
21 21
 class EEH_Line_Item
22 22
 {
23 23
 
24
-    /**
25
-     * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
26
-     * Does NOT automatically re-calculate the line item totals or update the related transaction.
27
-     * You should call recalculate_total_including_taxes() on the grant total line item after this
28
-     * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
29
-     * to keep the registration final prices in-sync with the transaction's total.
30
-     *
31
-     * @param EE_Line_Item $parent_line_item
32
-     * @param string       $name
33
-     * @param float        $unit_price
34
-     * @param string       $description
35
-     * @param int          $quantity
36
-     * @param boolean      $taxable
37
-     * @param boolean      $code if set to a value, ensures there is only one line item with that code
38
-     * @return boolean success
39
-     * @throws EE_Error
40
-     * @throws InvalidArgumentException
41
-     * @throws InvalidDataTypeException
42
-     * @throws InvalidInterfaceException
43
-     * @throws ReflectionException
44
-     */
45
-    public static function add_unrelated_item(
46
-        EE_Line_Item $parent_line_item,
47
-        $name,
48
-        $unit_price,
49
-        $description = '',
50
-        $quantity = 1,
51
-        $taxable = false,
52
-        $code = null
53
-    ) {
54
-        $items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
55
-        $line_item = EE_Line_Item::new_instance(array(
56
-            'LIN_name'       => $name,
57
-            'LIN_desc'       => $description,
58
-            'LIN_unit_price' => $unit_price,
59
-            'LIN_quantity'   => $quantity,
60
-            'LIN_percent'    => null,
61
-            'LIN_is_taxable' => $taxable,
62
-            'LIN_order'      => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
63
-            'LIN_total'      => (float) $unit_price * (int) $quantity,
64
-            'LIN_type'       => EEM_Line_Item::type_line_item,
65
-            'LIN_code'       => $code,
66
-        ));
67
-        $line_item = apply_filters(
68
-            'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
69
-            $line_item,
70
-            $parent_line_item
71
-        );
72
-        return self::add_item($parent_line_item, $line_item);
73
-    }
74
-
75
-
76
-    /**
77
-     * Adds a simple item ( unrelated to any other model object) to the total line item,
78
-     * in the correct spot in the line item tree. Does not automatically
79
-     * re-calculate the line item totals, nor update the related transaction, nor upgrade the transaction's
80
-     * registrations' final prices (which should probably change because of this).
81
-     * You should call recalculate_total_including_taxes() on the grand total line item, then
82
-     * update the transaction's total, and EE_Registration_Processor::update_registration_final_prices()
83
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
84
-     *
85
-     * @param EE_Line_Item $parent_line_item
86
-     * @param string       $name
87
-     * @param float        $percentage_amount
88
-     * @param string       $description
89
-     * @param boolean      $taxable
90
-     * @return boolean success
91
-     * @throws EE_Error
92
-     */
93
-    public static function add_percentage_based_item(
94
-        EE_Line_Item $parent_line_item,
95
-        $name,
96
-        $percentage_amount,
97
-        $description = '',
98
-        $taxable = false
99
-    ) {
100
-        $line_item = EE_Line_Item::new_instance(array(
101
-            'LIN_name'       => $name,
102
-            'LIN_desc'       => $description,
103
-            'LIN_unit_price' => 0,
104
-            'LIN_percent'    => $percentage_amount,
105
-            'LIN_quantity'   => 1,
106
-            'LIN_is_taxable' => $taxable,
107
-            'LIN_total'      => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
108
-            'LIN_type'       => EEM_Line_Item::type_line_item,
109
-            'LIN_parent'     => $parent_line_item->ID(),
110
-        ));
111
-        $line_item = apply_filters(
112
-            'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
113
-            $line_item
114
-        );
115
-        return $parent_line_item->add_child_line_item($line_item, false);
116
-    }
117
-
118
-
119
-    /**
120
-     * Returns the new line item created by adding a purchase of the ticket
121
-     * ensures that ticket line item is saved, and that cart total has been recalculated.
122
-     * If this ticket has already been purchased, just increments its count.
123
-     * Automatically re-calculates the line item totals and updates the related transaction. But
124
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
125
-     * should probably change because of this).
126
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
127
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
128
-     *
129
-     * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
130
-     * @param EE_Ticket    $ticket
131
-     * @param int          $qty
132
-     * @return EE_Line_Item
133
-     * @throws EE_Error
134
-     * @throws InvalidArgumentException
135
-     * @throws InvalidDataTypeException
136
-     * @throws InvalidInterfaceException
137
-     * @throws ReflectionException
138
-     */
139
-    public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
140
-    {
141
-        if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
142
-            throw new EE_Error(
143
-                sprintf(
144
-                    esc_html__(
145
-                        'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.',
146
-                        'event_espresso'
147
-                    ),
148
-                    $ticket->ID(),
149
-                    $total_line_item->ID()
150
-                )
151
-            );
152
-        }
153
-        // either increment the qty for an existing ticket
154
-        $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
155
-        // or add a new one
156
-        if (! $line_item instanceof EE_Line_Item) {
157
-            $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
158
-        }
159
-        $total_line_item->recalculate_total_including_taxes();
160
-        return $line_item;
161
-    }
162
-
163
-
164
-    /**
165
-     * Returns the new line item created by adding a purchase of the ticket
166
-     *
167
-     * @param EE_Line_Item $total_line_item
168
-     * @param EE_Ticket    $ticket
169
-     * @param int          $qty
170
-     * @return EE_Line_Item
171
-     * @throws EE_Error
172
-     * @throws InvalidArgumentException
173
-     * @throws InvalidDataTypeException
174
-     * @throws InvalidInterfaceException
175
-     * @throws ReflectionException
176
-     */
177
-    public static function increment_ticket_qty_if_already_in_cart(
178
-        EE_Line_Item $total_line_item,
179
-        EE_Ticket $ticket,
180
-        $qty = 1
181
-    ) {
182
-        $line_item = null;
183
-        if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
184
-            $ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
185
-            foreach ((array) $ticket_line_items as $ticket_line_item) {
186
-                if (
187
-                    $ticket_line_item instanceof EE_Line_Item
188
-                    && (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
189
-                ) {
190
-                    $line_item = $ticket_line_item;
191
-                    break;
192
-                }
193
-            }
194
-        }
195
-        if ($line_item instanceof EE_Line_Item) {
196
-            EEH_Line_Item::increment_quantity($line_item, $qty);
197
-            return $line_item;
198
-        }
199
-        return null;
200
-    }
201
-
202
-
203
-    /**
204
-     * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
205
-     * Does NOT save or recalculate other line items totals
206
-     *
207
-     * @param EE_Line_Item $line_item
208
-     * @param int          $qty
209
-     * @return void
210
-     * @throws EE_Error
211
-     * @throws InvalidArgumentException
212
-     * @throws InvalidDataTypeException
213
-     * @throws InvalidInterfaceException
214
-     * @throws ReflectionException
215
-     */
216
-    public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
217
-    {
218
-        if (! $line_item->is_percent()) {
219
-            $qty += $line_item->quantity();
220
-            $line_item->set_quantity($qty);
221
-            $line_item->set_total($line_item->unit_price() * $qty);
222
-            $line_item->save();
223
-        }
224
-        foreach ($line_item->children() as $child) {
225
-            if ($child->is_sub_line_item()) {
226
-                EEH_Line_Item::update_quantity($child, $qty);
227
-            }
228
-        }
229
-    }
230
-
231
-
232
-    /**
233
-     * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
234
-     * Does NOT save or recalculate other line items totals
235
-     *
236
-     * @param EE_Line_Item $line_item
237
-     * @param int          $qty
238
-     * @return void
239
-     * @throws EE_Error
240
-     * @throws InvalidArgumentException
241
-     * @throws InvalidDataTypeException
242
-     * @throws InvalidInterfaceException
243
-     * @throws ReflectionException
244
-     */
245
-    public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
246
-    {
247
-        if (! $line_item->is_percent()) {
248
-            $qty = $line_item->quantity() - $qty;
249
-            $qty = max($qty, 0);
250
-            $line_item->set_quantity($qty);
251
-            $line_item->set_total($line_item->unit_price() * $qty);
252
-            $line_item->save();
253
-        }
254
-        foreach ($line_item->children() as $child) {
255
-            if ($child->is_sub_line_item()) {
256
-                EEH_Line_Item::update_quantity($child, $qty);
257
-            }
258
-        }
259
-    }
260
-
261
-
262
-    /**
263
-     * Updates the line item and its children's quantities to the specified number.
264
-     * Does NOT save them or recalculate totals.
265
-     *
266
-     * @param EE_Line_Item $line_item
267
-     * @param int          $new_quantity
268
-     * @throws EE_Error
269
-     * @throws InvalidArgumentException
270
-     * @throws InvalidDataTypeException
271
-     * @throws InvalidInterfaceException
272
-     * @throws ReflectionException
273
-     */
274
-    public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
275
-    {
276
-        if (! $line_item->is_percent()) {
277
-            $line_item->set_quantity($new_quantity);
278
-            $line_item->set_total($line_item->unit_price() * $new_quantity);
279
-            $line_item->save();
280
-        }
281
-        foreach ($line_item->children() as $child) {
282
-            if ($child->is_sub_line_item()) {
283
-                EEH_Line_Item::update_quantity($child, $new_quantity);
284
-            }
285
-        }
286
-    }
287
-
288
-
289
-    /**
290
-     * Returns the new line item created by adding a purchase of the ticket
291
-     *
292
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
293
-     * @param EE_Ticket    $ticket
294
-     * @param int          $qty
295
-     * @return EE_Line_Item
296
-     * @throws EE_Error
297
-     * @throws InvalidArgumentException
298
-     * @throws InvalidDataTypeException
299
-     * @throws InvalidInterfaceException
300
-     * @throws ReflectionException
301
-     */
302
-    public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
303
-    {
304
-        $datetimes = $ticket->datetimes();
305
-        $first_datetime = reset($datetimes);
306
-        $first_datetime_name = esc_html__('Event', 'event_espresso');
307
-        if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
308
-            $first_datetime_name = $first_datetime->event()->name();
309
-        }
310
-        $event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
311
-        // get event subtotal line
312
-        $events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
313
-        // add $ticket to cart
314
-        $line_item = EE_Line_Item::new_instance(array(
315
-            'LIN_name'       => $ticket->name(),
316
-            'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
317
-            'LIN_unit_price' => $ticket->price(),
318
-            'LIN_quantity'   => $qty,
319
-            'LIN_is_taxable' => $ticket->taxable(),
320
-            'LIN_order'      => count($events_sub_total->children()),
321
-            'LIN_total'      => $ticket->price() * $qty,
322
-            'LIN_type'       => EEM_Line_Item::type_line_item,
323
-            'OBJ_ID'         => $ticket->ID(),
324
-            'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_TICKET,
325
-        ));
326
-        $line_item = apply_filters(
327
-            'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
328
-            $line_item
329
-        );
330
-        $events_sub_total->add_child_line_item($line_item);
331
-        // now add the sub-line items
332
-        $running_total_for_ticket = 0;
333
-        foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
334
-            $sign = $price->is_discount() ? -1 : 1;
335
-            $price_total = $price->is_percent()
336
-                ? $running_total_for_ticket * $price->amount() / 100
337
-                : $price->amount() * $qty;
338
-            $sub_line_item = EE_Line_Item::new_instance(array(
339
-                'LIN_name'       => $price->name(),
340
-                'LIN_desc'       => $price->desc(),
341
-                'LIN_quantity'   => $price->is_percent() ? null : $qty,
342
-                'LIN_is_taxable' => false,
343
-                'LIN_order'      => $price->order(),
344
-                'LIN_total'      => $sign * $price_total,
345
-                'LIN_type'       => EEM_Line_Item::type_sub_line_item,
346
-                'OBJ_ID'         => $price->ID(),
347
-                'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
348
-            ));
349
-            $sub_line_item = apply_filters(
350
-                'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
351
-                $sub_line_item
352
-            );
353
-            if ($price->is_percent()) {
354
-                $sub_line_item->set_percent($sign * $price->amount());
355
-            } else {
356
-                $sub_line_item->set_unit_price($sign * $price->amount());
357
-            }
358
-            $running_total_for_ticket += $price_total;
359
-            $line_item->add_child_line_item($sub_line_item);
360
-        }
361
-        return $line_item;
362
-    }
363
-
364
-
365
-    /**
366
-     * Adds the specified item under the pre-tax-sub-total line item. Automatically
367
-     * re-calculates the line item totals and updates the related transaction. But
368
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
369
-     * should probably change because of this).
370
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
371
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
372
-     *
373
-     * @param EE_Line_Item $total_line_item
374
-     * @param EE_Line_Item $item to be added
375
-     * @return boolean
376
-     * @throws EE_Error
377
-     * @throws InvalidArgumentException
378
-     * @throws InvalidDataTypeException
379
-     * @throws InvalidInterfaceException
380
-     * @throws ReflectionException
381
-     */
382
-    public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
383
-    {
384
-        $pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
385
-        if ($pre_tax_subtotal instanceof EE_Line_Item) {
386
-            $success = $pre_tax_subtotal->add_child_line_item($item);
387
-        } else {
388
-            return false;
389
-        }
390
-        $total_line_item->recalculate_total_including_taxes();
391
-        return $success;
392
-    }
393
-
394
-
395
-    /**
396
-     * cancels an existing ticket line item,
397
-     * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
398
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
399
-     *
400
-     * @param EE_Line_Item $ticket_line_item
401
-     * @param int          $qty
402
-     * @return bool success
403
-     * @throws EE_Error
404
-     * @throws InvalidArgumentException
405
-     * @throws InvalidDataTypeException
406
-     * @throws InvalidInterfaceException
407
-     * @throws ReflectionException
408
-     */
409
-    public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
410
-    {
411
-        // validate incoming line_item
412
-        if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
413
-            throw new EE_Error(
414
-                sprintf(
415
-                    esc_html__(
416
-                        'The supplied line item must have an Object Type of "Ticket", not %1$s.',
417
-                        'event_espresso'
418
-                    ),
419
-                    $ticket_line_item->type()
420
-                )
421
-            );
422
-        }
423
-        if ($ticket_line_item->quantity() < $qty) {
424
-            throw new EE_Error(
425
-                sprintf(
426
-                    esc_html__(
427
-                        'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.',
428
-                        'event_espresso'
429
-                    ),
430
-                    $qty,
431
-                    $ticket_line_item->quantity()
432
-                )
433
-            );
434
-        }
435
-        // decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
436
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
437
-        foreach ($ticket_line_item->children() as $child_line_item) {
438
-            if (
439
-                $child_line_item->is_sub_line_item()
440
-                && ! $child_line_item->is_percent()
441
-                && ! $child_line_item->is_cancellation()
442
-            ) {
443
-                $child_line_item->set_quantity($child_line_item->quantity() - $qty);
444
-            }
445
-        }
446
-        // get cancellation sub line item
447
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
448
-            $ticket_line_item,
449
-            EEM_Line_Item::type_cancellation
450
-        );
451
-        $cancellation_line_item = reset($cancellation_line_item);
452
-        // verify that this ticket was indeed previously cancelled
453
-        if ($cancellation_line_item instanceof EE_Line_Item) {
454
-            // increment cancelled quantity
455
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
456
-        } else {
457
-            // create cancellation sub line item
458
-            $cancellation_line_item = EE_Line_Item::new_instance(array(
459
-                'LIN_name'       => esc_html__('Cancellation', 'event_espresso'),
460
-                'LIN_desc'       => sprintf(
461
-                    esc_html_x(
462
-                        'Cancelled %1$s : %2$s',
463
-                        'Cancelled Ticket Name : 2015-01-01 11:11',
464
-                        'event_espresso'
465
-                    ),
466
-                    $ticket_line_item->name(),
467
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
468
-                ),
469
-                'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
470
-                'LIN_quantity'   => $qty,
471
-                'LIN_is_taxable' => $ticket_line_item->is_taxable(),
472
-                'LIN_order'      => count($ticket_line_item->children()),
473
-                'LIN_total'      => 0, // $ticket_line_item->unit_price()
474
-                'LIN_type'       => EEM_Line_Item::type_cancellation,
475
-            ));
476
-            $ticket_line_item->add_child_line_item($cancellation_line_item);
477
-        }
478
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
479
-            // decrement parent line item quantity
480
-            $event_line_item = $ticket_line_item->parent();
481
-            if (
482
-                $event_line_item instanceof EE_Line_Item
483
-                && $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
484
-            ) {
485
-                $event_line_item->set_quantity($event_line_item->quantity() - $qty);
486
-                $event_line_item->save();
487
-            }
488
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
489
-            return true;
490
-        }
491
-        return false;
492
-    }
493
-
494
-
495
-    /**
496
-     * reinstates (un-cancels?) a previously canceled ticket line item,
497
-     * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
498
-     * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
499
-     *
500
-     * @param EE_Line_Item $ticket_line_item
501
-     * @param int          $qty
502
-     * @return bool success
503
-     * @throws EE_Error
504
-     * @throws InvalidArgumentException
505
-     * @throws InvalidDataTypeException
506
-     * @throws InvalidInterfaceException
507
-     * @throws ReflectionException
508
-     */
509
-    public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
510
-    {
511
-        // validate incoming line_item
512
-        if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
513
-            throw new EE_Error(
514
-                sprintf(
515
-                    esc_html__(
516
-                        'The supplied line item must have an Object Type of "Ticket", not %1$s.',
517
-                        'event_espresso'
518
-                    ),
519
-                    $ticket_line_item->type()
520
-                )
521
-            );
522
-        }
523
-        // get cancellation sub line item
524
-        $cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
525
-            $ticket_line_item,
526
-            EEM_Line_Item::type_cancellation
527
-        );
528
-        $cancellation_line_item = reset($cancellation_line_item);
529
-        // verify that this ticket was indeed previously cancelled
530
-        if (! $cancellation_line_item instanceof EE_Line_Item) {
531
-            return false;
532
-        }
533
-        if ($cancellation_line_item->quantity() > $qty) {
534
-            // decrement cancelled quantity
535
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
536
-        } elseif ($cancellation_line_item->quantity() === $qty) {
537
-            // decrement cancelled quantity in case anyone still has the object kicking around
538
-            $cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
539
-            // delete because quantity will end up as 0
540
-            $cancellation_line_item->delete();
541
-            // and attempt to destroy the object,
542
-            // even though PHP won't actually destroy it until it needs the memory
543
-            unset($cancellation_line_item);
544
-        } else {
545
-            // what ?!?! negative quantity ?!?!
546
-            throw new EE_Error(
547
-                sprintf(
548
-                    esc_html__(
549
-                        'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
550
-                        'event_espresso'
551
-                    ),
552
-                    $qty,
553
-                    $cancellation_line_item->quantity()
554
-                )
555
-            );
556
-        }
557
-        // increment ticket quantity
558
-        $ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
559
-        if ($ticket_line_item->save_this_and_descendants() > 0) {
560
-            // increment parent line item quantity
561
-            $event_line_item = $ticket_line_item->parent();
562
-            if (
563
-                $event_line_item instanceof EE_Line_Item
564
-                && $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
565
-            ) {
566
-                $event_line_item->set_quantity($event_line_item->quantity() + $qty);
567
-            }
568
-            EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
569
-            return true;
570
-        }
571
-        return false;
572
-    }
573
-
574
-
575
-    /**
576
-     * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
577
-     * then EE_Line_Item::recalculate_total_including_taxes() on the result
578
-     *
579
-     * @param EE_Line_Item $line_item
580
-     * @return float
581
-     * @throws EE_Error
582
-     * @throws InvalidArgumentException
583
-     * @throws InvalidDataTypeException
584
-     * @throws InvalidInterfaceException
585
-     * @throws ReflectionException
586
-     */
587
-    public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
588
-    {
589
-        $grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
590
-        return $grand_total_line_item->recalculate_total_including_taxes();
591
-    }
592
-
593
-
594
-    /**
595
-     * Gets the line item which contains the subtotal of all the items
596
-     *
597
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
598
-     * @return EE_Line_Item
599
-     * @throws EE_Error
600
-     * @throws InvalidArgumentException
601
-     * @throws InvalidDataTypeException
602
-     * @throws InvalidInterfaceException
603
-     * @throws ReflectionException
604
-     */
605
-    public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
606
-    {
607
-        $pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
608
-        return $pre_tax_subtotal instanceof EE_Line_Item
609
-            ? $pre_tax_subtotal
610
-            : self::create_pre_tax_subtotal($total_line_item);
611
-    }
612
-
613
-
614
-    /**
615
-     * Gets the line item for the taxes subtotal
616
-     *
617
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
618
-     * @return EE_Line_Item
619
-     * @throws EE_Error
620
-     * @throws InvalidArgumentException
621
-     * @throws InvalidDataTypeException
622
-     * @throws InvalidInterfaceException
623
-     * @throws ReflectionException
624
-     */
625
-    public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
626
-    {
627
-        $taxes = $total_line_item->get_child_line_item('taxes');
628
-        return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
629
-    }
630
-
631
-
632
-    /**
633
-     * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
634
-     *
635
-     * @param EE_Line_Item   $line_item
636
-     * @param EE_Transaction $transaction
637
-     * @return void
638
-     * @throws EE_Error
639
-     * @throws InvalidArgumentException
640
-     * @throws InvalidDataTypeException
641
-     * @throws InvalidInterfaceException
642
-     * @throws ReflectionException
643
-     */
644
-    public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
645
-    {
646
-        if ($transaction) {
647
-            /** @type EEM_Transaction $EEM_Transaction */
648
-            $EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
649
-            $TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
650
-            $line_item->set_TXN_ID($TXN_ID);
651
-        }
652
-    }
653
-
654
-
655
-    /**
656
-     * Creates a new default total line item for the transaction,
657
-     * and its tickets subtotal and taxes subtotal line items (and adds the
658
-     * existing taxes as children of the taxes subtotal line item)
659
-     *
660
-     * @param EE_Transaction $transaction
661
-     * @return EE_Line_Item of type total
662
-     * @throws EE_Error
663
-     * @throws InvalidArgumentException
664
-     * @throws InvalidDataTypeException
665
-     * @throws InvalidInterfaceException
666
-     * @throws ReflectionException
667
-     */
668
-    public static function create_total_line_item($transaction = null)
669
-    {
670
-        $total_line_item = EE_Line_Item::new_instance(array(
671
-            'LIN_code' => 'total',
672
-            'LIN_name' => esc_html__('Grand Total', 'event_espresso'),
673
-            'LIN_type' => EEM_Line_Item::type_total,
674
-            'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TRANSACTION,
675
-        ));
676
-        $total_line_item = apply_filters(
677
-            'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
678
-            $total_line_item
679
-        );
680
-        self::set_TXN_ID($total_line_item, $transaction);
681
-        self::create_pre_tax_subtotal($total_line_item, $transaction);
682
-        self::create_taxes_subtotal($total_line_item, $transaction);
683
-        return $total_line_item;
684
-    }
685
-
686
-
687
-    /**
688
-     * Creates a default items subtotal line item
689
-     *
690
-     * @param EE_Line_Item   $total_line_item
691
-     * @param EE_Transaction $transaction
692
-     * @return EE_Line_Item
693
-     * @throws EE_Error
694
-     * @throws InvalidArgumentException
695
-     * @throws InvalidDataTypeException
696
-     * @throws InvalidInterfaceException
697
-     * @throws ReflectionException
698
-     */
699
-    protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
700
-    {
701
-        $pre_tax_line_item = EE_Line_Item::new_instance(array(
702
-            'LIN_code' => 'pre-tax-subtotal',
703
-            'LIN_name' => esc_html__('Pre-Tax Subtotal', 'event_espresso'),
704
-            'LIN_type' => EEM_Line_Item::type_sub_total,
705
-        ));
706
-        $pre_tax_line_item = apply_filters(
707
-            'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
708
-            $pre_tax_line_item
709
-        );
710
-        self::set_TXN_ID($pre_tax_line_item, $transaction);
711
-        $total_line_item->add_child_line_item($pre_tax_line_item);
712
-        self::create_event_subtotal($pre_tax_line_item, $transaction);
713
-        return $pre_tax_line_item;
714
-    }
715
-
716
-
717
-    /**
718
-     * Creates a line item for the taxes subtotal and finds all the tax prices
719
-     * and applies taxes to it
720
-     *
721
-     * @param EE_Line_Item   $total_line_item of type EEM_Line_Item::type_total
722
-     * @param EE_Transaction $transaction
723
-     * @return EE_Line_Item
724
-     * @throws EE_Error
725
-     * @throws InvalidArgumentException
726
-     * @throws InvalidDataTypeException
727
-     * @throws InvalidInterfaceException
728
-     * @throws ReflectionException
729
-     */
730
-    protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
731
-    {
732
-        $tax_line_item = EE_Line_Item::new_instance(array(
733
-            'LIN_code'  => 'taxes',
734
-            'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
735
-            'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
736
-            'LIN_order' => 1000,// this should always come last
737
-        ));
738
-        $tax_line_item = apply_filters(
739
-            'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
740
-            $tax_line_item
741
-        );
742
-        self::set_TXN_ID($tax_line_item, $transaction);
743
-        $total_line_item->add_child_line_item($tax_line_item);
744
-        // and lastly, add the actual taxes
745
-        self::apply_taxes($total_line_item);
746
-        return $tax_line_item;
747
-    }
748
-
749
-
750
-    /**
751
-     * Creates a default items subtotal line item
752
-     *
753
-     * @param EE_Line_Item   $pre_tax_line_item
754
-     * @param EE_Transaction $transaction
755
-     * @param EE_Event       $event
756
-     * @return EE_Line_Item
757
-     * @throws EE_Error
758
-     * @throws InvalidArgumentException
759
-     * @throws InvalidDataTypeException
760
-     * @throws InvalidInterfaceException
761
-     * @throws ReflectionException
762
-     */
763
-    public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
764
-    {
765
-        $event_line_item = EE_Line_Item::new_instance(array(
766
-            'LIN_code' => self::get_event_code($event),
767
-            'LIN_name' => self::get_event_name($event),
768
-            'LIN_desc' => self::get_event_desc($event),
769
-            'LIN_type' => EEM_Line_Item::type_sub_total,
770
-            'OBJ_type' => EEM_Line_Item::OBJ_TYPE_EVENT,
771
-            'OBJ_ID'   => $event instanceof EE_Event ? $event->ID() : 0,
772
-        ));
773
-        $event_line_item = apply_filters(
774
-            'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
775
-            $event_line_item
776
-        );
777
-        self::set_TXN_ID($event_line_item, $transaction);
778
-        $pre_tax_line_item->add_child_line_item($event_line_item);
779
-        return $event_line_item;
780
-    }
781
-
782
-
783
-    /**
784
-     * Gets what the event ticket's code SHOULD be
785
-     *
786
-     * @param EE_Event $event
787
-     * @return string
788
-     * @throws EE_Error
789
-     */
790
-    public static function get_event_code($event)
791
-    {
792
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
793
-    }
794
-
795
-
796
-    /**
797
-     * Gets the event name
798
-     *
799
-     * @param EE_Event $event
800
-     * @return string
801
-     * @throws EE_Error
802
-     */
803
-    public static function get_event_name($event)
804
-    {
805
-        return $event instanceof EE_Event
806
-            ? mb_substr($event->name(), 0, 245)
807
-            : esc_html__('Event', 'event_espresso');
808
-    }
809
-
810
-
811
-    /**
812
-     * Gets the event excerpt
813
-     *
814
-     * @param EE_Event $event
815
-     * @return string
816
-     * @throws EE_Error
817
-     */
818
-    public static function get_event_desc($event)
819
-    {
820
-        return $event instanceof EE_Event ? $event->short_description() : '';
821
-    }
822
-
823
-
824
-    /**
825
-     * Given the grand total line item and a ticket, finds the event sub-total
826
-     * line item the ticket's purchase should be added onto
827
-     *
828
-     * @access public
829
-     * @param EE_Line_Item $grand_total the grand total line item
830
-     * @param EE_Ticket    $ticket
831
-     * @return EE_Line_Item
832
-     * @throws EE_Error
833
-     * @throws InvalidArgumentException
834
-     * @throws InvalidDataTypeException
835
-     * @throws InvalidInterfaceException
836
-     * @throws ReflectionException
837
-     */
838
-    public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
839
-    {
840
-        $first_datetime = $ticket->first_datetime();
841
-        if (! $first_datetime instanceof EE_Datetime) {
842
-            throw new EE_Error(
843
-                sprintf(
844
-                    esc_html__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
845
-                    $ticket->ID()
846
-                )
847
-            );
848
-        }
849
-        $event = $first_datetime->event();
850
-        if (! $event instanceof EE_Event) {
851
-            throw new EE_Error(
852
-                sprintf(
853
-                    esc_html__(
854
-                        'The supplied ticket (ID %d) has no event data associated with it.',
855
-                        'event_espresso'
856
-                    ),
857
-                    $ticket->ID()
858
-                )
859
-            );
860
-        }
861
-        $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
862
-        if (! $events_sub_total instanceof EE_Line_Item) {
863
-            throw new EE_Error(
864
-                sprintf(
865
-                    esc_html__(
866
-                        'There is no events sub-total for ticket %s on total line item %d',
867
-                        'event_espresso'
868
-                    ),
869
-                    $ticket->ID(),
870
-                    $grand_total->ID()
871
-                )
872
-            );
873
-        }
874
-        return $events_sub_total;
875
-    }
876
-
877
-
878
-    /**
879
-     * Gets the event line item
880
-     *
881
-     * @param EE_Line_Item $grand_total
882
-     * @param EE_Event     $event
883
-     * @return EE_Line_Item for the event subtotal which is a child of $grand_total
884
-     * @throws EE_Error
885
-     * @throws InvalidArgumentException
886
-     * @throws InvalidDataTypeException
887
-     * @throws InvalidInterfaceException
888
-     * @throws ReflectionException
889
-     */
890
-    public static function get_event_line_item(EE_Line_Item $grand_total, $event)
891
-    {
892
-        /** @type EE_Event $event */
893
-        $event = EEM_Event::instance()->ensure_is_obj($event, true);
894
-        $event_line_item = null;
895
-        $found = false;
896
-        foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
897
-            // default event subtotal, we should only ever find this the first time this method is called
898
-            if (! $event_line_item->OBJ_ID()) {
899
-                // let's use this! but first... set the event details
900
-                EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
901
-                $found = true;
902
-                break;
903
-            }
904
-            if ($event_line_item->OBJ_ID() === $event->ID()) {
905
-                // found existing line item for this event in the cart, so break out of loop and use this one
906
-                $found = true;
907
-                break;
908
-            }
909
-        }
910
-        if (! $found) {
911
-            // there is no event sub-total yet, so add it
912
-            $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
913
-            // create a new "event" subtotal below that
914
-            $event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
915
-            // and set the event details
916
-            EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
917
-        }
918
-        return $event_line_item;
919
-    }
920
-
921
-
922
-    /**
923
-     * Creates a default items subtotal line item
924
-     *
925
-     * @param EE_Line_Item   $event_line_item
926
-     * @param EE_Event       $event
927
-     * @param EE_Transaction $transaction
928
-     * @return void
929
-     * @throws EE_Error
930
-     * @throws InvalidArgumentException
931
-     * @throws InvalidDataTypeException
932
-     * @throws InvalidInterfaceException
933
-     * @throws ReflectionException
934
-     */
935
-    public static function set_event_subtotal_details(
936
-        EE_Line_Item $event_line_item,
937
-        EE_Event $event,
938
-        $transaction = null
939
-    ) {
940
-        if ($event instanceof EE_Event) {
941
-            $event_line_item->set_code(self::get_event_code($event));
942
-            $event_line_item->set_name(self::get_event_name($event));
943
-            $event_line_item->set_desc(self::get_event_desc($event));
944
-            $event_line_item->set_OBJ_ID($event->ID());
945
-        }
946
-        self::set_TXN_ID($event_line_item, $transaction);
947
-    }
948
-
949
-
950
-    /**
951
-     * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
952
-     * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
953
-     * any old taxes are removed
954
-     *
955
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
956
-     * @param bool         $update_txn_status
957
-     * @return bool
958
-     * @throws EE_Error
959
-     * @throws InvalidArgumentException
960
-     * @throws InvalidDataTypeException
961
-     * @throws InvalidInterfaceException
962
-     * @throws ReflectionException
963
-     * @throws RuntimeException
964
-     */
965
-    public static function apply_taxes(EE_Line_Item $total_line_item, $update_txn_status = false)
966
-    {
967
-        /** @type EEM_Price $EEM_Price */
968
-        $EEM_Price = EE_Registry::instance()->load_model('Price');
969
-        // get array of taxes via Price Model
970
-        $ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
971
-        ksort($ordered_taxes);
972
-        $taxes_line_item = self::get_taxes_subtotal($total_line_item);
973
-        // just to be safe, remove its old tax line items
974
-        $deleted = $taxes_line_item->delete_children_line_items();
975
-        $updates = false;
976
-        // loop thru taxes
977
-        foreach ($ordered_taxes as $order => $taxes) {
978
-            foreach ($taxes as $tax) {
979
-                if ($tax instanceof EE_Price) {
980
-                    $tax_line_item = EE_Line_Item::new_instance(
981
-                        array(
982
-                            'LIN_name'       => $tax->name(),
983
-                            'LIN_desc'       => $tax->desc(),
984
-                            'LIN_percent'    => $tax->amount(),
985
-                            'LIN_is_taxable' => false,
986
-                            'LIN_order'      => $order,
987
-                            'LIN_total'      => 0,
988
-                            'LIN_type'       => EEM_Line_Item::type_tax,
989
-                            'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
990
-                            'OBJ_ID'         => $tax->ID(),
991
-                        )
992
-                    );
993
-                    $tax_line_item = apply_filters(
994
-                        'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
995
-                        $tax_line_item
996
-                    );
997
-                    $updates = $taxes_line_item->add_child_line_item($tax_line_item) ?
998
-                        true :
999
-                        $updates;
1000
-                }
1001
-            }
1002
-        }
1003
-        // only recalculate totals if something changed
1004
-        if ($deleted || $updates) {
1005
-            $total_line_item->recalculate_total_including_taxes($update_txn_status);
1006
-            return true;
1007
-        }
1008
-        return false;
1009
-    }
1010
-
1011
-
1012
-    /**
1013
-     * Ensures that taxes have been applied to the order, if not applies them.
1014
-     * Returns the total amount of tax
1015
-     *
1016
-     * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
1017
-     * @return float
1018
-     * @throws EE_Error
1019
-     * @throws InvalidArgumentException
1020
-     * @throws InvalidDataTypeException
1021
-     * @throws InvalidInterfaceException
1022
-     * @throws ReflectionException
1023
-     */
1024
-    public static function ensure_taxes_applied($total_line_item)
1025
-    {
1026
-        $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1027
-        if (! $taxes_subtotal->children()) {
1028
-            self::apply_taxes($total_line_item);
1029
-        }
1030
-        return $taxes_subtotal->total();
1031
-    }
1032
-
1033
-
1034
-    /**
1035
-     * Deletes ALL children of the passed line item
1036
-     *
1037
-     * @param EE_Line_Item $parent_line_item
1038
-     * @return bool
1039
-     * @throws EE_Error
1040
-     * @throws InvalidArgumentException
1041
-     * @throws InvalidDataTypeException
1042
-     * @throws InvalidInterfaceException
1043
-     * @throws ReflectionException
1044
-     */
1045
-    public static function delete_all_child_items(EE_Line_Item $parent_line_item)
1046
-    {
1047
-        $deleted = 0;
1048
-        foreach ($parent_line_item->children() as $child_line_item) {
1049
-            if ($child_line_item instanceof EE_Line_Item) {
1050
-                $deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
1051
-                if ($child_line_item->ID()) {
1052
-                    $child_line_item->delete();
1053
-                    unset($child_line_item);
1054
-                } else {
1055
-                    $parent_line_item->delete_child_line_item($child_line_item->code());
1056
-                }
1057
-                $deleted++;
1058
-            }
1059
-        }
1060
-        return $deleted;
1061
-    }
1062
-
1063
-
1064
-    /**
1065
-     * Deletes the line items as indicated by the line item code(s) provided,
1066
-     * regardless of where they're found in the line item tree. Automatically
1067
-     * re-calculates the line item totals and updates the related transaction. But
1068
-     * DOES NOT automatically upgrade the transaction's registrations' final prices (which
1069
-     * should probably change because of this).
1070
-     * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
1071
-     * after using this, to keep the registration final prices in-sync with the transaction's total.
1072
-     *
1073
-     * @param EE_Line_Item      $total_line_item of type EEM_Line_Item::type_total
1074
-     * @param array|bool|string $line_item_codes
1075
-     * @return int number of items successfully removed
1076
-     * @throws EE_Error
1077
-     */
1078
-    public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
1079
-    {
1080
-
1081
-        if ($total_line_item->type() !== EEM_Line_Item::type_total) {
1082
-            EE_Error::doing_it_wrong(
1083
-                'EEH_Line_Item::delete_items',
1084
-                esc_html__(
1085
-                    'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
1086
-                    'event_espresso'
1087
-                ),
1088
-                '4.6.18'
1089
-            );
1090
-        }
1091
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1092
-
1093
-        // check if only a single line_item_id was passed
1094
-        if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1095
-            // place single line_item_id in an array to appear as multiple line_item_ids
1096
-            $line_item_codes = array($line_item_codes);
1097
-        }
1098
-        $removals = 0;
1099
-        // cycle thru line_item_ids
1100
-        foreach ($line_item_codes as $line_item_id) {
1101
-            $removals += $total_line_item->delete_child_line_item($line_item_id);
1102
-        }
1103
-
1104
-        if ($removals > 0) {
1105
-            $total_line_item->recalculate_taxes_and_tax_total();
1106
-            return $removals;
1107
-        } else {
1108
-            return false;
1109
-        }
1110
-    }
1111
-
1112
-
1113
-    /**
1114
-     * Overwrites the previous tax by clearing out the old taxes, and creates a new
1115
-     * tax and updates the total line item accordingly
1116
-     *
1117
-     * @param EE_Line_Item $total_line_item
1118
-     * @param float        $amount
1119
-     * @param string       $name
1120
-     * @param string       $description
1121
-     * @param string       $code
1122
-     * @param boolean      $add_to_existing_line_item
1123
-     *                          if true, and a duplicate line item with the same code is found,
1124
-     *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
1125
-     * @return EE_Line_Item the new tax line item created
1126
-     * @throws EE_Error
1127
-     * @throws InvalidArgumentException
1128
-     * @throws InvalidDataTypeException
1129
-     * @throws InvalidInterfaceException
1130
-     * @throws ReflectionException
1131
-     */
1132
-    public static function set_total_tax_to(
1133
-        EE_Line_Item $total_line_item,
1134
-        $amount,
1135
-        $name = null,
1136
-        $description = null,
1137
-        $code = null,
1138
-        $add_to_existing_line_item = false
1139
-    ) {
1140
-        $tax_subtotal = self::get_taxes_subtotal($total_line_item);
1141
-        $taxable_total = $total_line_item->taxable_total();
1142
-
1143
-        if ($add_to_existing_line_item) {
1144
-            $new_tax = $tax_subtotal->get_child_line_item($code);
1145
-            EEM_Line_Item::instance()->delete(
1146
-                array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
1147
-            );
1148
-        } else {
1149
-            $new_tax = null;
1150
-            $tax_subtotal->delete_children_line_items();
1151
-        }
1152
-        if ($new_tax) {
1153
-            $new_tax->set_total($new_tax->total() + $amount);
1154
-            $new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
1155
-        } else {
1156
-            // no existing tax item. Create it
1157
-            $new_tax = EE_Line_Item::new_instance(array(
1158
-                'TXN_ID'      => $total_line_item->TXN_ID(),
1159
-                'LIN_name'    => $name ? $name : esc_html__('Tax', 'event_espresso'),
1160
-                'LIN_desc'    => $description ? $description : '',
1161
-                'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
1162
-                'LIN_total'   => $amount,
1163
-                'LIN_parent'  => $tax_subtotal->ID(),
1164
-                'LIN_type'    => EEM_Line_Item::type_tax,
1165
-                'LIN_code'    => $code,
1166
-            ));
1167
-        }
1168
-
1169
-        $new_tax = apply_filters(
1170
-            'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1171
-            $new_tax,
1172
-            $total_line_item
1173
-        );
1174
-        $new_tax->save();
1175
-        $tax_subtotal->set_total($new_tax->total());
1176
-        $tax_subtotal->save();
1177
-        $total_line_item->recalculate_total_including_taxes();
1178
-        return $new_tax;
1179
-    }
1180
-
1181
-
1182
-    /**
1183
-     * Makes all the line items which are children of $line_item taxable (or not).
1184
-     * Does NOT save the line items
1185
-     *
1186
-     * @param EE_Line_Item $line_item
1187
-     * @param boolean      $taxable
1188
-     * @param string       $code_substring_for_whitelist if this string is part of the line item's code
1189
-     *                                                   it will be whitelisted (ie, except from becoming taxable)
1190
-     * @throws EE_Error
1191
-     */
1192
-    public static function set_line_items_taxable(
1193
-        EE_Line_Item $line_item,
1194
-        $taxable = true,
1195
-        $code_substring_for_whitelist = null
1196
-    ) {
1197
-        $whitelisted = false;
1198
-        if ($code_substring_for_whitelist !== null) {
1199
-            $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1200
-        }
1201
-        if (! $whitelisted && $line_item->is_line_item()) {
1202
-            $line_item->set_is_taxable($taxable);
1203
-        }
1204
-        foreach ($line_item->children() as $child_line_item) {
1205
-            EEH_Line_Item::set_line_items_taxable(
1206
-                $child_line_item,
1207
-                $taxable,
1208
-                $code_substring_for_whitelist
1209
-            );
1210
-        }
1211
-    }
1212
-
1213
-
1214
-    /**
1215
-     * Gets all descendants that are event subtotals
1216
-     *
1217
-     * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1218
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1219
-     * @return EE_Line_Item[]
1220
-     * @throws EE_Error
1221
-     */
1222
-    public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1223
-    {
1224
-        return self::get_subtotals_of_object_type($parent_line_item, EEM_Line_Item::OBJ_TYPE_EVENT);
1225
-    }
1226
-
1227
-
1228
-    /**
1229
-     * Gets all descendants subtotals that match the supplied object type
1230
-     *
1231
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1232
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1233
-     * @param string       $obj_type
1234
-     * @return EE_Line_Item[]
1235
-     * @throws EE_Error
1236
-     */
1237
-    public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1238
-    {
1239
-        return self::_get_descendants_by_type_and_object_type(
1240
-            $parent_line_item,
1241
-            EEM_Line_Item::type_sub_total,
1242
-            $obj_type
1243
-        );
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Gets all descendants that are tickets
1249
-     *
1250
-     * @uses  EEH_Line_Item::get_line_items_of_object_type()
1251
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1252
-     * @return EE_Line_Item[]
1253
-     * @throws EE_Error
1254
-     */
1255
-    public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1256
-    {
1257
-        return self::get_line_items_of_object_type(
1258
-            $parent_line_item,
1259
-            EEM_Line_Item::OBJ_TYPE_TICKET
1260
-        );
1261
-    }
1262
-
1263
-
1264
-    /**
1265
-     * Gets all descendants subtotals that match the supplied object type
1266
-     *
1267
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1268
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1269
-     * @param string       $obj_type
1270
-     * @return EE_Line_Item[]
1271
-     * @throws EE_Error
1272
-     */
1273
-    public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1274
-    {
1275
-        return self::_get_descendants_by_type_and_object_type(
1276
-            $parent_line_item,
1277
-            EEM_Line_Item::type_line_item,
1278
-            $obj_type
1279
-        );
1280
-    }
1281
-
1282
-
1283
-    /**
1284
-     * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1285
-     *
1286
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1287
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1288
-     * @return EE_Line_Item[]
1289
-     * @throws EE_Error
1290
-     */
1291
-    public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1292
-    {
1293
-        return EEH_Line_Item::get_descendants_of_type(
1294
-            $parent_line_item,
1295
-            EEM_Line_Item::type_tax
1296
-        );
1297
-    }
1298
-
1299
-
1300
-    /**
1301
-     * Gets all the real items purchased which are children of this item
1302
-     *
1303
-     * @uses  EEH_Line_Item::get_descendants_of_type()
1304
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1305
-     * @return EE_Line_Item[]
1306
-     * @throws EE_Error
1307
-     */
1308
-    public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1309
-    {
1310
-        return EEH_Line_Item::get_descendants_of_type(
1311
-            $parent_line_item,
1312
-            EEM_Line_Item::type_line_item
1313
-        );
1314
-    }
1315
-
1316
-
1317
-    /**
1318
-     * Gets all descendants of supplied line item that match the supplied line item type
1319
-     *
1320
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1321
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1322
-     * @param string       $line_item_type   one of the EEM_Line_Item constants
1323
-     * @return EE_Line_Item[]
1324
-     * @throws EE_Error
1325
-     */
1326
-    public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1327
-    {
1328
-        return self::_get_descendants_by_type_and_object_type(
1329
-            $parent_line_item,
1330
-            $line_item_type,
1331
-            null
1332
-        );
1333
-    }
1334
-
1335
-
1336
-    /**
1337
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1338
-     * as well
1339
-     *
1340
-     * @param EE_Line_Item  $parent_line_item - the line item to find descendants of
1341
-     * @param string        $line_item_type   one of the EEM_Line_Item constants
1342
-     * @param string | NULL $obj_type         object model class name (minus prefix) or NULL to ignore object type when
1343
-     *                                        searching
1344
-     * @return EE_Line_Item[]
1345
-     * @throws EE_Error
1346
-     */
1347
-    protected static function _get_descendants_by_type_and_object_type(
1348
-        EE_Line_Item $parent_line_item,
1349
-        $line_item_type,
1350
-        $obj_type = null
1351
-    ) {
1352
-        $objects = array();
1353
-        foreach ($parent_line_item->children() as $child_line_item) {
1354
-            if ($child_line_item instanceof EE_Line_Item) {
1355
-                if (
1356
-                    $child_line_item->type() === $line_item_type
1357
-                    && (
1358
-                        $child_line_item->OBJ_type() === $obj_type || $obj_type === null
1359
-                    )
1360
-                ) {
1361
-                    $objects[] = $child_line_item;
1362
-                } else {
1363
-                    // go-through-all-its children looking for more matches
1364
-                    $objects = array_merge(
1365
-                        $objects,
1366
-                        self::_get_descendants_by_type_and_object_type(
1367
-                            $child_line_item,
1368
-                            $line_item_type,
1369
-                            $obj_type
1370
-                        )
1371
-                    );
1372
-                }
1373
-            }
1374
-        }
1375
-        return $objects;
1376
-    }
1377
-
1378
-
1379
-    /**
1380
-     * Gets all descendants subtotals that match the supplied object type
1381
-     *
1382
-     * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1383
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1384
-     * @param string       $OBJ_type         object type (like Event)
1385
-     * @param array        $OBJ_IDs          array of OBJ_IDs
1386
-     * @return EE_Line_Item[]
1387
-     * @throws EE_Error
1388
-     */
1389
-    public static function get_line_items_by_object_type_and_IDs(
1390
-        EE_Line_Item $parent_line_item,
1391
-        $OBJ_type = '',
1392
-        $OBJ_IDs = array()
1393
-    ) {
1394
-        return self::_get_descendants_by_object_type_and_object_ID(
1395
-            $parent_line_item,
1396
-            $OBJ_type,
1397
-            $OBJ_IDs
1398
-        );
1399
-    }
1400
-
1401
-
1402
-    /**
1403
-     * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1404
-     * as well
1405
-     *
1406
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1407
-     * @param string       $OBJ_type         object type (like Event)
1408
-     * @param array        $OBJ_IDs          array of OBJ_IDs
1409
-     * @return EE_Line_Item[]
1410
-     * @throws EE_Error
1411
-     */
1412
-    protected static function _get_descendants_by_object_type_and_object_ID(
1413
-        EE_Line_Item $parent_line_item,
1414
-        $OBJ_type,
1415
-        $OBJ_IDs
1416
-    ) {
1417
-        $objects = array();
1418
-        foreach ($parent_line_item->children() as $child_line_item) {
1419
-            if ($child_line_item instanceof EE_Line_Item) {
1420
-                if (
1421
-                    $child_line_item->OBJ_type() === $OBJ_type
1422
-                    && is_array($OBJ_IDs)
1423
-                    && in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1424
-                ) {
1425
-                    $objects[] = $child_line_item;
1426
-                } else {
1427
-                    // go-through-all-its children looking for more matches
1428
-                    $objects = array_merge(
1429
-                        $objects,
1430
-                        self::_get_descendants_by_object_type_and_object_ID(
1431
-                            $child_line_item,
1432
-                            $OBJ_type,
1433
-                            $OBJ_IDs
1434
-                        )
1435
-                    );
1436
-                }
1437
-            }
1438
-        }
1439
-        return $objects;
1440
-    }
1441
-
1442
-
1443
-    /**
1444
-     * Uses a breadth-first-search in order to find the nearest descendant of
1445
-     * the specified type and returns it, else NULL
1446
-     *
1447
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1448
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1449
-     * @param string       $type             like one of the EEM_Line_Item::type_*
1450
-     * @return EE_Line_Item
1451
-     * @throws EE_Error
1452
-     * @throws InvalidArgumentException
1453
-     * @throws InvalidDataTypeException
1454
-     * @throws InvalidInterfaceException
1455
-     * @throws ReflectionException
1456
-     */
1457
-    public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1458
-    {
1459
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1460
-    }
1461
-
1462
-
1463
-    /**
1464
-     * Uses a breadth-first-search in order to find the nearest descendant
1465
-     * having the specified LIN_code and returns it, else NULL
1466
-     *
1467
-     * @uses  EEH_Line_Item::_get_nearest_descendant()
1468
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1469
-     * @param string       $code             any value used for LIN_code
1470
-     * @return EE_Line_Item
1471
-     * @throws EE_Error
1472
-     * @throws InvalidArgumentException
1473
-     * @throws InvalidDataTypeException
1474
-     * @throws InvalidInterfaceException
1475
-     * @throws ReflectionException
1476
-     */
1477
-    public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1478
-    {
1479
-        return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1480
-    }
1481
-
1482
-
1483
-    /**
1484
-     * Uses a breadth-first-search in order to find the nearest descendant
1485
-     * having the specified LIN_code and returns it, else NULL
1486
-     *
1487
-     * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1488
-     * @param string       $search_field     name of EE_Line_Item property
1489
-     * @param string       $value            any value stored in $search_field
1490
-     * @return EE_Line_Item
1491
-     * @throws EE_Error
1492
-     * @throws InvalidArgumentException
1493
-     * @throws InvalidDataTypeException
1494
-     * @throws InvalidInterfaceException
1495
-     * @throws ReflectionException
1496
-     */
1497
-    protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1498
-    {
1499
-        foreach ($parent_line_item->children() as $child) {
1500
-            if ($child->get($search_field) == $value) {
1501
-                return $child;
1502
-            }
1503
-        }
1504
-        foreach ($parent_line_item->children() as $child) {
1505
-            $descendant_found = self::_get_nearest_descendant(
1506
-                $child,
1507
-                $search_field,
1508
-                $value
1509
-            );
1510
-            if ($descendant_found) {
1511
-                return $descendant_found;
1512
-            }
1513
-        }
1514
-        return null;
1515
-    }
1516
-
1517
-
1518
-    /**
1519
-     * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1520
-     * else recursively walks up the line item tree until a parent of type total is found,
1521
-     *
1522
-     * @param EE_Line_Item $line_item
1523
-     * @return EE_Line_Item
1524
-     * @throws EE_Error
1525
-     */
1526
-    public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1527
-    {
1528
-        if ($line_item->TXN_ID()) {
1529
-            $total_line_item = $line_item->transaction()->total_line_item(false);
1530
-            if ($total_line_item instanceof EE_Line_Item) {
1531
-                return $total_line_item;
1532
-            }
1533
-        } else {
1534
-            $line_item_parent = $line_item->parent();
1535
-            if ($line_item_parent instanceof EE_Line_Item) {
1536
-                if ($line_item_parent->is_total()) {
1537
-                    return $line_item_parent;
1538
-                }
1539
-                return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1540
-            }
1541
-        }
1542
-        throw new EE_Error(
1543
-            sprintf(
1544
-                esc_html__(
1545
-                    'A valid grand total for line item %1$d was not found.',
1546
-                    'event_espresso'
1547
-                ),
1548
-                $line_item->ID()
1549
-            )
1550
-        );
1551
-    }
1552
-
1553
-
1554
-    /**
1555
-     * Prints out a representation of the line item tree
1556
-     *
1557
-     * @param EE_Line_Item $line_item
1558
-     * @param int          $indentation
1559
-     * @return void
1560
-     * @throws EE_Error
1561
-     */
1562
-    public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1563
-    {
1564
-        echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1565
-        if (! $indentation) {
1566
-            echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1567
-        }
1568
-        for ($i = 0; $i < $indentation; $i++) {
1569
-            echo '. ';
1570
-        }
1571
-        $breakdown = '';
1572
-        if ($line_item->is_line_item()) {
1573
-            if ($line_item->is_percent()) {
1574
-                $breakdown = "{$line_item->percent()}%";
1575
-            } else {
1576
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1577
-            }
1578
-        }
1579
-        echo $line_item->name();
1580
-        echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1581
-        echo '$' . (string) $line_item->total();
1582
-        if ($breakdown) {
1583
-            echo " ( {$breakdown} )";
1584
-        }
1585
-        if ($line_item->is_taxable()) {
1586
-            echo '  * taxable';
1587
-        }
1588
-        if ($line_item->children()) {
1589
-            foreach ($line_item->children() as $child) {
1590
-                self::visualize($child, $indentation + 1);
1591
-            }
1592
-        }
1593
-    }
1594
-
1595
-
1596
-    /**
1597
-     * Calculates the registration's final price, taking into account that they
1598
-     * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1599
-     * and receive a portion of any transaction-wide discounts.
1600
-     * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1601
-     * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1602
-     * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1603
-     * and brent's final price should be $5.50.
1604
-     * In order to do this, we basically need to traverse the line item tree calculating
1605
-     * the running totals (just as if we were recalculating the total), but when we identify
1606
-     * regular line items, we need to keep track of their share of the grand total.
1607
-     * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1608
-     * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1609
-     * when there are non-taxable items; otherwise they would be the same)
1610
-     *
1611
-     * @param EE_Line_Item $line_item
1612
-     * @param array        $billable_ticket_quantities  array of EE_Ticket IDs and their corresponding quantity that
1613
-     *                                                  can be included in price calculations at this moment
1614
-     * @return array        keys are line items for tickets IDs and values are their share of the running total,
1615
-     *                                                  plus the key 'total', and 'taxable' which also has keys of all
1616
-     *                                                  the ticket IDs.
1617
-     *                                                  Eg array(
1618
-     *                                                      12 => 4.3
1619
-     *                                                      23 => 8.0
1620
-     *                                                      'total' => 16.6,
1621
-     *                                                      'taxable' => array(
1622
-     *                                                          12 => 10,
1623
-     *                                                          23 => 4
1624
-     *                                                      ).
1625
-     *                                                  So to find which registrations have which final price, we need
1626
-     *                                                  to find which line item is theirs, which can be done with
1627
-     *                                                  `EEM_Line_Item::instance()->get_line_item_for_registration(
1628
-     *                                                  $registration );`
1629
-     * @throws EE_Error
1630
-     * @throws InvalidArgumentException
1631
-     * @throws InvalidDataTypeException
1632
-     * @throws InvalidInterfaceException
1633
-     * @throws ReflectionException
1634
-     */
1635
-    public static function calculate_reg_final_prices_per_line_item(
1636
-        EE_Line_Item $line_item,
1637
-        $billable_ticket_quantities = array()
1638
-    ) {
1639
-        $running_totals = [
1640
-            'total'   => 0,
1641
-            'taxable' => ['total' => 0]
1642
-        ];
1643
-        foreach ($line_item->children() as $child_line_item) {
1644
-            switch ($child_line_item->type()) {
1645
-                case EEM_Line_Item::type_sub_total:
1646
-                    $running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1647
-                        $child_line_item,
1648
-                        $billable_ticket_quantities
1649
-                    );
1650
-                    // combine arrays but preserve numeric keys
1651
-                    $running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1652
-                    $running_totals['total'] += $running_totals_from_subtotal['total'];
1653
-                    $running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1654
-                    break;
1655
-
1656
-                case EEM_Line_Item::type_tax_sub_total:
1657
-                    // find how much the taxes percentage is
1658
-                    if ($child_line_item->percent() !== 0) {
1659
-                        $tax_percent_decimal = $child_line_item->percent() / 100;
1660
-                    } else {
1661
-                        $tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1662
-                    }
1663
-                    // and apply to all the taxable totals, and add to the pretax totals
1664
-                    foreach ($running_totals as $line_item_id => $this_running_total) {
1665
-                        // "total" and "taxable" array key is an exception
1666
-                        if ($line_item_id === 'taxable') {
1667
-                            continue;
1668
-                        }
1669
-                        $taxable_total = $running_totals['taxable'][ $line_item_id ];
1670
-                        $running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1671
-                    }
1672
-                    break;
1673
-
1674
-                case EEM_Line_Item::type_line_item:
1675
-                    // ticket line items or ????
1676
-                    if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1677
-                        // kk it's a ticket
1678
-                        if (isset($running_totals[ $child_line_item->ID() ])) {
1679
-                            // huh? that shouldn't happen.
1680
-                            $running_totals['total'] += $child_line_item->total();
1681
-                        } else {
1682
-                            // its not in our running totals yet. great.
1683
-                            if ($child_line_item->is_taxable()) {
1684
-                                $taxable_amount = $child_line_item->unit_price();
1685
-                            } else {
1686
-                                $taxable_amount = 0;
1687
-                            }
1688
-                            // are we only calculating totals for some tickets?
1689
-                            if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1690
-                                $quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1691
-                                $running_totals[ $child_line_item->ID() ] = $quantity
1692
-                                    ? $child_line_item->unit_price()
1693
-                                    : 0;
1694
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1695
-                                    ? $taxable_amount
1696
-                                    : 0;
1697
-                            } else {
1698
-                                $quantity = $child_line_item->quantity();
1699
-                                $running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1700
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1701
-                            }
1702
-                            $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1703
-                            $running_totals['total'] += $child_line_item->unit_price() * $quantity;
1704
-                        }
1705
-                    } else {
1706
-                        // it's some other type of item added to the cart
1707
-                        // it should affect the running totals
1708
-                        // basically we want to convert it into a PERCENT modifier. Because
1709
-                        // more clearly affect all registration's final price equally
1710
-                        $line_items_percent_of_running_total = $running_totals['total'] > 0
1711
-                            ? ($child_line_item->total() / $running_totals['total']) + 1
1712
-                            : 1;
1713
-                        foreach ($running_totals as $line_item_id => $this_running_total) {
1714
-                            // the "taxable" array key is an exception
1715
-                            if ($line_item_id === 'taxable') {
1716
-                                continue;
1717
-                            }
1718
-                            // update the running totals
1719
-                            // yes this actually even works for the running grand total!
1720
-                            $running_totals[ $line_item_id ] =
1721
-                                $line_items_percent_of_running_total * $this_running_total;
1722
-
1723
-                            if ($child_line_item->is_taxable()) {
1724
-                                $running_totals['taxable'][ $line_item_id ] =
1725
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1726
-                            }
1727
-                        }
1728
-                    }
1729
-                    break;
1730
-            }
1731
-        }
1732
-        return $running_totals;
1733
-    }
1734
-
1735
-
1736
-    /**
1737
-     * @param EE_Line_Item $total_line_item
1738
-     * @param EE_Line_Item $ticket_line_item
1739
-     * @return float | null
1740
-     * @throws EE_Error
1741
-     * @throws InvalidArgumentException
1742
-     * @throws InvalidDataTypeException
1743
-     * @throws InvalidInterfaceException
1744
-     * @throws OutOfRangeException
1745
-     * @throws ReflectionException
1746
-     */
1747
-    public static function calculate_final_price_for_ticket_line_item(
1748
-        EE_Line_Item $total_line_item,
1749
-        EE_Line_Item $ticket_line_item
1750
-    ) {
1751
-        static $final_prices_per_ticket_line_item = array();
1752
-        if (empty($final_prices_per_ticket_line_item) || empty($final_prices_per_ticket_line_item[ $total_line_item->ID() ])) {
1753
-            $final_prices_per_ticket_line_item[ $total_line_item->ID() ] = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1754
-                $total_line_item
1755
-            );
1756
-        }
1757
-        // ok now find this new registration's final price
1758
-        if (isset($final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ])) {
1759
-            return $final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ];
1760
-        }
1761
-        $message = sprintf(
1762
-            esc_html__(
1763
-                'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1764
-                'event_espresso'
1765
-            ),
1766
-            $ticket_line_item->ID()
1767
-        );
1768
-        if (WP_DEBUG) {
1769
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1770
-            throw new OutOfRangeException($message);
1771
-        }
1772
-        EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1773
-        return null;
1774
-    }
1775
-
1776
-
1777
-    /**
1778
-     * Creates a duplicate of the line item tree, except only includes billable items
1779
-     * and the portion of line items attributed to billable things
1780
-     *
1781
-     * @param EE_Line_Item      $line_item
1782
-     * @param EE_Registration[] $registrations
1783
-     * @return EE_Line_Item
1784
-     * @throws EE_Error
1785
-     * @throws InvalidArgumentException
1786
-     * @throws InvalidDataTypeException
1787
-     * @throws InvalidInterfaceException
1788
-     * @throws ReflectionException
1789
-     */
1790
-    public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1791
-    {
1792
-        $copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1793
-        foreach ($line_item->children() as $child_li) {
1794
-            $copy_li->add_child_line_item(
1795
-                EEH_Line_Item::billable_line_item_tree($child_li, $registrations)
1796
-            );
1797
-        }
1798
-        // if this is the grand total line item, make sure the totals all add up
1799
-        // (we could have duplicated this logic AS we copied the line items, but
1800
-        // it seems DRYer this way)
1801
-        if ($copy_li->type() === EEM_Line_Item::type_total) {
1802
-            $copy_li->recalculate_total_including_taxes();
1803
-        }
1804
-        return $copy_li;
1805
-    }
1806
-
1807
-
1808
-    /**
1809
-     * Creates a new, unsaved line item from $line_item that factors in the
1810
-     * number of billable registrations on $registrations.
1811
-     *
1812
-     * @param EE_Line_Item      $line_item
1813
-     * @param EE_Registration[] $registrations
1814
-     * @return EE_Line_Item
1815
-     * @throws EE_Error
1816
-     * @throws InvalidArgumentException
1817
-     * @throws InvalidDataTypeException
1818
-     * @throws InvalidInterfaceException
1819
-     * @throws ReflectionException
1820
-     */
1821
-    public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1822
-    {
1823
-        $new_li_fields = $line_item->model_field_array();
1824
-        if (
1825
-            $line_item->type() === EEM_Line_Item::type_line_item &&
1826
-            $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1827
-        ) {
1828
-            $count = 0;
1829
-            foreach ($registrations as $registration) {
1830
-                if (
1831
-                    $line_item->OBJ_ID() === $registration->ticket_ID() &&
1832
-                    in_array(
1833
-                        $registration->status_ID(),
1834
-                        EEM_Registration::reg_statuses_that_allow_payment(),
1835
-                        true
1836
-                    )
1837
-                ) {
1838
-                    $count++;
1839
-                }
1840
-            }
1841
-            $new_li_fields['LIN_quantity'] = $count;
1842
-        }
1843
-        // don't set the total. We'll leave that up to the code that calculates it
1844
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1845
-        return EE_Line_Item::new_instance($new_li_fields);
1846
-    }
1847
-
1848
-
1849
-    /**
1850
-     * Returns a modified line item tree where all the subtotals which have a total of 0
1851
-     * are removed, and line items with a quantity of 0
1852
-     *
1853
-     * @param EE_Line_Item $line_item |null
1854
-     * @return EE_Line_Item|null
1855
-     * @throws EE_Error
1856
-     * @throws InvalidArgumentException
1857
-     * @throws InvalidDataTypeException
1858
-     * @throws InvalidInterfaceException
1859
-     * @throws ReflectionException
1860
-     */
1861
-    public static function non_empty_line_items(EE_Line_Item $line_item)
1862
-    {
1863
-        $copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1864
-        if ($copied_li === null) {
1865
-            return null;
1866
-        }
1867
-        // if this is an event subtotal, we want to only include it if it
1868
-        // has a non-zero total and at least one ticket line item child
1869
-        $ticket_children = 0;
1870
-        foreach ($line_item->children() as $child_li) {
1871
-            $child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1872
-            if ($child_li_copy !== null) {
1873
-                $copied_li->add_child_line_item($child_li_copy);
1874
-                if (
1875
-                    $child_li_copy->type() === EEM_Line_Item::type_line_item &&
1876
-                    $child_li_copy->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1877
-                ) {
1878
-                    $ticket_children++;
1879
-                }
1880
-            }
1881
-        }
1882
-        // if this is an event subtotal with NO ticket children
1883
-        // we basically want to ignore it
1884
-        if (
1885
-            $ticket_children === 0
1886
-            && $line_item->type() === EEM_Line_Item::type_sub_total
1887
-            && $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
1888
-            && $line_item->total() === 0
1889
-        ) {
1890
-            return null;
1891
-        }
1892
-        return $copied_li;
1893
-    }
1894
-
1895
-
1896
-    /**
1897
-     * Creates a new, unsaved line item, but if it's a ticket line item
1898
-     * with a total of 0, or a subtotal of 0, returns null instead
1899
-     *
1900
-     * @param EE_Line_Item $line_item
1901
-     * @return EE_Line_Item
1902
-     * @throws EE_Error
1903
-     * @throws InvalidArgumentException
1904
-     * @throws InvalidDataTypeException
1905
-     * @throws InvalidInterfaceException
1906
-     * @throws ReflectionException
1907
-     */
1908
-    public static function non_empty_line_item(EE_Line_Item $line_item)
1909
-    {
1910
-        if (
1911
-            $line_item->type() === EEM_Line_Item::type_line_item
1912
-            && $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1913
-            && $line_item->quantity() === 0
1914
-        ) {
1915
-            return null;
1916
-        }
1917
-        $new_li_fields = $line_item->model_field_array();
1918
-        // don't set the total. We'll leave that up to the code that calculates it
1919
-        unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1920
-        return EE_Line_Item::new_instance($new_li_fields);
1921
-    }
1922
-
1923
-
1924
-    /**
1925
-     * Cycles through all of the ticket line items for the supplied total line item
1926
-     * and ensures that the line item's "is_taxable" field matches that of its corresponding ticket
1927
-     *
1928
-     * @param EE_Line_Item $total_line_item
1929
-     * @since 4.9.79.p
1930
-     * @throws EE_Error
1931
-     * @throws InvalidArgumentException
1932
-     * @throws InvalidDataTypeException
1933
-     * @throws InvalidInterfaceException
1934
-     * @throws ReflectionException
1935
-     */
1936
-    public static function resetIsTaxableForTickets(EE_Line_Item $total_line_item)
1937
-    {
1938
-        $ticket_line_items = self::get_ticket_line_items($total_line_item);
1939
-        foreach ($ticket_line_items as $ticket_line_item) {
1940
-            if (
1941
-                $ticket_line_item instanceof EE_Line_Item
1942
-                && $ticket_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1943
-            ) {
1944
-                $ticket = $ticket_line_item->ticket();
1945
-                if ($ticket instanceof EE_Ticket && $ticket->taxable() !== $ticket_line_item->is_taxable()) {
1946
-                    $ticket_line_item->set_is_taxable($ticket->taxable());
1947
-                    $ticket_line_item->save();
1948
-                }
1949
-            }
1950
-        }
1951
-    }
1952
-
1953
-
1954
-
1955
-    /**************************************** @DEPRECATED METHODS *************************************** */
1956
-    /**
1957
-     * @deprecated
1958
-     * @param EE_Line_Item $total_line_item
1959
-     * @return EE_Line_Item
1960
-     * @throws EE_Error
1961
-     * @throws InvalidArgumentException
1962
-     * @throws InvalidDataTypeException
1963
-     * @throws InvalidInterfaceException
1964
-     * @throws ReflectionException
1965
-     */
1966
-    public static function get_items_subtotal(EE_Line_Item $total_line_item)
1967
-    {
1968
-        EE_Error::doing_it_wrong(
1969
-            'EEH_Line_Item::get_items_subtotal()',
1970
-            sprintf(
1971
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1972
-                'EEH_Line_Item::get_pre_tax_subtotal()'
1973
-            ),
1974
-            '4.6.0'
1975
-        );
1976
-        return self::get_pre_tax_subtotal($total_line_item);
1977
-    }
1978
-
1979
-
1980
-    /**
1981
-     * @deprecated
1982
-     * @param EE_Transaction $transaction
1983
-     * @return EE_Line_Item
1984
-     * @throws EE_Error
1985
-     * @throws InvalidArgumentException
1986
-     * @throws InvalidDataTypeException
1987
-     * @throws InvalidInterfaceException
1988
-     * @throws ReflectionException
1989
-     */
1990
-    public static function create_default_total_line_item($transaction = null)
1991
-    {
1992
-        EE_Error::doing_it_wrong(
1993
-            'EEH_Line_Item::create_default_total_line_item()',
1994
-            sprintf(
1995
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
1996
-                'EEH_Line_Item::create_total_line_item()'
1997
-            ),
1998
-            '4.6.0'
1999
-        );
2000
-        return self::create_total_line_item($transaction);
2001
-    }
2002
-
2003
-
2004
-    /**
2005
-     * @deprecated
2006
-     * @param EE_Line_Item   $total_line_item
2007
-     * @param EE_Transaction $transaction
2008
-     * @return EE_Line_Item
2009
-     * @throws EE_Error
2010
-     * @throws InvalidArgumentException
2011
-     * @throws InvalidDataTypeException
2012
-     * @throws InvalidInterfaceException
2013
-     * @throws ReflectionException
2014
-     */
2015
-    public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2016
-    {
2017
-        EE_Error::doing_it_wrong(
2018
-            'EEH_Line_Item::create_default_tickets_subtotal()',
2019
-            sprintf(
2020
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2021
-                'EEH_Line_Item::create_pre_tax_subtotal()'
2022
-            ),
2023
-            '4.6.0'
2024
-        );
2025
-        return self::create_pre_tax_subtotal($total_line_item, $transaction);
2026
-    }
2027
-
2028
-
2029
-    /**
2030
-     * @deprecated
2031
-     * @param EE_Line_Item   $total_line_item
2032
-     * @param EE_Transaction $transaction
2033
-     * @return EE_Line_Item
2034
-     * @throws EE_Error
2035
-     * @throws InvalidArgumentException
2036
-     * @throws InvalidDataTypeException
2037
-     * @throws InvalidInterfaceException
2038
-     * @throws ReflectionException
2039
-     */
2040
-    public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2041
-    {
2042
-        EE_Error::doing_it_wrong(
2043
-            'EEH_Line_Item::create_default_taxes_subtotal()',
2044
-            sprintf(
2045
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2046
-                'EEH_Line_Item::create_taxes_subtotal()'
2047
-            ),
2048
-            '4.6.0'
2049
-        );
2050
-        return self::create_taxes_subtotal($total_line_item, $transaction);
2051
-    }
2052
-
2053
-
2054
-    /**
2055
-     * @deprecated
2056
-     * @param EE_Line_Item   $total_line_item
2057
-     * @param EE_Transaction $transaction
2058
-     * @return EE_Line_Item
2059
-     * @throws EE_Error
2060
-     * @throws InvalidArgumentException
2061
-     * @throws InvalidDataTypeException
2062
-     * @throws InvalidInterfaceException
2063
-     * @throws ReflectionException
2064
-     */
2065
-    public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2066
-    {
2067
-        EE_Error::doing_it_wrong(
2068
-            'EEH_Line_Item::create_default_event_subtotal()',
2069
-            sprintf(
2070
-                esc_html__('Method replaced with %1$s', 'event_espresso'),
2071
-                'EEH_Line_Item::create_event_subtotal()'
2072
-            ),
2073
-            '4.6.0'
2074
-        );
2075
-        return self::create_event_subtotal($total_line_item, $transaction);
2076
-    }
24
+	/**
25
+	 * Adds a simple item (unrelated to any other model object) to the provided PARENT line item.
26
+	 * Does NOT automatically re-calculate the line item totals or update the related transaction.
27
+	 * You should call recalculate_total_including_taxes() on the grant total line item after this
28
+	 * to update the subtotals, and EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
29
+	 * to keep the registration final prices in-sync with the transaction's total.
30
+	 *
31
+	 * @param EE_Line_Item $parent_line_item
32
+	 * @param string       $name
33
+	 * @param float        $unit_price
34
+	 * @param string       $description
35
+	 * @param int          $quantity
36
+	 * @param boolean      $taxable
37
+	 * @param boolean      $code if set to a value, ensures there is only one line item with that code
38
+	 * @return boolean success
39
+	 * @throws EE_Error
40
+	 * @throws InvalidArgumentException
41
+	 * @throws InvalidDataTypeException
42
+	 * @throws InvalidInterfaceException
43
+	 * @throws ReflectionException
44
+	 */
45
+	public static function add_unrelated_item(
46
+		EE_Line_Item $parent_line_item,
47
+		$name,
48
+		$unit_price,
49
+		$description = '',
50
+		$quantity = 1,
51
+		$taxable = false,
52
+		$code = null
53
+	) {
54
+		$items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
55
+		$line_item = EE_Line_Item::new_instance(array(
56
+			'LIN_name'       => $name,
57
+			'LIN_desc'       => $description,
58
+			'LIN_unit_price' => $unit_price,
59
+			'LIN_quantity'   => $quantity,
60
+			'LIN_percent'    => null,
61
+			'LIN_is_taxable' => $taxable,
62
+			'LIN_order'      => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
63
+			'LIN_total'      => (float) $unit_price * (int) $quantity,
64
+			'LIN_type'       => EEM_Line_Item::type_line_item,
65
+			'LIN_code'       => $code,
66
+		));
67
+		$line_item = apply_filters(
68
+			'FHEE__EEH_Line_Item__add_unrelated_item__line_item',
69
+			$line_item,
70
+			$parent_line_item
71
+		);
72
+		return self::add_item($parent_line_item, $line_item);
73
+	}
74
+
75
+
76
+	/**
77
+	 * Adds a simple item ( unrelated to any other model object) to the total line item,
78
+	 * in the correct spot in the line item tree. Does not automatically
79
+	 * re-calculate the line item totals, nor update the related transaction, nor upgrade the transaction's
80
+	 * registrations' final prices (which should probably change because of this).
81
+	 * You should call recalculate_total_including_taxes() on the grand total line item, then
82
+	 * update the transaction's total, and EE_Registration_Processor::update_registration_final_prices()
83
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
84
+	 *
85
+	 * @param EE_Line_Item $parent_line_item
86
+	 * @param string       $name
87
+	 * @param float        $percentage_amount
88
+	 * @param string       $description
89
+	 * @param boolean      $taxable
90
+	 * @return boolean success
91
+	 * @throws EE_Error
92
+	 */
93
+	public static function add_percentage_based_item(
94
+		EE_Line_Item $parent_line_item,
95
+		$name,
96
+		$percentage_amount,
97
+		$description = '',
98
+		$taxable = false
99
+	) {
100
+		$line_item = EE_Line_Item::new_instance(array(
101
+			'LIN_name'       => $name,
102
+			'LIN_desc'       => $description,
103
+			'LIN_unit_price' => 0,
104
+			'LIN_percent'    => $percentage_amount,
105
+			'LIN_quantity'   => 1,
106
+			'LIN_is_taxable' => $taxable,
107
+			'LIN_total'      => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
108
+			'LIN_type'       => EEM_Line_Item::type_line_item,
109
+			'LIN_parent'     => $parent_line_item->ID(),
110
+		));
111
+		$line_item = apply_filters(
112
+			'FHEE__EEH_Line_Item__add_percentage_based_item__line_item',
113
+			$line_item
114
+		);
115
+		return $parent_line_item->add_child_line_item($line_item, false);
116
+	}
117
+
118
+
119
+	/**
120
+	 * Returns the new line item created by adding a purchase of the ticket
121
+	 * ensures that ticket line item is saved, and that cart total has been recalculated.
122
+	 * If this ticket has already been purchased, just increments its count.
123
+	 * Automatically re-calculates the line item totals and updates the related transaction. But
124
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
125
+	 * should probably change because of this).
126
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
127
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
128
+	 *
129
+	 * @param EE_Line_Item $total_line_item grand total line item of type EEM_Line_Item::type_total
130
+	 * @param EE_Ticket    $ticket
131
+	 * @param int          $qty
132
+	 * @return EE_Line_Item
133
+	 * @throws EE_Error
134
+	 * @throws InvalidArgumentException
135
+	 * @throws InvalidDataTypeException
136
+	 * @throws InvalidInterfaceException
137
+	 * @throws ReflectionException
138
+	 */
139
+	public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
140
+	{
141
+		if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
142
+			throw new EE_Error(
143
+				sprintf(
144
+					esc_html__(
145
+						'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.',
146
+						'event_espresso'
147
+					),
148
+					$ticket->ID(),
149
+					$total_line_item->ID()
150
+				)
151
+			);
152
+		}
153
+		// either increment the qty for an existing ticket
154
+		$line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
155
+		// or add a new one
156
+		if (! $line_item instanceof EE_Line_Item) {
157
+			$line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
158
+		}
159
+		$total_line_item->recalculate_total_including_taxes();
160
+		return $line_item;
161
+	}
162
+
163
+
164
+	/**
165
+	 * Returns the new line item created by adding a purchase of the ticket
166
+	 *
167
+	 * @param EE_Line_Item $total_line_item
168
+	 * @param EE_Ticket    $ticket
169
+	 * @param int          $qty
170
+	 * @return EE_Line_Item
171
+	 * @throws EE_Error
172
+	 * @throws InvalidArgumentException
173
+	 * @throws InvalidDataTypeException
174
+	 * @throws InvalidInterfaceException
175
+	 * @throws ReflectionException
176
+	 */
177
+	public static function increment_ticket_qty_if_already_in_cart(
178
+		EE_Line_Item $total_line_item,
179
+		EE_Ticket $ticket,
180
+		$qty = 1
181
+	) {
182
+		$line_item = null;
183
+		if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
184
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
185
+			foreach ((array) $ticket_line_items as $ticket_line_item) {
186
+				if (
187
+					$ticket_line_item instanceof EE_Line_Item
188
+					&& (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
189
+				) {
190
+					$line_item = $ticket_line_item;
191
+					break;
192
+				}
193
+			}
194
+		}
195
+		if ($line_item instanceof EE_Line_Item) {
196
+			EEH_Line_Item::increment_quantity($line_item, $qty);
197
+			return $line_item;
198
+		}
199
+		return null;
200
+	}
201
+
202
+
203
+	/**
204
+	 * Increments the line item and all its children's quantity by $qty (but percent line items are unaffected).
205
+	 * Does NOT save or recalculate other line items totals
206
+	 *
207
+	 * @param EE_Line_Item $line_item
208
+	 * @param int          $qty
209
+	 * @return void
210
+	 * @throws EE_Error
211
+	 * @throws InvalidArgumentException
212
+	 * @throws InvalidDataTypeException
213
+	 * @throws InvalidInterfaceException
214
+	 * @throws ReflectionException
215
+	 */
216
+	public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
217
+	{
218
+		if (! $line_item->is_percent()) {
219
+			$qty += $line_item->quantity();
220
+			$line_item->set_quantity($qty);
221
+			$line_item->set_total($line_item->unit_price() * $qty);
222
+			$line_item->save();
223
+		}
224
+		foreach ($line_item->children() as $child) {
225
+			if ($child->is_sub_line_item()) {
226
+				EEH_Line_Item::update_quantity($child, $qty);
227
+			}
228
+		}
229
+	}
230
+
231
+
232
+	/**
233
+	 * Decrements the line item and all its children's quantity by $qty (but percent line items are unaffected).
234
+	 * Does NOT save or recalculate other line items totals
235
+	 *
236
+	 * @param EE_Line_Item $line_item
237
+	 * @param int          $qty
238
+	 * @return void
239
+	 * @throws EE_Error
240
+	 * @throws InvalidArgumentException
241
+	 * @throws InvalidDataTypeException
242
+	 * @throws InvalidInterfaceException
243
+	 * @throws ReflectionException
244
+	 */
245
+	public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
246
+	{
247
+		if (! $line_item->is_percent()) {
248
+			$qty = $line_item->quantity() - $qty;
249
+			$qty = max($qty, 0);
250
+			$line_item->set_quantity($qty);
251
+			$line_item->set_total($line_item->unit_price() * $qty);
252
+			$line_item->save();
253
+		}
254
+		foreach ($line_item->children() as $child) {
255
+			if ($child->is_sub_line_item()) {
256
+				EEH_Line_Item::update_quantity($child, $qty);
257
+			}
258
+		}
259
+	}
260
+
261
+
262
+	/**
263
+	 * Updates the line item and its children's quantities to the specified number.
264
+	 * Does NOT save them or recalculate totals.
265
+	 *
266
+	 * @param EE_Line_Item $line_item
267
+	 * @param int          $new_quantity
268
+	 * @throws EE_Error
269
+	 * @throws InvalidArgumentException
270
+	 * @throws InvalidDataTypeException
271
+	 * @throws InvalidInterfaceException
272
+	 * @throws ReflectionException
273
+	 */
274
+	public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
275
+	{
276
+		if (! $line_item->is_percent()) {
277
+			$line_item->set_quantity($new_quantity);
278
+			$line_item->set_total($line_item->unit_price() * $new_quantity);
279
+			$line_item->save();
280
+		}
281
+		foreach ($line_item->children() as $child) {
282
+			if ($child->is_sub_line_item()) {
283
+				EEH_Line_Item::update_quantity($child, $new_quantity);
284
+			}
285
+		}
286
+	}
287
+
288
+
289
+	/**
290
+	 * Returns the new line item created by adding a purchase of the ticket
291
+	 *
292
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
293
+	 * @param EE_Ticket    $ticket
294
+	 * @param int          $qty
295
+	 * @return EE_Line_Item
296
+	 * @throws EE_Error
297
+	 * @throws InvalidArgumentException
298
+	 * @throws InvalidDataTypeException
299
+	 * @throws InvalidInterfaceException
300
+	 * @throws ReflectionException
301
+	 */
302
+	public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
303
+	{
304
+		$datetimes = $ticket->datetimes();
305
+		$first_datetime = reset($datetimes);
306
+		$first_datetime_name = esc_html__('Event', 'event_espresso');
307
+		if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
308
+			$first_datetime_name = $first_datetime->event()->name();
309
+		}
310
+		$event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
311
+		// get event subtotal line
312
+		$events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
313
+		// add $ticket to cart
314
+		$line_item = EE_Line_Item::new_instance(array(
315
+			'LIN_name'       => $ticket->name(),
316
+			'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
317
+			'LIN_unit_price' => $ticket->price(),
318
+			'LIN_quantity'   => $qty,
319
+			'LIN_is_taxable' => $ticket->taxable(),
320
+			'LIN_order'      => count($events_sub_total->children()),
321
+			'LIN_total'      => $ticket->price() * $qty,
322
+			'LIN_type'       => EEM_Line_Item::type_line_item,
323
+			'OBJ_ID'         => $ticket->ID(),
324
+			'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_TICKET,
325
+		));
326
+		$line_item = apply_filters(
327
+			'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
328
+			$line_item
329
+		);
330
+		$events_sub_total->add_child_line_item($line_item);
331
+		// now add the sub-line items
332
+		$running_total_for_ticket = 0;
333
+		foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
334
+			$sign = $price->is_discount() ? -1 : 1;
335
+			$price_total = $price->is_percent()
336
+				? $running_total_for_ticket * $price->amount() / 100
337
+				: $price->amount() * $qty;
338
+			$sub_line_item = EE_Line_Item::new_instance(array(
339
+				'LIN_name'       => $price->name(),
340
+				'LIN_desc'       => $price->desc(),
341
+				'LIN_quantity'   => $price->is_percent() ? null : $qty,
342
+				'LIN_is_taxable' => false,
343
+				'LIN_order'      => $price->order(),
344
+				'LIN_total'      => $sign * $price_total,
345
+				'LIN_type'       => EEM_Line_Item::type_sub_line_item,
346
+				'OBJ_ID'         => $price->ID(),
347
+				'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
348
+			));
349
+			$sub_line_item = apply_filters(
350
+				'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
351
+				$sub_line_item
352
+			);
353
+			if ($price->is_percent()) {
354
+				$sub_line_item->set_percent($sign * $price->amount());
355
+			} else {
356
+				$sub_line_item->set_unit_price($sign * $price->amount());
357
+			}
358
+			$running_total_for_ticket += $price_total;
359
+			$line_item->add_child_line_item($sub_line_item);
360
+		}
361
+		return $line_item;
362
+	}
363
+
364
+
365
+	/**
366
+	 * Adds the specified item under the pre-tax-sub-total line item. Automatically
367
+	 * re-calculates the line item totals and updates the related transaction. But
368
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
369
+	 * should probably change because of this).
370
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
371
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
372
+	 *
373
+	 * @param EE_Line_Item $total_line_item
374
+	 * @param EE_Line_Item $item to be added
375
+	 * @return boolean
376
+	 * @throws EE_Error
377
+	 * @throws InvalidArgumentException
378
+	 * @throws InvalidDataTypeException
379
+	 * @throws InvalidInterfaceException
380
+	 * @throws ReflectionException
381
+	 */
382
+	public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item)
383
+	{
384
+		$pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
385
+		if ($pre_tax_subtotal instanceof EE_Line_Item) {
386
+			$success = $pre_tax_subtotal->add_child_line_item($item);
387
+		} else {
388
+			return false;
389
+		}
390
+		$total_line_item->recalculate_total_including_taxes();
391
+		return $success;
392
+	}
393
+
394
+
395
+	/**
396
+	 * cancels an existing ticket line item,
397
+	 * by decrementing it's quantity by 1 and adding a new "type_cancellation" sub-line-item.
398
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
399
+	 *
400
+	 * @param EE_Line_Item $ticket_line_item
401
+	 * @param int          $qty
402
+	 * @return bool success
403
+	 * @throws EE_Error
404
+	 * @throws InvalidArgumentException
405
+	 * @throws InvalidDataTypeException
406
+	 * @throws InvalidInterfaceException
407
+	 * @throws ReflectionException
408
+	 */
409
+	public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
410
+	{
411
+		// validate incoming line_item
412
+		if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
413
+			throw new EE_Error(
414
+				sprintf(
415
+					esc_html__(
416
+						'The supplied line item must have an Object Type of "Ticket", not %1$s.',
417
+						'event_espresso'
418
+					),
419
+					$ticket_line_item->type()
420
+				)
421
+			);
422
+		}
423
+		if ($ticket_line_item->quantity() < $qty) {
424
+			throw new EE_Error(
425
+				sprintf(
426
+					esc_html__(
427
+						'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.',
428
+						'event_espresso'
429
+					),
430
+					$qty,
431
+					$ticket_line_item->quantity()
432
+				)
433
+			);
434
+		}
435
+		// decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
436
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
437
+		foreach ($ticket_line_item->children() as $child_line_item) {
438
+			if (
439
+				$child_line_item->is_sub_line_item()
440
+				&& ! $child_line_item->is_percent()
441
+				&& ! $child_line_item->is_cancellation()
442
+			) {
443
+				$child_line_item->set_quantity($child_line_item->quantity() - $qty);
444
+			}
445
+		}
446
+		// get cancellation sub line item
447
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
448
+			$ticket_line_item,
449
+			EEM_Line_Item::type_cancellation
450
+		);
451
+		$cancellation_line_item = reset($cancellation_line_item);
452
+		// verify that this ticket was indeed previously cancelled
453
+		if ($cancellation_line_item instanceof EE_Line_Item) {
454
+			// increment cancelled quantity
455
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
456
+		} else {
457
+			// create cancellation sub line item
458
+			$cancellation_line_item = EE_Line_Item::new_instance(array(
459
+				'LIN_name'       => esc_html__('Cancellation', 'event_espresso'),
460
+				'LIN_desc'       => sprintf(
461
+					esc_html_x(
462
+						'Cancelled %1$s : %2$s',
463
+						'Cancelled Ticket Name : 2015-01-01 11:11',
464
+						'event_espresso'
465
+					),
466
+					$ticket_line_item->name(),
467
+					current_time(get_option('date_format') . ' ' . get_option('time_format'))
468
+				),
469
+				'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
470
+				'LIN_quantity'   => $qty,
471
+				'LIN_is_taxable' => $ticket_line_item->is_taxable(),
472
+				'LIN_order'      => count($ticket_line_item->children()),
473
+				'LIN_total'      => 0, // $ticket_line_item->unit_price()
474
+				'LIN_type'       => EEM_Line_Item::type_cancellation,
475
+			));
476
+			$ticket_line_item->add_child_line_item($cancellation_line_item);
477
+		}
478
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
479
+			// decrement parent line item quantity
480
+			$event_line_item = $ticket_line_item->parent();
481
+			if (
482
+				$event_line_item instanceof EE_Line_Item
483
+				&& $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
484
+			) {
485
+				$event_line_item->set_quantity($event_line_item->quantity() - $qty);
486
+				$event_line_item->save();
487
+			}
488
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
489
+			return true;
490
+		}
491
+		return false;
492
+	}
493
+
494
+
495
+	/**
496
+	 * reinstates (un-cancels?) a previously canceled ticket line item,
497
+	 * by incrementing it's quantity by 1, and decrementing it's "type_cancellation" sub-line-item.
498
+	 * ALL totals and subtotals will NEED TO BE UPDATED after performing this action
499
+	 *
500
+	 * @param EE_Line_Item $ticket_line_item
501
+	 * @param int          $qty
502
+	 * @return bool success
503
+	 * @throws EE_Error
504
+	 * @throws InvalidArgumentException
505
+	 * @throws InvalidDataTypeException
506
+	 * @throws InvalidInterfaceException
507
+	 * @throws ReflectionException
508
+	 */
509
+	public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1)
510
+	{
511
+		// validate incoming line_item
512
+		if ($ticket_line_item->OBJ_type() !== EEM_Line_Item::OBJ_TYPE_TICKET) {
513
+			throw new EE_Error(
514
+				sprintf(
515
+					esc_html__(
516
+						'The supplied line item must have an Object Type of "Ticket", not %1$s.',
517
+						'event_espresso'
518
+					),
519
+					$ticket_line_item->type()
520
+				)
521
+			);
522
+		}
523
+		// get cancellation sub line item
524
+		$cancellation_line_item = EEH_Line_Item::get_descendants_of_type(
525
+			$ticket_line_item,
526
+			EEM_Line_Item::type_cancellation
527
+		);
528
+		$cancellation_line_item = reset($cancellation_line_item);
529
+		// verify that this ticket was indeed previously cancelled
530
+		if (! $cancellation_line_item instanceof EE_Line_Item) {
531
+			return false;
532
+		}
533
+		if ($cancellation_line_item->quantity() > $qty) {
534
+			// decrement cancelled quantity
535
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
536
+		} elseif ($cancellation_line_item->quantity() === $qty) {
537
+			// decrement cancelled quantity in case anyone still has the object kicking around
538
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
539
+			// delete because quantity will end up as 0
540
+			$cancellation_line_item->delete();
541
+			// and attempt to destroy the object,
542
+			// even though PHP won't actually destroy it until it needs the memory
543
+			unset($cancellation_line_item);
544
+		} else {
545
+			// what ?!?! negative quantity ?!?!
546
+			throw new EE_Error(
547
+				sprintf(
548
+					esc_html__(
549
+						'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
550
+						'event_espresso'
551
+					),
552
+					$qty,
553
+					$cancellation_line_item->quantity()
554
+				)
555
+			);
556
+		}
557
+		// increment ticket quantity
558
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
559
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
560
+			// increment parent line item quantity
561
+			$event_line_item = $ticket_line_item->parent();
562
+			if (
563
+				$event_line_item instanceof EE_Line_Item
564
+				&& $event_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
565
+			) {
566
+				$event_line_item->set_quantity($event_line_item->quantity() + $qty);
567
+			}
568
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
569
+			return true;
570
+		}
571
+		return false;
572
+	}
573
+
574
+
575
+	/**
576
+	 * calls EEH_Line_Item::find_transaction_grand_total_for_line_item()
577
+	 * then EE_Line_Item::recalculate_total_including_taxes() on the result
578
+	 *
579
+	 * @param EE_Line_Item $line_item
580
+	 * @return float
581
+	 * @throws EE_Error
582
+	 * @throws InvalidArgumentException
583
+	 * @throws InvalidDataTypeException
584
+	 * @throws InvalidInterfaceException
585
+	 * @throws ReflectionException
586
+	 */
587
+	public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item)
588
+	{
589
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
590
+		return $grand_total_line_item->recalculate_total_including_taxes();
591
+	}
592
+
593
+
594
+	/**
595
+	 * Gets the line item which contains the subtotal of all the items
596
+	 *
597
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
598
+	 * @return EE_Line_Item
599
+	 * @throws EE_Error
600
+	 * @throws InvalidArgumentException
601
+	 * @throws InvalidDataTypeException
602
+	 * @throws InvalidInterfaceException
603
+	 * @throws ReflectionException
604
+	 */
605
+	public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item)
606
+	{
607
+		$pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
608
+		return $pre_tax_subtotal instanceof EE_Line_Item
609
+			? $pre_tax_subtotal
610
+			: self::create_pre_tax_subtotal($total_line_item);
611
+	}
612
+
613
+
614
+	/**
615
+	 * Gets the line item for the taxes subtotal
616
+	 *
617
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
618
+	 * @return EE_Line_Item
619
+	 * @throws EE_Error
620
+	 * @throws InvalidArgumentException
621
+	 * @throws InvalidDataTypeException
622
+	 * @throws InvalidInterfaceException
623
+	 * @throws ReflectionException
624
+	 */
625
+	public static function get_taxes_subtotal(EE_Line_Item $total_line_item)
626
+	{
627
+		$taxes = $total_line_item->get_child_line_item('taxes');
628
+		return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
629
+	}
630
+
631
+
632
+	/**
633
+	 * sets the TXN ID on an EE_Line_Item if passed a valid EE_Transaction object
634
+	 *
635
+	 * @param EE_Line_Item   $line_item
636
+	 * @param EE_Transaction $transaction
637
+	 * @return void
638
+	 * @throws EE_Error
639
+	 * @throws InvalidArgumentException
640
+	 * @throws InvalidDataTypeException
641
+	 * @throws InvalidInterfaceException
642
+	 * @throws ReflectionException
643
+	 */
644
+	public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = null)
645
+	{
646
+		if ($transaction) {
647
+			/** @type EEM_Transaction $EEM_Transaction */
648
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
649
+			$TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
650
+			$line_item->set_TXN_ID($TXN_ID);
651
+		}
652
+	}
653
+
654
+
655
+	/**
656
+	 * Creates a new default total line item for the transaction,
657
+	 * and its tickets subtotal and taxes subtotal line items (and adds the
658
+	 * existing taxes as children of the taxes subtotal line item)
659
+	 *
660
+	 * @param EE_Transaction $transaction
661
+	 * @return EE_Line_Item of type total
662
+	 * @throws EE_Error
663
+	 * @throws InvalidArgumentException
664
+	 * @throws InvalidDataTypeException
665
+	 * @throws InvalidInterfaceException
666
+	 * @throws ReflectionException
667
+	 */
668
+	public static function create_total_line_item($transaction = null)
669
+	{
670
+		$total_line_item = EE_Line_Item::new_instance(array(
671
+			'LIN_code' => 'total',
672
+			'LIN_name' => esc_html__('Grand Total', 'event_espresso'),
673
+			'LIN_type' => EEM_Line_Item::type_total,
674
+			'OBJ_type' => EEM_Line_Item::OBJ_TYPE_TRANSACTION,
675
+		));
676
+		$total_line_item = apply_filters(
677
+			'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
678
+			$total_line_item
679
+		);
680
+		self::set_TXN_ID($total_line_item, $transaction);
681
+		self::create_pre_tax_subtotal($total_line_item, $transaction);
682
+		self::create_taxes_subtotal($total_line_item, $transaction);
683
+		return $total_line_item;
684
+	}
685
+
686
+
687
+	/**
688
+	 * Creates a default items subtotal line item
689
+	 *
690
+	 * @param EE_Line_Item   $total_line_item
691
+	 * @param EE_Transaction $transaction
692
+	 * @return EE_Line_Item
693
+	 * @throws EE_Error
694
+	 * @throws InvalidArgumentException
695
+	 * @throws InvalidDataTypeException
696
+	 * @throws InvalidInterfaceException
697
+	 * @throws ReflectionException
698
+	 */
699
+	protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = null)
700
+	{
701
+		$pre_tax_line_item = EE_Line_Item::new_instance(array(
702
+			'LIN_code' => 'pre-tax-subtotal',
703
+			'LIN_name' => esc_html__('Pre-Tax Subtotal', 'event_espresso'),
704
+			'LIN_type' => EEM_Line_Item::type_sub_total,
705
+		));
706
+		$pre_tax_line_item = apply_filters(
707
+			'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
708
+			$pre_tax_line_item
709
+		);
710
+		self::set_TXN_ID($pre_tax_line_item, $transaction);
711
+		$total_line_item->add_child_line_item($pre_tax_line_item);
712
+		self::create_event_subtotal($pre_tax_line_item, $transaction);
713
+		return $pre_tax_line_item;
714
+	}
715
+
716
+
717
+	/**
718
+	 * Creates a line item for the taxes subtotal and finds all the tax prices
719
+	 * and applies taxes to it
720
+	 *
721
+	 * @param EE_Line_Item   $total_line_item of type EEM_Line_Item::type_total
722
+	 * @param EE_Transaction $transaction
723
+	 * @return EE_Line_Item
724
+	 * @throws EE_Error
725
+	 * @throws InvalidArgumentException
726
+	 * @throws InvalidDataTypeException
727
+	 * @throws InvalidInterfaceException
728
+	 * @throws ReflectionException
729
+	 */
730
+	protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
731
+	{
732
+		$tax_line_item = EE_Line_Item::new_instance(array(
733
+			'LIN_code'  => 'taxes',
734
+			'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
735
+			'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
736
+			'LIN_order' => 1000,// this should always come last
737
+		));
738
+		$tax_line_item = apply_filters(
739
+			'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
740
+			$tax_line_item
741
+		);
742
+		self::set_TXN_ID($tax_line_item, $transaction);
743
+		$total_line_item->add_child_line_item($tax_line_item);
744
+		// and lastly, add the actual taxes
745
+		self::apply_taxes($total_line_item);
746
+		return $tax_line_item;
747
+	}
748
+
749
+
750
+	/**
751
+	 * Creates a default items subtotal line item
752
+	 *
753
+	 * @param EE_Line_Item   $pre_tax_line_item
754
+	 * @param EE_Transaction $transaction
755
+	 * @param EE_Event       $event
756
+	 * @return EE_Line_Item
757
+	 * @throws EE_Error
758
+	 * @throws InvalidArgumentException
759
+	 * @throws InvalidDataTypeException
760
+	 * @throws InvalidInterfaceException
761
+	 * @throws ReflectionException
762
+	 */
763
+	public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = null, $event = null)
764
+	{
765
+		$event_line_item = EE_Line_Item::new_instance(array(
766
+			'LIN_code' => self::get_event_code($event),
767
+			'LIN_name' => self::get_event_name($event),
768
+			'LIN_desc' => self::get_event_desc($event),
769
+			'LIN_type' => EEM_Line_Item::type_sub_total,
770
+			'OBJ_type' => EEM_Line_Item::OBJ_TYPE_EVENT,
771
+			'OBJ_ID'   => $event instanceof EE_Event ? $event->ID() : 0,
772
+		));
773
+		$event_line_item = apply_filters(
774
+			'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
775
+			$event_line_item
776
+		);
777
+		self::set_TXN_ID($event_line_item, $transaction);
778
+		$pre_tax_line_item->add_child_line_item($event_line_item);
779
+		return $event_line_item;
780
+	}
781
+
782
+
783
+	/**
784
+	 * Gets what the event ticket's code SHOULD be
785
+	 *
786
+	 * @param EE_Event $event
787
+	 * @return string
788
+	 * @throws EE_Error
789
+	 */
790
+	public static function get_event_code($event)
791
+	{
792
+		return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
793
+	}
794
+
795
+
796
+	/**
797
+	 * Gets the event name
798
+	 *
799
+	 * @param EE_Event $event
800
+	 * @return string
801
+	 * @throws EE_Error
802
+	 */
803
+	public static function get_event_name($event)
804
+	{
805
+		return $event instanceof EE_Event
806
+			? mb_substr($event->name(), 0, 245)
807
+			: esc_html__('Event', 'event_espresso');
808
+	}
809
+
810
+
811
+	/**
812
+	 * Gets the event excerpt
813
+	 *
814
+	 * @param EE_Event $event
815
+	 * @return string
816
+	 * @throws EE_Error
817
+	 */
818
+	public static function get_event_desc($event)
819
+	{
820
+		return $event instanceof EE_Event ? $event->short_description() : '';
821
+	}
822
+
823
+
824
+	/**
825
+	 * Given the grand total line item and a ticket, finds the event sub-total
826
+	 * line item the ticket's purchase should be added onto
827
+	 *
828
+	 * @access public
829
+	 * @param EE_Line_Item $grand_total the grand total line item
830
+	 * @param EE_Ticket    $ticket
831
+	 * @return EE_Line_Item
832
+	 * @throws EE_Error
833
+	 * @throws InvalidArgumentException
834
+	 * @throws InvalidDataTypeException
835
+	 * @throws InvalidInterfaceException
836
+	 * @throws ReflectionException
837
+	 */
838
+	public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
839
+	{
840
+		$first_datetime = $ticket->first_datetime();
841
+		if (! $first_datetime instanceof EE_Datetime) {
842
+			throw new EE_Error(
843
+				sprintf(
844
+					esc_html__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
845
+					$ticket->ID()
846
+				)
847
+			);
848
+		}
849
+		$event = $first_datetime->event();
850
+		if (! $event instanceof EE_Event) {
851
+			throw new EE_Error(
852
+				sprintf(
853
+					esc_html__(
854
+						'The supplied ticket (ID %d) has no event data associated with it.',
855
+						'event_espresso'
856
+					),
857
+					$ticket->ID()
858
+				)
859
+			);
860
+		}
861
+		$events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
862
+		if (! $events_sub_total instanceof EE_Line_Item) {
863
+			throw new EE_Error(
864
+				sprintf(
865
+					esc_html__(
866
+						'There is no events sub-total for ticket %s on total line item %d',
867
+						'event_espresso'
868
+					),
869
+					$ticket->ID(),
870
+					$grand_total->ID()
871
+				)
872
+			);
873
+		}
874
+		return $events_sub_total;
875
+	}
876
+
877
+
878
+	/**
879
+	 * Gets the event line item
880
+	 *
881
+	 * @param EE_Line_Item $grand_total
882
+	 * @param EE_Event     $event
883
+	 * @return EE_Line_Item for the event subtotal which is a child of $grand_total
884
+	 * @throws EE_Error
885
+	 * @throws InvalidArgumentException
886
+	 * @throws InvalidDataTypeException
887
+	 * @throws InvalidInterfaceException
888
+	 * @throws ReflectionException
889
+	 */
890
+	public static function get_event_line_item(EE_Line_Item $grand_total, $event)
891
+	{
892
+		/** @type EE_Event $event */
893
+		$event = EEM_Event::instance()->ensure_is_obj($event, true);
894
+		$event_line_item = null;
895
+		$found = false;
896
+		foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
897
+			// default event subtotal, we should only ever find this the first time this method is called
898
+			if (! $event_line_item->OBJ_ID()) {
899
+				// let's use this! but first... set the event details
900
+				EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
901
+				$found = true;
902
+				break;
903
+			}
904
+			if ($event_line_item->OBJ_ID() === $event->ID()) {
905
+				// found existing line item for this event in the cart, so break out of loop and use this one
906
+				$found = true;
907
+				break;
908
+			}
909
+		}
910
+		if (! $found) {
911
+			// there is no event sub-total yet, so add it
912
+			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
913
+			// create a new "event" subtotal below that
914
+			$event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
915
+			// and set the event details
916
+			EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
917
+		}
918
+		return $event_line_item;
919
+	}
920
+
921
+
922
+	/**
923
+	 * Creates a default items subtotal line item
924
+	 *
925
+	 * @param EE_Line_Item   $event_line_item
926
+	 * @param EE_Event       $event
927
+	 * @param EE_Transaction $transaction
928
+	 * @return void
929
+	 * @throws EE_Error
930
+	 * @throws InvalidArgumentException
931
+	 * @throws InvalidDataTypeException
932
+	 * @throws InvalidInterfaceException
933
+	 * @throws ReflectionException
934
+	 */
935
+	public static function set_event_subtotal_details(
936
+		EE_Line_Item $event_line_item,
937
+		EE_Event $event,
938
+		$transaction = null
939
+	) {
940
+		if ($event instanceof EE_Event) {
941
+			$event_line_item->set_code(self::get_event_code($event));
942
+			$event_line_item->set_name(self::get_event_name($event));
943
+			$event_line_item->set_desc(self::get_event_desc($event));
944
+			$event_line_item->set_OBJ_ID($event->ID());
945
+		}
946
+		self::set_TXN_ID($event_line_item, $transaction);
947
+	}
948
+
949
+
950
+	/**
951
+	 * Finds what taxes should apply, adds them as tax line items under the taxes sub-total,
952
+	 * and recalculates the taxes sub-total and the grand total. Resets the taxes, so
953
+	 * any old taxes are removed
954
+	 *
955
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
956
+	 * @param bool         $update_txn_status
957
+	 * @return bool
958
+	 * @throws EE_Error
959
+	 * @throws InvalidArgumentException
960
+	 * @throws InvalidDataTypeException
961
+	 * @throws InvalidInterfaceException
962
+	 * @throws ReflectionException
963
+	 * @throws RuntimeException
964
+	 */
965
+	public static function apply_taxes(EE_Line_Item $total_line_item, $update_txn_status = false)
966
+	{
967
+		/** @type EEM_Price $EEM_Price */
968
+		$EEM_Price = EE_Registry::instance()->load_model('Price');
969
+		// get array of taxes via Price Model
970
+		$ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
971
+		ksort($ordered_taxes);
972
+		$taxes_line_item = self::get_taxes_subtotal($total_line_item);
973
+		// just to be safe, remove its old tax line items
974
+		$deleted = $taxes_line_item->delete_children_line_items();
975
+		$updates = false;
976
+		// loop thru taxes
977
+		foreach ($ordered_taxes as $order => $taxes) {
978
+			foreach ($taxes as $tax) {
979
+				if ($tax instanceof EE_Price) {
980
+					$tax_line_item = EE_Line_Item::new_instance(
981
+						array(
982
+							'LIN_name'       => $tax->name(),
983
+							'LIN_desc'       => $tax->desc(),
984
+							'LIN_percent'    => $tax->amount(),
985
+							'LIN_is_taxable' => false,
986
+							'LIN_order'      => $order,
987
+							'LIN_total'      => 0,
988
+							'LIN_type'       => EEM_Line_Item::type_tax,
989
+							'OBJ_type'       => EEM_Line_Item::OBJ_TYPE_PRICE,
990
+							'OBJ_ID'         => $tax->ID(),
991
+						)
992
+					);
993
+					$tax_line_item = apply_filters(
994
+						'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
995
+						$tax_line_item
996
+					);
997
+					$updates = $taxes_line_item->add_child_line_item($tax_line_item) ?
998
+						true :
999
+						$updates;
1000
+				}
1001
+			}
1002
+		}
1003
+		// only recalculate totals if something changed
1004
+		if ($deleted || $updates) {
1005
+			$total_line_item->recalculate_total_including_taxes($update_txn_status);
1006
+			return true;
1007
+		}
1008
+		return false;
1009
+	}
1010
+
1011
+
1012
+	/**
1013
+	 * Ensures that taxes have been applied to the order, if not applies them.
1014
+	 * Returns the total amount of tax
1015
+	 *
1016
+	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
1017
+	 * @return float
1018
+	 * @throws EE_Error
1019
+	 * @throws InvalidArgumentException
1020
+	 * @throws InvalidDataTypeException
1021
+	 * @throws InvalidInterfaceException
1022
+	 * @throws ReflectionException
1023
+	 */
1024
+	public static function ensure_taxes_applied($total_line_item)
1025
+	{
1026
+		$taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1027
+		if (! $taxes_subtotal->children()) {
1028
+			self::apply_taxes($total_line_item);
1029
+		}
1030
+		return $taxes_subtotal->total();
1031
+	}
1032
+
1033
+
1034
+	/**
1035
+	 * Deletes ALL children of the passed line item
1036
+	 *
1037
+	 * @param EE_Line_Item $parent_line_item
1038
+	 * @return bool
1039
+	 * @throws EE_Error
1040
+	 * @throws InvalidArgumentException
1041
+	 * @throws InvalidDataTypeException
1042
+	 * @throws InvalidInterfaceException
1043
+	 * @throws ReflectionException
1044
+	 */
1045
+	public static function delete_all_child_items(EE_Line_Item $parent_line_item)
1046
+	{
1047
+		$deleted = 0;
1048
+		foreach ($parent_line_item->children() as $child_line_item) {
1049
+			if ($child_line_item instanceof EE_Line_Item) {
1050
+				$deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
1051
+				if ($child_line_item->ID()) {
1052
+					$child_line_item->delete();
1053
+					unset($child_line_item);
1054
+				} else {
1055
+					$parent_line_item->delete_child_line_item($child_line_item->code());
1056
+				}
1057
+				$deleted++;
1058
+			}
1059
+		}
1060
+		return $deleted;
1061
+	}
1062
+
1063
+
1064
+	/**
1065
+	 * Deletes the line items as indicated by the line item code(s) provided,
1066
+	 * regardless of where they're found in the line item tree. Automatically
1067
+	 * re-calculates the line item totals and updates the related transaction. But
1068
+	 * DOES NOT automatically upgrade the transaction's registrations' final prices (which
1069
+	 * should probably change because of this).
1070
+	 * You should call EE_Registration_Processor::calculate_reg_final_prices_per_line_item()
1071
+	 * after using this, to keep the registration final prices in-sync with the transaction's total.
1072
+	 *
1073
+	 * @param EE_Line_Item      $total_line_item of type EEM_Line_Item::type_total
1074
+	 * @param array|bool|string $line_item_codes
1075
+	 * @return int number of items successfully removed
1076
+	 * @throws EE_Error
1077
+	 */
1078
+	public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = false)
1079
+	{
1080
+
1081
+		if ($total_line_item->type() !== EEM_Line_Item::type_total) {
1082
+			EE_Error::doing_it_wrong(
1083
+				'EEH_Line_Item::delete_items',
1084
+				esc_html__(
1085
+					'This static method should only be called with a TOTAL line item, otherwise we won\'t recalculate the totals correctly',
1086
+					'event_espresso'
1087
+				),
1088
+				'4.6.18'
1089
+			);
1090
+		}
1091
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1092
+
1093
+		// check if only a single line_item_id was passed
1094
+		if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1095
+			// place single line_item_id in an array to appear as multiple line_item_ids
1096
+			$line_item_codes = array($line_item_codes);
1097
+		}
1098
+		$removals = 0;
1099
+		// cycle thru line_item_ids
1100
+		foreach ($line_item_codes as $line_item_id) {
1101
+			$removals += $total_line_item->delete_child_line_item($line_item_id);
1102
+		}
1103
+
1104
+		if ($removals > 0) {
1105
+			$total_line_item->recalculate_taxes_and_tax_total();
1106
+			return $removals;
1107
+		} else {
1108
+			return false;
1109
+		}
1110
+	}
1111
+
1112
+
1113
+	/**
1114
+	 * Overwrites the previous tax by clearing out the old taxes, and creates a new
1115
+	 * tax and updates the total line item accordingly
1116
+	 *
1117
+	 * @param EE_Line_Item $total_line_item
1118
+	 * @param float        $amount
1119
+	 * @param string       $name
1120
+	 * @param string       $description
1121
+	 * @param string       $code
1122
+	 * @param boolean      $add_to_existing_line_item
1123
+	 *                          if true, and a duplicate line item with the same code is found,
1124
+	 *                          $amount will be added onto it; otherwise will simply set the taxes to match $amount
1125
+	 * @return EE_Line_Item the new tax line item created
1126
+	 * @throws EE_Error
1127
+	 * @throws InvalidArgumentException
1128
+	 * @throws InvalidDataTypeException
1129
+	 * @throws InvalidInterfaceException
1130
+	 * @throws ReflectionException
1131
+	 */
1132
+	public static function set_total_tax_to(
1133
+		EE_Line_Item $total_line_item,
1134
+		$amount,
1135
+		$name = null,
1136
+		$description = null,
1137
+		$code = null,
1138
+		$add_to_existing_line_item = false
1139
+	) {
1140
+		$tax_subtotal = self::get_taxes_subtotal($total_line_item);
1141
+		$taxable_total = $total_line_item->taxable_total();
1142
+
1143
+		if ($add_to_existing_line_item) {
1144
+			$new_tax = $tax_subtotal->get_child_line_item($code);
1145
+			EEM_Line_Item::instance()->delete(
1146
+				array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
1147
+			);
1148
+		} else {
1149
+			$new_tax = null;
1150
+			$tax_subtotal->delete_children_line_items();
1151
+		}
1152
+		if ($new_tax) {
1153
+			$new_tax->set_total($new_tax->total() + $amount);
1154
+			$new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
1155
+		} else {
1156
+			// no existing tax item. Create it
1157
+			$new_tax = EE_Line_Item::new_instance(array(
1158
+				'TXN_ID'      => $total_line_item->TXN_ID(),
1159
+				'LIN_name'    => $name ? $name : esc_html__('Tax', 'event_espresso'),
1160
+				'LIN_desc'    => $description ? $description : '',
1161
+				'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
1162
+				'LIN_total'   => $amount,
1163
+				'LIN_parent'  => $tax_subtotal->ID(),
1164
+				'LIN_type'    => EEM_Line_Item::type_tax,
1165
+				'LIN_code'    => $code,
1166
+			));
1167
+		}
1168
+
1169
+		$new_tax = apply_filters(
1170
+			'FHEE__EEH_Line_Item__set_total_tax_to__new_tax_subtotal',
1171
+			$new_tax,
1172
+			$total_line_item
1173
+		);
1174
+		$new_tax->save();
1175
+		$tax_subtotal->set_total($new_tax->total());
1176
+		$tax_subtotal->save();
1177
+		$total_line_item->recalculate_total_including_taxes();
1178
+		return $new_tax;
1179
+	}
1180
+
1181
+
1182
+	/**
1183
+	 * Makes all the line items which are children of $line_item taxable (or not).
1184
+	 * Does NOT save the line items
1185
+	 *
1186
+	 * @param EE_Line_Item $line_item
1187
+	 * @param boolean      $taxable
1188
+	 * @param string       $code_substring_for_whitelist if this string is part of the line item's code
1189
+	 *                                                   it will be whitelisted (ie, except from becoming taxable)
1190
+	 * @throws EE_Error
1191
+	 */
1192
+	public static function set_line_items_taxable(
1193
+		EE_Line_Item $line_item,
1194
+		$taxable = true,
1195
+		$code_substring_for_whitelist = null
1196
+	) {
1197
+		$whitelisted = false;
1198
+		if ($code_substring_for_whitelist !== null) {
1199
+			$whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1200
+		}
1201
+		if (! $whitelisted && $line_item->is_line_item()) {
1202
+			$line_item->set_is_taxable($taxable);
1203
+		}
1204
+		foreach ($line_item->children() as $child_line_item) {
1205
+			EEH_Line_Item::set_line_items_taxable(
1206
+				$child_line_item,
1207
+				$taxable,
1208
+				$code_substring_for_whitelist
1209
+			);
1210
+		}
1211
+	}
1212
+
1213
+
1214
+	/**
1215
+	 * Gets all descendants that are event subtotals
1216
+	 *
1217
+	 * @uses  EEH_Line_Item::get_subtotals_of_object_type()
1218
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1219
+	 * @return EE_Line_Item[]
1220
+	 * @throws EE_Error
1221
+	 */
1222
+	public static function get_event_subtotals(EE_Line_Item $parent_line_item)
1223
+	{
1224
+		return self::get_subtotals_of_object_type($parent_line_item, EEM_Line_Item::OBJ_TYPE_EVENT);
1225
+	}
1226
+
1227
+
1228
+	/**
1229
+	 * Gets all descendants subtotals that match the supplied object type
1230
+	 *
1231
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1232
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1233
+	 * @param string       $obj_type
1234
+	 * @return EE_Line_Item[]
1235
+	 * @throws EE_Error
1236
+	 */
1237
+	public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1238
+	{
1239
+		return self::_get_descendants_by_type_and_object_type(
1240
+			$parent_line_item,
1241
+			EEM_Line_Item::type_sub_total,
1242
+			$obj_type
1243
+		);
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Gets all descendants that are tickets
1249
+	 *
1250
+	 * @uses  EEH_Line_Item::get_line_items_of_object_type()
1251
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1252
+	 * @return EE_Line_Item[]
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public static function get_ticket_line_items(EE_Line_Item $parent_line_item)
1256
+	{
1257
+		return self::get_line_items_of_object_type(
1258
+			$parent_line_item,
1259
+			EEM_Line_Item::OBJ_TYPE_TICKET
1260
+		);
1261
+	}
1262
+
1263
+
1264
+	/**
1265
+	 * Gets all descendants subtotals that match the supplied object type
1266
+	 *
1267
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1268
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1269
+	 * @param string       $obj_type
1270
+	 * @return EE_Line_Item[]
1271
+	 * @throws EE_Error
1272
+	 */
1273
+	public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '')
1274
+	{
1275
+		return self::_get_descendants_by_type_and_object_type(
1276
+			$parent_line_item,
1277
+			EEM_Line_Item::type_line_item,
1278
+			$obj_type
1279
+		);
1280
+	}
1281
+
1282
+
1283
+	/**
1284
+	 * Gets all the descendants (ie, children or children of children etc) that are of the type 'tax'
1285
+	 *
1286
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1287
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1288
+	 * @return EE_Line_Item[]
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public static function get_tax_descendants(EE_Line_Item $parent_line_item)
1292
+	{
1293
+		return EEH_Line_Item::get_descendants_of_type(
1294
+			$parent_line_item,
1295
+			EEM_Line_Item::type_tax
1296
+		);
1297
+	}
1298
+
1299
+
1300
+	/**
1301
+	 * Gets all the real items purchased which are children of this item
1302
+	 *
1303
+	 * @uses  EEH_Line_Item::get_descendants_of_type()
1304
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1305
+	 * @return EE_Line_Item[]
1306
+	 * @throws EE_Error
1307
+	 */
1308
+	public static function get_line_item_descendants(EE_Line_Item $parent_line_item)
1309
+	{
1310
+		return EEH_Line_Item::get_descendants_of_type(
1311
+			$parent_line_item,
1312
+			EEM_Line_Item::type_line_item
1313
+		);
1314
+	}
1315
+
1316
+
1317
+	/**
1318
+	 * Gets all descendants of supplied line item that match the supplied line item type
1319
+	 *
1320
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1321
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1322
+	 * @param string       $line_item_type   one of the EEM_Line_Item constants
1323
+	 * @return EE_Line_Item[]
1324
+	 * @throws EE_Error
1325
+	 */
1326
+	public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type)
1327
+	{
1328
+		return self::_get_descendants_by_type_and_object_type(
1329
+			$parent_line_item,
1330
+			$line_item_type,
1331
+			null
1332
+		);
1333
+	}
1334
+
1335
+
1336
+	/**
1337
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1338
+	 * as well
1339
+	 *
1340
+	 * @param EE_Line_Item  $parent_line_item - the line item to find descendants of
1341
+	 * @param string        $line_item_type   one of the EEM_Line_Item constants
1342
+	 * @param string | NULL $obj_type         object model class name (minus prefix) or NULL to ignore object type when
1343
+	 *                                        searching
1344
+	 * @return EE_Line_Item[]
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	protected static function _get_descendants_by_type_and_object_type(
1348
+		EE_Line_Item $parent_line_item,
1349
+		$line_item_type,
1350
+		$obj_type = null
1351
+	) {
1352
+		$objects = array();
1353
+		foreach ($parent_line_item->children() as $child_line_item) {
1354
+			if ($child_line_item instanceof EE_Line_Item) {
1355
+				if (
1356
+					$child_line_item->type() === $line_item_type
1357
+					&& (
1358
+						$child_line_item->OBJ_type() === $obj_type || $obj_type === null
1359
+					)
1360
+				) {
1361
+					$objects[] = $child_line_item;
1362
+				} else {
1363
+					// go-through-all-its children looking for more matches
1364
+					$objects = array_merge(
1365
+						$objects,
1366
+						self::_get_descendants_by_type_and_object_type(
1367
+							$child_line_item,
1368
+							$line_item_type,
1369
+							$obj_type
1370
+						)
1371
+					);
1372
+				}
1373
+			}
1374
+		}
1375
+		return $objects;
1376
+	}
1377
+
1378
+
1379
+	/**
1380
+	 * Gets all descendants subtotals that match the supplied object type
1381
+	 *
1382
+	 * @uses  EEH_Line_Item::_get_descendants_by_type_and_object_type()
1383
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1384
+	 * @param string       $OBJ_type         object type (like Event)
1385
+	 * @param array        $OBJ_IDs          array of OBJ_IDs
1386
+	 * @return EE_Line_Item[]
1387
+	 * @throws EE_Error
1388
+	 */
1389
+	public static function get_line_items_by_object_type_and_IDs(
1390
+		EE_Line_Item $parent_line_item,
1391
+		$OBJ_type = '',
1392
+		$OBJ_IDs = array()
1393
+	) {
1394
+		return self::_get_descendants_by_object_type_and_object_ID(
1395
+			$parent_line_item,
1396
+			$OBJ_type,
1397
+			$OBJ_IDs
1398
+		);
1399
+	}
1400
+
1401
+
1402
+	/**
1403
+	 * Gets all descendants of supplied line item that match the supplied line item type and possibly the object type
1404
+	 * as well
1405
+	 *
1406
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1407
+	 * @param string       $OBJ_type         object type (like Event)
1408
+	 * @param array        $OBJ_IDs          array of OBJ_IDs
1409
+	 * @return EE_Line_Item[]
1410
+	 * @throws EE_Error
1411
+	 */
1412
+	protected static function _get_descendants_by_object_type_and_object_ID(
1413
+		EE_Line_Item $parent_line_item,
1414
+		$OBJ_type,
1415
+		$OBJ_IDs
1416
+	) {
1417
+		$objects = array();
1418
+		foreach ($parent_line_item->children() as $child_line_item) {
1419
+			if ($child_line_item instanceof EE_Line_Item) {
1420
+				if (
1421
+					$child_line_item->OBJ_type() === $OBJ_type
1422
+					&& is_array($OBJ_IDs)
1423
+					&& in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1424
+				) {
1425
+					$objects[] = $child_line_item;
1426
+				} else {
1427
+					// go-through-all-its children looking for more matches
1428
+					$objects = array_merge(
1429
+						$objects,
1430
+						self::_get_descendants_by_object_type_and_object_ID(
1431
+							$child_line_item,
1432
+							$OBJ_type,
1433
+							$OBJ_IDs
1434
+						)
1435
+					);
1436
+				}
1437
+			}
1438
+		}
1439
+		return $objects;
1440
+	}
1441
+
1442
+
1443
+	/**
1444
+	 * Uses a breadth-first-search in order to find the nearest descendant of
1445
+	 * the specified type and returns it, else NULL
1446
+	 *
1447
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1448
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1449
+	 * @param string       $type             like one of the EEM_Line_Item::type_*
1450
+	 * @return EE_Line_Item
1451
+	 * @throws EE_Error
1452
+	 * @throws InvalidArgumentException
1453
+	 * @throws InvalidDataTypeException
1454
+	 * @throws InvalidInterfaceException
1455
+	 * @throws ReflectionException
1456
+	 */
1457
+	public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type)
1458
+	{
1459
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1460
+	}
1461
+
1462
+
1463
+	/**
1464
+	 * Uses a breadth-first-search in order to find the nearest descendant
1465
+	 * having the specified LIN_code and returns it, else NULL
1466
+	 *
1467
+	 * @uses  EEH_Line_Item::_get_nearest_descendant()
1468
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1469
+	 * @param string       $code             any value used for LIN_code
1470
+	 * @return EE_Line_Item
1471
+	 * @throws EE_Error
1472
+	 * @throws InvalidArgumentException
1473
+	 * @throws InvalidDataTypeException
1474
+	 * @throws InvalidInterfaceException
1475
+	 * @throws ReflectionException
1476
+	 */
1477
+	public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code)
1478
+	{
1479
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1480
+	}
1481
+
1482
+
1483
+	/**
1484
+	 * Uses a breadth-first-search in order to find the nearest descendant
1485
+	 * having the specified LIN_code and returns it, else NULL
1486
+	 *
1487
+	 * @param EE_Line_Item $parent_line_item - the line item to find descendants of
1488
+	 * @param string       $search_field     name of EE_Line_Item property
1489
+	 * @param string       $value            any value stored in $search_field
1490
+	 * @return EE_Line_Item
1491
+	 * @throws EE_Error
1492
+	 * @throws InvalidArgumentException
1493
+	 * @throws InvalidDataTypeException
1494
+	 * @throws InvalidInterfaceException
1495
+	 * @throws ReflectionException
1496
+	 */
1497
+	protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value)
1498
+	{
1499
+		foreach ($parent_line_item->children() as $child) {
1500
+			if ($child->get($search_field) == $value) {
1501
+				return $child;
1502
+			}
1503
+		}
1504
+		foreach ($parent_line_item->children() as $child) {
1505
+			$descendant_found = self::_get_nearest_descendant(
1506
+				$child,
1507
+				$search_field,
1508
+				$value
1509
+			);
1510
+			if ($descendant_found) {
1511
+				return $descendant_found;
1512
+			}
1513
+		}
1514
+		return null;
1515
+	}
1516
+
1517
+
1518
+	/**
1519
+	 * if passed line item has a TXN ID, uses that to jump directly to the grand total line item for the transaction,
1520
+	 * else recursively walks up the line item tree until a parent of type total is found,
1521
+	 *
1522
+	 * @param EE_Line_Item $line_item
1523
+	 * @return EE_Line_Item
1524
+	 * @throws EE_Error
1525
+	 */
1526
+	public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item)
1527
+	{
1528
+		if ($line_item->TXN_ID()) {
1529
+			$total_line_item = $line_item->transaction()->total_line_item(false);
1530
+			if ($total_line_item instanceof EE_Line_Item) {
1531
+				return $total_line_item;
1532
+			}
1533
+		} else {
1534
+			$line_item_parent = $line_item->parent();
1535
+			if ($line_item_parent instanceof EE_Line_Item) {
1536
+				if ($line_item_parent->is_total()) {
1537
+					return $line_item_parent;
1538
+				}
1539
+				return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1540
+			}
1541
+		}
1542
+		throw new EE_Error(
1543
+			sprintf(
1544
+				esc_html__(
1545
+					'A valid grand total for line item %1$d was not found.',
1546
+					'event_espresso'
1547
+				),
1548
+				$line_item->ID()
1549
+			)
1550
+		);
1551
+	}
1552
+
1553
+
1554
+	/**
1555
+	 * Prints out a representation of the line item tree
1556
+	 *
1557
+	 * @param EE_Line_Item $line_item
1558
+	 * @param int          $indentation
1559
+	 * @return void
1560
+	 * @throws EE_Error
1561
+	 */
1562
+	public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1563
+	{
1564
+		echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1565
+		if (! $indentation) {
1566
+			echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1567
+		}
1568
+		for ($i = 0; $i < $indentation; $i++) {
1569
+			echo '. ';
1570
+		}
1571
+		$breakdown = '';
1572
+		if ($line_item->is_line_item()) {
1573
+			if ($line_item->is_percent()) {
1574
+				$breakdown = "{$line_item->percent()}%";
1575
+			} else {
1576
+				$breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1577
+			}
1578
+		}
1579
+		echo $line_item->name();
1580
+		echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1581
+		echo '$' . (string) $line_item->total();
1582
+		if ($breakdown) {
1583
+			echo " ( {$breakdown} )";
1584
+		}
1585
+		if ($line_item->is_taxable()) {
1586
+			echo '  * taxable';
1587
+		}
1588
+		if ($line_item->children()) {
1589
+			foreach ($line_item->children() as $child) {
1590
+				self::visualize($child, $indentation + 1);
1591
+			}
1592
+		}
1593
+	}
1594
+
1595
+
1596
+	/**
1597
+	 * Calculates the registration's final price, taking into account that they
1598
+	 * need to not only help pay for their OWN ticket, but also any transaction-wide surcharges and taxes,
1599
+	 * and receive a portion of any transaction-wide discounts.
1600
+	 * eg1, if I buy a $1 ticket and brent buys a $9 ticket, and we receive a $5 discount
1601
+	 * then I'll get 1/10 of that $5 discount, which is $0.50, and brent will get
1602
+	 * 9/10ths of that $5 discount, which is $4.50. So my final price should be $0.50
1603
+	 * and brent's final price should be $5.50.
1604
+	 * In order to do this, we basically need to traverse the line item tree calculating
1605
+	 * the running totals (just as if we were recalculating the total), but when we identify
1606
+	 * regular line items, we need to keep track of their share of the grand total.
1607
+	 * Also, we need to keep track of the TAXABLE total for each ticket purchase, so
1608
+	 * we can know how to apply taxes to it. (Note: "taxable total" does not equal the "pretax total"
1609
+	 * when there are non-taxable items; otherwise they would be the same)
1610
+	 *
1611
+	 * @param EE_Line_Item $line_item
1612
+	 * @param array        $billable_ticket_quantities  array of EE_Ticket IDs and their corresponding quantity that
1613
+	 *                                                  can be included in price calculations at this moment
1614
+	 * @return array        keys are line items for tickets IDs and values are their share of the running total,
1615
+	 *                                                  plus the key 'total', and 'taxable' which also has keys of all
1616
+	 *                                                  the ticket IDs.
1617
+	 *                                                  Eg array(
1618
+	 *                                                      12 => 4.3
1619
+	 *                                                      23 => 8.0
1620
+	 *                                                      'total' => 16.6,
1621
+	 *                                                      'taxable' => array(
1622
+	 *                                                          12 => 10,
1623
+	 *                                                          23 => 4
1624
+	 *                                                      ).
1625
+	 *                                                  So to find which registrations have which final price, we need
1626
+	 *                                                  to find which line item is theirs, which can be done with
1627
+	 *                                                  `EEM_Line_Item::instance()->get_line_item_for_registration(
1628
+	 *                                                  $registration );`
1629
+	 * @throws EE_Error
1630
+	 * @throws InvalidArgumentException
1631
+	 * @throws InvalidDataTypeException
1632
+	 * @throws InvalidInterfaceException
1633
+	 * @throws ReflectionException
1634
+	 */
1635
+	public static function calculate_reg_final_prices_per_line_item(
1636
+		EE_Line_Item $line_item,
1637
+		$billable_ticket_quantities = array()
1638
+	) {
1639
+		$running_totals = [
1640
+			'total'   => 0,
1641
+			'taxable' => ['total' => 0]
1642
+		];
1643
+		foreach ($line_item->children() as $child_line_item) {
1644
+			switch ($child_line_item->type()) {
1645
+				case EEM_Line_Item::type_sub_total:
1646
+					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1647
+						$child_line_item,
1648
+						$billable_ticket_quantities
1649
+					);
1650
+					// combine arrays but preserve numeric keys
1651
+					$running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1652
+					$running_totals['total'] += $running_totals_from_subtotal['total'];
1653
+					$running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1654
+					break;
1655
+
1656
+				case EEM_Line_Item::type_tax_sub_total:
1657
+					// find how much the taxes percentage is
1658
+					if ($child_line_item->percent() !== 0) {
1659
+						$tax_percent_decimal = $child_line_item->percent() / 100;
1660
+					} else {
1661
+						$tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1662
+					}
1663
+					// and apply to all the taxable totals, and add to the pretax totals
1664
+					foreach ($running_totals as $line_item_id => $this_running_total) {
1665
+						// "total" and "taxable" array key is an exception
1666
+						if ($line_item_id === 'taxable') {
1667
+							continue;
1668
+						}
1669
+						$taxable_total = $running_totals['taxable'][ $line_item_id ];
1670
+						$running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1671
+					}
1672
+					break;
1673
+
1674
+				case EEM_Line_Item::type_line_item:
1675
+					// ticket line items or ????
1676
+					if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1677
+						// kk it's a ticket
1678
+						if (isset($running_totals[ $child_line_item->ID() ])) {
1679
+							// huh? that shouldn't happen.
1680
+							$running_totals['total'] += $child_line_item->total();
1681
+						} else {
1682
+							// its not in our running totals yet. great.
1683
+							if ($child_line_item->is_taxable()) {
1684
+								$taxable_amount = $child_line_item->unit_price();
1685
+							} else {
1686
+								$taxable_amount = 0;
1687
+							}
1688
+							// are we only calculating totals for some tickets?
1689
+							if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1690
+								$quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1691
+								$running_totals[ $child_line_item->ID() ] = $quantity
1692
+									? $child_line_item->unit_price()
1693
+									: 0;
1694
+								$running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1695
+									? $taxable_amount
1696
+									: 0;
1697
+							} else {
1698
+								$quantity = $child_line_item->quantity();
1699
+								$running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1700
+								$running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1701
+							}
1702
+							$running_totals['taxable']['total'] += $taxable_amount * $quantity;
1703
+							$running_totals['total'] += $child_line_item->unit_price() * $quantity;
1704
+						}
1705
+					} else {
1706
+						// it's some other type of item added to the cart
1707
+						// it should affect the running totals
1708
+						// basically we want to convert it into a PERCENT modifier. Because
1709
+						// more clearly affect all registration's final price equally
1710
+						$line_items_percent_of_running_total = $running_totals['total'] > 0
1711
+							? ($child_line_item->total() / $running_totals['total']) + 1
1712
+							: 1;
1713
+						foreach ($running_totals as $line_item_id => $this_running_total) {
1714
+							// the "taxable" array key is an exception
1715
+							if ($line_item_id === 'taxable') {
1716
+								continue;
1717
+							}
1718
+							// update the running totals
1719
+							// yes this actually even works for the running grand total!
1720
+							$running_totals[ $line_item_id ] =
1721
+								$line_items_percent_of_running_total * $this_running_total;
1722
+
1723
+							if ($child_line_item->is_taxable()) {
1724
+								$running_totals['taxable'][ $line_item_id ] =
1725
+									$line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1726
+							}
1727
+						}
1728
+					}
1729
+					break;
1730
+			}
1731
+		}
1732
+		return $running_totals;
1733
+	}
1734
+
1735
+
1736
+	/**
1737
+	 * @param EE_Line_Item $total_line_item
1738
+	 * @param EE_Line_Item $ticket_line_item
1739
+	 * @return float | null
1740
+	 * @throws EE_Error
1741
+	 * @throws InvalidArgumentException
1742
+	 * @throws InvalidDataTypeException
1743
+	 * @throws InvalidInterfaceException
1744
+	 * @throws OutOfRangeException
1745
+	 * @throws ReflectionException
1746
+	 */
1747
+	public static function calculate_final_price_for_ticket_line_item(
1748
+		EE_Line_Item $total_line_item,
1749
+		EE_Line_Item $ticket_line_item
1750
+	) {
1751
+		static $final_prices_per_ticket_line_item = array();
1752
+		if (empty($final_prices_per_ticket_line_item) || empty($final_prices_per_ticket_line_item[ $total_line_item->ID() ])) {
1753
+			$final_prices_per_ticket_line_item[ $total_line_item->ID() ] = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1754
+				$total_line_item
1755
+			);
1756
+		}
1757
+		// ok now find this new registration's final price
1758
+		if (isset($final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ])) {
1759
+			return $final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ];
1760
+		}
1761
+		$message = sprintf(
1762
+			esc_html__(
1763
+				'The final price for the ticket line item (ID:%1$d) could not be calculated.',
1764
+				'event_espresso'
1765
+			),
1766
+			$ticket_line_item->ID()
1767
+		);
1768
+		if (WP_DEBUG) {
1769
+			$message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1770
+			throw new OutOfRangeException($message);
1771
+		}
1772
+		EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1773
+		return null;
1774
+	}
1775
+
1776
+
1777
+	/**
1778
+	 * Creates a duplicate of the line item tree, except only includes billable items
1779
+	 * and the portion of line items attributed to billable things
1780
+	 *
1781
+	 * @param EE_Line_Item      $line_item
1782
+	 * @param EE_Registration[] $registrations
1783
+	 * @return EE_Line_Item
1784
+	 * @throws EE_Error
1785
+	 * @throws InvalidArgumentException
1786
+	 * @throws InvalidDataTypeException
1787
+	 * @throws InvalidInterfaceException
1788
+	 * @throws ReflectionException
1789
+	 */
1790
+	public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations)
1791
+	{
1792
+		$copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1793
+		foreach ($line_item->children() as $child_li) {
1794
+			$copy_li->add_child_line_item(
1795
+				EEH_Line_Item::billable_line_item_tree($child_li, $registrations)
1796
+			);
1797
+		}
1798
+		// if this is the grand total line item, make sure the totals all add up
1799
+		// (we could have duplicated this logic AS we copied the line items, but
1800
+		// it seems DRYer this way)
1801
+		if ($copy_li->type() === EEM_Line_Item::type_total) {
1802
+			$copy_li->recalculate_total_including_taxes();
1803
+		}
1804
+		return $copy_li;
1805
+	}
1806
+
1807
+
1808
+	/**
1809
+	 * Creates a new, unsaved line item from $line_item that factors in the
1810
+	 * number of billable registrations on $registrations.
1811
+	 *
1812
+	 * @param EE_Line_Item      $line_item
1813
+	 * @param EE_Registration[] $registrations
1814
+	 * @return EE_Line_Item
1815
+	 * @throws EE_Error
1816
+	 * @throws InvalidArgumentException
1817
+	 * @throws InvalidDataTypeException
1818
+	 * @throws InvalidInterfaceException
1819
+	 * @throws ReflectionException
1820
+	 */
1821
+	public static function billable_line_item(EE_Line_Item $line_item, $registrations)
1822
+	{
1823
+		$new_li_fields = $line_item->model_field_array();
1824
+		if (
1825
+			$line_item->type() === EEM_Line_Item::type_line_item &&
1826
+			$line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1827
+		) {
1828
+			$count = 0;
1829
+			foreach ($registrations as $registration) {
1830
+				if (
1831
+					$line_item->OBJ_ID() === $registration->ticket_ID() &&
1832
+					in_array(
1833
+						$registration->status_ID(),
1834
+						EEM_Registration::reg_statuses_that_allow_payment(),
1835
+						true
1836
+					)
1837
+				) {
1838
+					$count++;
1839
+				}
1840
+			}
1841
+			$new_li_fields['LIN_quantity'] = $count;
1842
+		}
1843
+		// don't set the total. We'll leave that up to the code that calculates it
1844
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1845
+		return EE_Line_Item::new_instance($new_li_fields);
1846
+	}
1847
+
1848
+
1849
+	/**
1850
+	 * Returns a modified line item tree where all the subtotals which have a total of 0
1851
+	 * are removed, and line items with a quantity of 0
1852
+	 *
1853
+	 * @param EE_Line_Item $line_item |null
1854
+	 * @return EE_Line_Item|null
1855
+	 * @throws EE_Error
1856
+	 * @throws InvalidArgumentException
1857
+	 * @throws InvalidDataTypeException
1858
+	 * @throws InvalidInterfaceException
1859
+	 * @throws ReflectionException
1860
+	 */
1861
+	public static function non_empty_line_items(EE_Line_Item $line_item)
1862
+	{
1863
+		$copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1864
+		if ($copied_li === null) {
1865
+			return null;
1866
+		}
1867
+		// if this is an event subtotal, we want to only include it if it
1868
+		// has a non-zero total and at least one ticket line item child
1869
+		$ticket_children = 0;
1870
+		foreach ($line_item->children() as $child_li) {
1871
+			$child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1872
+			if ($child_li_copy !== null) {
1873
+				$copied_li->add_child_line_item($child_li_copy);
1874
+				if (
1875
+					$child_li_copy->type() === EEM_Line_Item::type_line_item &&
1876
+					$child_li_copy->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1877
+				) {
1878
+					$ticket_children++;
1879
+				}
1880
+			}
1881
+		}
1882
+		// if this is an event subtotal with NO ticket children
1883
+		// we basically want to ignore it
1884
+		if (
1885
+			$ticket_children === 0
1886
+			&& $line_item->type() === EEM_Line_Item::type_sub_total
1887
+			&& $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_EVENT
1888
+			&& $line_item->total() === 0
1889
+		) {
1890
+			return null;
1891
+		}
1892
+		return $copied_li;
1893
+	}
1894
+
1895
+
1896
+	/**
1897
+	 * Creates a new, unsaved line item, but if it's a ticket line item
1898
+	 * with a total of 0, or a subtotal of 0, returns null instead
1899
+	 *
1900
+	 * @param EE_Line_Item $line_item
1901
+	 * @return EE_Line_Item
1902
+	 * @throws EE_Error
1903
+	 * @throws InvalidArgumentException
1904
+	 * @throws InvalidDataTypeException
1905
+	 * @throws InvalidInterfaceException
1906
+	 * @throws ReflectionException
1907
+	 */
1908
+	public static function non_empty_line_item(EE_Line_Item $line_item)
1909
+	{
1910
+		if (
1911
+			$line_item->type() === EEM_Line_Item::type_line_item
1912
+			&& $line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1913
+			&& $line_item->quantity() === 0
1914
+		) {
1915
+			return null;
1916
+		}
1917
+		$new_li_fields = $line_item->model_field_array();
1918
+		// don't set the total. We'll leave that up to the code that calculates it
1919
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1920
+		return EE_Line_Item::new_instance($new_li_fields);
1921
+	}
1922
+
1923
+
1924
+	/**
1925
+	 * Cycles through all of the ticket line items for the supplied total line item
1926
+	 * and ensures that the line item's "is_taxable" field matches that of its corresponding ticket
1927
+	 *
1928
+	 * @param EE_Line_Item $total_line_item
1929
+	 * @since 4.9.79.p
1930
+	 * @throws EE_Error
1931
+	 * @throws InvalidArgumentException
1932
+	 * @throws InvalidDataTypeException
1933
+	 * @throws InvalidInterfaceException
1934
+	 * @throws ReflectionException
1935
+	 */
1936
+	public static function resetIsTaxableForTickets(EE_Line_Item $total_line_item)
1937
+	{
1938
+		$ticket_line_items = self::get_ticket_line_items($total_line_item);
1939
+		foreach ($ticket_line_items as $ticket_line_item) {
1940
+			if (
1941
+				$ticket_line_item instanceof EE_Line_Item
1942
+				&& $ticket_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET
1943
+			) {
1944
+				$ticket = $ticket_line_item->ticket();
1945
+				if ($ticket instanceof EE_Ticket && $ticket->taxable() !== $ticket_line_item->is_taxable()) {
1946
+					$ticket_line_item->set_is_taxable($ticket->taxable());
1947
+					$ticket_line_item->save();
1948
+				}
1949
+			}
1950
+		}
1951
+	}
1952
+
1953
+
1954
+
1955
+	/**************************************** @DEPRECATED METHODS *************************************** */
1956
+	/**
1957
+	 * @deprecated
1958
+	 * @param EE_Line_Item $total_line_item
1959
+	 * @return EE_Line_Item
1960
+	 * @throws EE_Error
1961
+	 * @throws InvalidArgumentException
1962
+	 * @throws InvalidDataTypeException
1963
+	 * @throws InvalidInterfaceException
1964
+	 * @throws ReflectionException
1965
+	 */
1966
+	public static function get_items_subtotal(EE_Line_Item $total_line_item)
1967
+	{
1968
+		EE_Error::doing_it_wrong(
1969
+			'EEH_Line_Item::get_items_subtotal()',
1970
+			sprintf(
1971
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1972
+				'EEH_Line_Item::get_pre_tax_subtotal()'
1973
+			),
1974
+			'4.6.0'
1975
+		);
1976
+		return self::get_pre_tax_subtotal($total_line_item);
1977
+	}
1978
+
1979
+
1980
+	/**
1981
+	 * @deprecated
1982
+	 * @param EE_Transaction $transaction
1983
+	 * @return EE_Line_Item
1984
+	 * @throws EE_Error
1985
+	 * @throws InvalidArgumentException
1986
+	 * @throws InvalidDataTypeException
1987
+	 * @throws InvalidInterfaceException
1988
+	 * @throws ReflectionException
1989
+	 */
1990
+	public static function create_default_total_line_item($transaction = null)
1991
+	{
1992
+		EE_Error::doing_it_wrong(
1993
+			'EEH_Line_Item::create_default_total_line_item()',
1994
+			sprintf(
1995
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
1996
+				'EEH_Line_Item::create_total_line_item()'
1997
+			),
1998
+			'4.6.0'
1999
+		);
2000
+		return self::create_total_line_item($transaction);
2001
+	}
2002
+
2003
+
2004
+	/**
2005
+	 * @deprecated
2006
+	 * @param EE_Line_Item   $total_line_item
2007
+	 * @param EE_Transaction $transaction
2008
+	 * @return EE_Line_Item
2009
+	 * @throws EE_Error
2010
+	 * @throws InvalidArgumentException
2011
+	 * @throws InvalidDataTypeException
2012
+	 * @throws InvalidInterfaceException
2013
+	 * @throws ReflectionException
2014
+	 */
2015
+	public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2016
+	{
2017
+		EE_Error::doing_it_wrong(
2018
+			'EEH_Line_Item::create_default_tickets_subtotal()',
2019
+			sprintf(
2020
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2021
+				'EEH_Line_Item::create_pre_tax_subtotal()'
2022
+			),
2023
+			'4.6.0'
2024
+		);
2025
+		return self::create_pre_tax_subtotal($total_line_item, $transaction);
2026
+	}
2027
+
2028
+
2029
+	/**
2030
+	 * @deprecated
2031
+	 * @param EE_Line_Item   $total_line_item
2032
+	 * @param EE_Transaction $transaction
2033
+	 * @return EE_Line_Item
2034
+	 * @throws EE_Error
2035
+	 * @throws InvalidArgumentException
2036
+	 * @throws InvalidDataTypeException
2037
+	 * @throws InvalidInterfaceException
2038
+	 * @throws ReflectionException
2039
+	 */
2040
+	public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2041
+	{
2042
+		EE_Error::doing_it_wrong(
2043
+			'EEH_Line_Item::create_default_taxes_subtotal()',
2044
+			sprintf(
2045
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2046
+				'EEH_Line_Item::create_taxes_subtotal()'
2047
+			),
2048
+			'4.6.0'
2049
+		);
2050
+		return self::create_taxes_subtotal($total_line_item, $transaction);
2051
+	}
2052
+
2053
+
2054
+	/**
2055
+	 * @deprecated
2056
+	 * @param EE_Line_Item   $total_line_item
2057
+	 * @param EE_Transaction $transaction
2058
+	 * @return EE_Line_Item
2059
+	 * @throws EE_Error
2060
+	 * @throws InvalidArgumentException
2061
+	 * @throws InvalidDataTypeException
2062
+	 * @throws InvalidInterfaceException
2063
+	 * @throws ReflectionException
2064
+	 */
2065
+	public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = null)
2066
+	{
2067
+		EE_Error::doing_it_wrong(
2068
+			'EEH_Line_Item::create_default_event_subtotal()',
2069
+			sprintf(
2070
+				esc_html__('Method replaced with %1$s', 'event_espresso'),
2071
+				'EEH_Line_Item::create_event_subtotal()'
2072
+			),
2073
+			'4.6.0'
2074
+		);
2075
+		return self::create_event_subtotal($total_line_item, $transaction);
2076
+	}
2077 2077
 }
Please login to merge, or discard this patch.
Spacing   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
      */
139 139
     public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1)
140 140
     {
141
-        if (! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
141
+        if ( ! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
142 142
             throw new EE_Error(
143 143
                 sprintf(
144 144
                     esc_html__(
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
         // either increment the qty for an existing ticket
154 154
         $line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
155 155
         // or add a new one
156
-        if (! $line_item instanceof EE_Line_Item) {
156
+        if ( ! $line_item instanceof EE_Line_Item) {
157 157
             $line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
158 158
         }
159 159
         $total_line_item->recalculate_total_including_taxes();
@@ -215,7 +215,7 @@  discard block
 block discarded – undo
215 215
      */
216 216
     public static function increment_quantity(EE_Line_Item $line_item, $qty = 1)
217 217
     {
218
-        if (! $line_item->is_percent()) {
218
+        if ( ! $line_item->is_percent()) {
219 219
             $qty += $line_item->quantity();
220 220
             $line_item->set_quantity($qty);
221 221
             $line_item->set_total($line_item->unit_price() * $qty);
@@ -244,7 +244,7 @@  discard block
 block discarded – undo
244 244
      */
245 245
     public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1)
246 246
     {
247
-        if (! $line_item->is_percent()) {
247
+        if ( ! $line_item->is_percent()) {
248 248
             $qty = $line_item->quantity() - $qty;
249 249
             $qty = max($qty, 0);
250 250
             $line_item->set_quantity($qty);
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
      */
274 274
     public static function update_quantity(EE_Line_Item $line_item, $new_quantity)
275 275
     {
276
-        if (! $line_item->is_percent()) {
276
+        if ( ! $line_item->is_percent()) {
277 277
             $line_item->set_quantity($new_quantity);
278 278
             $line_item->set_total($line_item->unit_price() * $new_quantity);
279 279
             $line_item->save();
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
         // add $ticket to cart
314 314
         $line_item = EE_Line_Item::new_instance(array(
315 315
             'LIN_name'       => $ticket->name(),
316
-            'LIN_desc'       => $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
316
+            'LIN_desc'       => $ticket->description() !== '' ? $ticket->description().' '.$event : $event,
317 317
             'LIN_unit_price' => $ticket->price(),
318 318
             'LIN_quantity'   => $qty,
319 319
             'LIN_is_taxable' => $ticket->taxable(),
@@ -464,7 +464,7 @@  discard block
 block discarded – undo
464 464
                         'event_espresso'
465 465
                     ),
466 466
                     $ticket_line_item->name(),
467
-                    current_time(get_option('date_format') . ' ' . get_option('time_format'))
467
+                    current_time(get_option('date_format').' '.get_option('time_format'))
468 468
                 ),
469 469
                 'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
470 470
                 'LIN_quantity'   => $qty,
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
         );
528 528
         $cancellation_line_item = reset($cancellation_line_item);
529 529
         // verify that this ticket was indeed previously cancelled
530
-        if (! $cancellation_line_item instanceof EE_Line_Item) {
530
+        if ( ! $cancellation_line_item instanceof EE_Line_Item) {
531 531
             return false;
532 532
         }
533 533
         if ($cancellation_line_item->quantity() > $qty) {
@@ -733,7 +733,7 @@  discard block
 block discarded – undo
733 733
             'LIN_code'  => 'taxes',
734 734
             'LIN_name'  => esc_html__('Taxes', 'event_espresso'),
735 735
             'LIN_type'  => EEM_Line_Item::type_tax_sub_total,
736
-            'LIN_order' => 1000,// this should always come last
736
+            'LIN_order' => 1000, // this should always come last
737 737
         ));
738 738
         $tax_line_item = apply_filters(
739 739
             'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
@@ -789,7 +789,7 @@  discard block
 block discarded – undo
789 789
      */
790 790
     public static function get_event_code($event)
791 791
     {
792
-        return 'event-' . ($event instanceof EE_Event ? $event->ID() : '0');
792
+        return 'event-'.($event instanceof EE_Event ? $event->ID() : '0');
793 793
     }
794 794
 
795 795
 
@@ -838,7 +838,7 @@  discard block
 block discarded – undo
838 838
     public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket)
839 839
     {
840 840
         $first_datetime = $ticket->first_datetime();
841
-        if (! $first_datetime instanceof EE_Datetime) {
841
+        if ( ! $first_datetime instanceof EE_Datetime) {
842 842
             throw new EE_Error(
843 843
                 sprintf(
844 844
                     esc_html__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'),
@@ -847,7 +847,7 @@  discard block
 block discarded – undo
847 847
             );
848 848
         }
849 849
         $event = $first_datetime->event();
850
-        if (! $event instanceof EE_Event) {
850
+        if ( ! $event instanceof EE_Event) {
851 851
             throw new EE_Error(
852 852
                 sprintf(
853 853
                     esc_html__(
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
             );
860 860
         }
861 861
         $events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
862
-        if (! $events_sub_total instanceof EE_Line_Item) {
862
+        if ( ! $events_sub_total instanceof EE_Line_Item) {
863 863
             throw new EE_Error(
864 864
                 sprintf(
865 865
                     esc_html__(
@@ -895,7 +895,7 @@  discard block
 block discarded – undo
895 895
         $found = false;
896 896
         foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
897 897
             // default event subtotal, we should only ever find this the first time this method is called
898
-            if (! $event_line_item->OBJ_ID()) {
898
+            if ( ! $event_line_item->OBJ_ID()) {
899 899
                 // let's use this! but first... set the event details
900 900
                 EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
901 901
                 $found = true;
@@ -907,7 +907,7 @@  discard block
 block discarded – undo
907 907
                 break;
908 908
             }
909 909
         }
910
-        if (! $found) {
910
+        if ( ! $found) {
911 911
             // there is no event sub-total yet, so add it
912 912
             $pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
913 913
             // create a new "event" subtotal below that
@@ -1024,7 +1024,7 @@  discard block
 block discarded – undo
1024 1024
     public static function ensure_taxes_applied($total_line_item)
1025 1025
     {
1026 1026
         $taxes_subtotal = self::get_taxes_subtotal($total_line_item);
1027
-        if (! $taxes_subtotal->children()) {
1027
+        if ( ! $taxes_subtotal->children()) {
1028 1028
             self::apply_taxes($total_line_item);
1029 1029
         }
1030 1030
         return $taxes_subtotal->total();
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1092 1092
 
1093 1093
         // check if only a single line_item_id was passed
1094
-        if (! empty($line_item_codes) && ! is_array($line_item_codes)) {
1094
+        if ( ! empty($line_item_codes) && ! is_array($line_item_codes)) {
1095 1095
             // place single line_item_id in an array to appear as multiple line_item_ids
1096 1096
             $line_item_codes = array($line_item_codes);
1097 1097
         }
@@ -1198,7 +1198,7 @@  discard block
 block discarded – undo
1198 1198
         if ($code_substring_for_whitelist !== null) {
1199 1199
             $whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false;
1200 1200
         }
1201
-        if (! $whitelisted && $line_item->is_line_item()) {
1201
+        if ( ! $whitelisted && $line_item->is_line_item()) {
1202 1202
             $line_item->set_is_taxable($taxable);
1203 1203
         }
1204 1204
         foreach ($line_item->children() as $child_line_item) {
@@ -1562,7 +1562,7 @@  discard block
 block discarded – undo
1562 1562
     public static function visualize(EE_Line_Item $line_item, $indentation = 0)
1563 1563
     {
1564 1564
         echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1565
-        if (! $indentation) {
1565
+        if ( ! $indentation) {
1566 1566
             echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1567 1567
         }
1568 1568
         for ($i = 0; $i < $indentation; $i++) {
@@ -1573,12 +1573,12 @@  discard block
 block discarded – undo
1573 1573
             if ($line_item->is_percent()) {
1574 1574
                 $breakdown = "{$line_item->percent()}%";
1575 1575
             } else {
1576
-                $breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1576
+                $breakdown = '$'."{$line_item->unit_price()} x {$line_item->quantity()}";
1577 1577
             }
1578 1578
         }
1579 1579
         echo $line_item->name();
1580 1580
         echo " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ";
1581
-        echo '$' . (string) $line_item->total();
1581
+        echo '$'.(string) $line_item->total();
1582 1582
         if ($breakdown) {
1583 1583
             echo " ( {$breakdown} )";
1584 1584
         }
@@ -1666,8 +1666,8 @@  discard block
 block discarded – undo
1666 1666
                         if ($line_item_id === 'taxable') {
1667 1667
                             continue;
1668 1668
                         }
1669
-                        $taxable_total = $running_totals['taxable'][ $line_item_id ];
1670
-                        $running_totals[ $line_item_id ] += ($taxable_total * $tax_percent_decimal);
1669
+                        $taxable_total = $running_totals['taxable'][$line_item_id];
1670
+                        $running_totals[$line_item_id] += ($taxable_total * $tax_percent_decimal);
1671 1671
                     }
1672 1672
                     break;
1673 1673
 
@@ -1675,7 +1675,7 @@  discard block
 block discarded – undo
1675 1675
                     // ticket line items or ????
1676 1676
                     if ($child_line_item->OBJ_type() === EEM_Line_Item::OBJ_TYPE_TICKET) {
1677 1677
                         // kk it's a ticket
1678
-                        if (isset($running_totals[ $child_line_item->ID() ])) {
1678
+                        if (isset($running_totals[$child_line_item->ID()])) {
1679 1679
                             // huh? that shouldn't happen.
1680 1680
                             $running_totals['total'] += $child_line_item->total();
1681 1681
                         } else {
@@ -1686,18 +1686,18 @@  discard block
 block discarded – undo
1686 1686
                                 $taxable_amount = 0;
1687 1687
                             }
1688 1688
                             // are we only calculating totals for some tickets?
1689
-                            if (isset($billable_ticket_quantities[ $child_line_item->OBJ_ID() ])) {
1690
-                                $quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1691
-                                $running_totals[ $child_line_item->ID() ] = $quantity
1689
+                            if (isset($billable_ticket_quantities[$child_line_item->OBJ_ID()])) {
1690
+                                $quantity = $billable_ticket_quantities[$child_line_item->OBJ_ID()];
1691
+                                $running_totals[$child_line_item->ID()] = $quantity
1692 1692
                                     ? $child_line_item->unit_price()
1693 1693
                                     : 0;
1694
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $quantity
1694
+                                $running_totals['taxable'][$child_line_item->ID()] = $quantity
1695 1695
                                     ? $taxable_amount
1696 1696
                                     : 0;
1697 1697
                             } else {
1698 1698
                                 $quantity = $child_line_item->quantity();
1699
-                                $running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1700
-                                $running_totals['taxable'][ $child_line_item->ID() ] = $taxable_amount;
1699
+                                $running_totals[$child_line_item->ID()] = $child_line_item->unit_price();
1700
+                                $running_totals['taxable'][$child_line_item->ID()] = $taxable_amount;
1701 1701
                             }
1702 1702
                             $running_totals['taxable']['total'] += $taxable_amount * $quantity;
1703 1703
                             $running_totals['total'] += $child_line_item->unit_price() * $quantity;
@@ -1717,12 +1717,12 @@  discard block
 block discarded – undo
1717 1717
                             }
1718 1718
                             // update the running totals
1719 1719
                             // yes this actually even works for the running grand total!
1720
-                            $running_totals[ $line_item_id ] =
1720
+                            $running_totals[$line_item_id] =
1721 1721
                                 $line_items_percent_of_running_total * $this_running_total;
1722 1722
 
1723 1723
                             if ($child_line_item->is_taxable()) {
1724
-                                $running_totals['taxable'][ $line_item_id ] =
1725
-                                    $line_items_percent_of_running_total * $running_totals['taxable'][ $line_item_id ];
1724
+                                $running_totals['taxable'][$line_item_id] =
1725
+                                    $line_items_percent_of_running_total * $running_totals['taxable'][$line_item_id];
1726 1726
                             }
1727 1727
                         }
1728 1728
                     }
@@ -1749,14 +1749,14 @@  discard block
 block discarded – undo
1749 1749
         EE_Line_Item $ticket_line_item
1750 1750
     ) {
1751 1751
         static $final_prices_per_ticket_line_item = array();
1752
-        if (empty($final_prices_per_ticket_line_item) || empty($final_prices_per_ticket_line_item[ $total_line_item->ID() ])) {
1753
-            $final_prices_per_ticket_line_item[ $total_line_item->ID() ] = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1752
+        if (empty($final_prices_per_ticket_line_item) || empty($final_prices_per_ticket_line_item[$total_line_item->ID()])) {
1753
+            $final_prices_per_ticket_line_item[$total_line_item->ID()] = EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1754 1754
                 $total_line_item
1755 1755
             );
1756 1756
         }
1757 1757
         // ok now find this new registration's final price
1758
-        if (isset($final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ])) {
1759
-            return $final_prices_per_ticket_line_item[ $total_line_item->ID() ][ $ticket_line_item->ID() ];
1758
+        if (isset($final_prices_per_ticket_line_item[$total_line_item->ID()][$ticket_line_item->ID()])) {
1759
+            return $final_prices_per_ticket_line_item[$total_line_item->ID()][$ticket_line_item->ID()];
1760 1760
         }
1761 1761
         $message = sprintf(
1762 1762
             esc_html__(
@@ -1766,7 +1766,7 @@  discard block
 block discarded – undo
1766 1766
             $ticket_line_item->ID()
1767 1767
         );
1768 1768
         if (WP_DEBUG) {
1769
-            $message .= '<br>' . print_r($final_prices_per_ticket_line_item, true);
1769
+            $message .= '<br>'.print_r($final_prices_per_ticket_line_item, true);
1770 1770
             throw new OutOfRangeException($message);
1771 1771
         }
1772 1772
         EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
Please login to merge, or discard this patch.