Completed
Branch BUG/escape-localized-variables (d40cc7)
by
unknown
09:56 queued 08:24
created
core/libraries/messages/EE_Message_Resource_Manager.lib.php 2 patches
Indentation   +1115 added lines, -1115 removed lines patch added patch discarded remove patch
@@ -12,1119 +12,1119 @@
 block discarded – undo
12 12
 class EE_Message_Resource_Manager
13 13
 {
14 14
 
15
-    /**
16
-     * This option in the database is used to keep a record of message types that have been activated for a messenger
17
-     * at some point in the history of the site.  It is utilized by the implementation of the 'force' flag in
18
-     * EE_Register_Message_Type.  The force flag is an indication of whether a message type should be activated by
19
-     * default when the message type is registered.  However, if a user has explicitly deactivated a message type, then
20
-     * the force flag is ignored.  The method by which the code knows whether to ignore this flag is via this option.
21
-     * Note, that this is NOT a historical record.  Its entirely possible for a message type to have been activated for
22
-     * a messenger and yet not have a record in this option.  This occurs when a message type is inactivated through an
23
-     * automated process (when an add-on registering the message type deactivates, or when some other code calls the
24
-     * EE_Registery_Message_Type::deregister method) and the related record(s) is(are) removed from this option to ensure
25
-     * the "force" flag is respected if that message type is later re-registered.
26
-     *
27
-     * This option should NOT be used to determine the current "active" state of a message type for a given messenger.
28
-     *
29
-     * The name of this option (and related methods/properties) is due to matching the original intended purpose for the
30
-     * option that got superseded by later behaviour requirements.
31
-     */
32
-    const HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME = 'ee_has_activated_messenger';
33
-
34
-    /**
35
-     * @type boolean $_initialized
36
-     */
37
-    protected $_initialized = false;
38
-
39
-    /**
40
-     * @type EE_Messenger_Collection $_messenger_collection_loader
41
-     */
42
-    protected $_messenger_collection_loader;
43
-
44
-    /**
45
-     * @type EE_Message_Type_Collection $_message_type_collection_loader
46
-     */
47
-    protected $_message_type_collection_loader;
48
-
49
-    /**
50
-     * @type EEM_Message_Template_Group $_message_template_group_model
51
-     */
52
-    protected $_message_template_group_model;
53
-
54
-    /**
55
-     * @type EE_messenger[]
56
-     */
57
-    protected $_installed_messengers = array();
58
-
59
-    /**
60
-     * @type EE_message_type[]
61
-     */
62
-    protected $_installed_message_types = array();
63
-
64
-    /**
65
-     * Array of active messengers.
66
-     * Format is this:
67
-     * array(
68
-     *      'messenger_name' => EE_messenger
69
-     * )
70
-     *
71
-     * @type EE_messenger[]
72
-     */
73
-    protected $_active_messengers = array();
74
-
75
-    /**
76
-     * Formatted array of active message types grouped per messenger.
77
-     * Format is this:
78
-     * array(
79
-     *      'messenger_name' => array(
80
-     *          'settings' => array(
81
-     *              '{messenger_name}-message_types' => array(
82
-     *                  'message_type_name' => array() //variable array of settings corresponding to message type.
83
-     *              )
84
-     *          )
85
-     *      )
86
-     * )
87
-     *
88
-     * @type array
89
-     */
90
-    protected $_active_message_types = array();
91
-
92
-
93
-    /**
94
-     * This holds the array of messengers and their corresponding message types that have
95
-     * been activated on a site at some point.  This is an important record that helps the messages system
96
-     * not accidentally reactivate something that was intentionally deactivated by a user.
97
-     *
98
-     * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
99
-     *
100
-     * @type array
101
-     */
102
-    protected $_has_activated_messengers_and_message_types = array();
103
-
104
-    /**
105
-     * An array of unique message type contexts across all active message types.
106
-     * The array will be indexed by either 'slugs' or 'all'.
107
-     * The slugs index contains an array indexed by unique context slugs with the latest label representation for that
108
-     * slug. array(
109
-     *      'context_slug' => 'localized label for context obtained from latest message type in the loop'.
110
-     * );
111
-     * The all index returns an array in this format:
112
-     * array(
113
-     *      'message_type_name' => array(
114
-     *          'context_slug' => array(
115
-     *              'label' => 'localized label for context',
116
-     *              'description' => 'localized description for context'
117
-     *          )
118
-     *      )
119
-     * );
120
-     *
121
-     * @type array
122
-     */
123
-    protected $_contexts = array();
124
-
125
-
126
-    /**
127
-     * EE_Message_Resource_Manager constructor.
128
-     *
129
-     * @param \EE_Messenger_Collection_Loader    $Messenger_Collection_Loader
130
-     * @param \EE_Message_Type_Collection_Loader $Message_Type_Collection_Loader
131
-     * @param \EEM_Message_Template_Group        $Message_Template_Group_Model
132
-     */
133
-    public function __construct(
134
-        EE_Messenger_Collection_Loader $Messenger_Collection_Loader,
135
-        EE_Message_Type_Collection_Loader $Message_Type_Collection_Loader,
136
-        EEM_Message_Template_Group $Message_Template_Group_Model
137
-    ) {
138
-        $this->_messenger_collection_loader    = $Messenger_Collection_Loader;
139
-        $this->_message_type_collection_loader = $Message_Type_Collection_Loader;
140
-        $this->_message_template_group_model   = $Message_Template_Group_Model;
141
-    }
142
-
143
-
144
-    /**
145
-     * @return void
146
-     */
147
-    protected function _initialize_collections()
148
-    {
149
-        if ($this->_initialized) {
150
-            return;
151
-        }
152
-        $this->_initialized = true;
153
-        $this->_messenger_collection_loader->load_messengers_from_folder();
154
-        $this->_message_type_collection_loader->load_message_types_from_folder();
155
-        $this->get_has_activated_messengers_option(true);
156
-        $this->_set_active_messengers_and_message_types();
157
-    }
158
-
159
-
160
-    /**
161
-     * @return EE_Messenger_Collection
162
-     */
163
-    public function messenger_collection()
164
-    {
165
-        $this->_initialize_collections();
166
-        return $this->_messenger_collection_loader->messenger_collection();
167
-    }
168
-
169
-
170
-    /**
171
-     * @return EE_messenger[]
172
-     */
173
-    public function active_messengers()
174
-    {
175
-        $this->_initialize_collections();
176
-        return $this->_active_messengers;
177
-    }
178
-
179
-
180
-    /**
181
-     * @param string $messenger_name
182
-     * @return \EE_messenger
183
-     */
184
-    public function get_messenger($messenger_name)
185
-    {
186
-        return $this->messenger_collection()->get_by_info($messenger_name);
187
-    }
188
-
189
-
190
-    /**
191
-     * This returns the corresponding EE_messenger object for the given string if it is active.
192
-     *
193
-     * @param string $messenger
194
-     * @return EE_messenger | null
195
-     */
196
-    public function get_active_messenger($messenger)
197
-    {
198
-        $this->_initialize_collections();
199
-        return ! empty($this->_active_messengers[ $messenger ]) ? $this->_active_messengers[ $messenger ] : null;
200
-    }
201
-
202
-
203
-    /**
204
-     * @return \EE_messenger[]
205
-     */
206
-    public function installed_messengers()
207
-    {
208
-        if (empty($this->_installed_messengers)) {
209
-            $this->_installed_messengers = array();
210
-            $this->messenger_collection()->rewind();
211
-            while ($this->messenger_collection()->valid()) {
212
-                $this->_installed_messengers[ $this->messenger_collection()->current()->name ] = $this->messenger_collection()->current();
213
-                $this->messenger_collection()->next();
214
-            }
215
-        }
216
-        return $this->_installed_messengers;
217
-    }
218
-
219
-
220
-    /**
221
-     * @param string $messenger_name
222
-     * @return \EE_messenger
223
-     * @throws EE_Error
224
-     */
225
-    public function valid_messenger($messenger_name)
226
-    {
227
-        $messenger = $this->get_messenger($messenger_name);
228
-        if ($messenger instanceof EE_messenger) {
229
-            return $messenger;
230
-        }
231
-        throw new EE_Error(
232
-            sprintf(
233
-                __('The "%1$s" messenger is either invalid or not installed', 'event_espresso'),
234
-                $messenger_name
235
-            )
236
-        );
237
-    }
238
-
239
-
240
-    /**
241
-     * @return EE_Message_Type_Collection
242
-     */
243
-    public function message_type_collection()
244
-    {
245
-        $this->_initialize_collections();
246
-        return $this->_message_type_collection_loader->message_type_collection();
247
-    }
248
-
249
-
250
-    /**
251
-     * @return array
252
-     */
253
-    public function active_message_types()
254
-    {
255
-        $this->_initialize_collections();
256
-        return $this->_active_message_types;
257
-    }
258
-
259
-
260
-    /**
261
-     * @param string $message_type_name
262
-     * @return \EE_message_type
263
-     */
264
-    public function get_message_type($message_type_name)
265
-    {
266
-        return $this->message_type_collection()->get_by_info($message_type_name);
267
-    }
268
-
269
-
270
-    /**
271
-     * This returns the EE_message_type from the active message types array ( if present );
272
-     *
273
-     * @param string $messenger_name
274
-     * @param string $message_type_name
275
-     * @return \EE_message_type|null
276
-     */
277
-    public function get_active_message_type_for_messenger($messenger_name, $message_type_name)
278
-    {
279
-        return $this->is_message_type_active_for_messenger($messenger_name, $message_type_name)
280
-            ? $this->get_message_type($message_type_name)
281
-            : null;
282
-    }
283
-
284
-
285
-    /**
286
-     * Returns whether the given message type is active for the given messenger.
287
-     *
288
-     * @param string $messenger_name
289
-     * @param string $message_type_name
290
-     * @return bool
291
-     */
292
-    public function is_message_type_active_for_messenger($messenger_name, $message_type_name)
293
-    {
294
-        $this->_initialize_collections();
295
-        return ! empty($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]);
296
-    }
297
-
298
-
299
-    /**
300
-     * Returns whether the given messenger is active.
301
-     *
302
-     * @param string $messenger_name the name of the messenger to check if active.
303
-     * @return bool
304
-     */
305
-    public function is_messenger_active($messenger_name)
306
-    {
307
-        $this->_initialize_collections();
308
-        return ! empty($this->_active_message_types[ $messenger_name ]);
309
-    }
310
-
311
-
312
-    /**
313
-     * This returns any settings that might be on a message type for a messenger
314
-     *
315
-     * @param string $messenger_name    The slug of the messenger
316
-     * @param string $message_type_name The slug of the message type getting the settings for.
317
-     * @return array
318
-     */
319
-    public function get_message_type_settings_for_messenger($messenger_name, $message_type_name)
320
-    {
321
-        $settings = array();
322
-        if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
323
-            $settings = isset($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings'])
324
-                ? $this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings']
325
-                : array();
326
-        }
327
-        return $settings;
328
-    }
329
-
330
-
331
-    /**
332
-     * Returns whether the given messenger name has active message types on it.
333
-     * Infers whether the messenger is active or not as well.
334
-     *
335
-     * @param string $messenger_name
336
-     * @return bool
337
-     */
338
-    public function messenger_has_active_message_types($messenger_name)
339
-    {
340
-        $this->_initialize_collections();
341
-        return
342
-            ! empty($this->_active_message_types[ $messenger_name ])
343
-            && ! empty($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ]);
344
-    }
345
-
346
-
347
-    /**
348
-     * This checks the _active_message_types property for any active message types
349
-     * that are present for the given messenger and returns them.
350
-     *
351
-     * @since 4.9.0
352
-     * @param string $messenger_name The messenger being checked
353
-     * @return EE_message_type[]|array    (empty array if no active_message_types)
354
-     */
355
-    public function get_active_message_types_for_messenger($messenger_name)
356
-    {
357
-        $message_types = array();
358
-        if (! $this->messenger_has_active_message_types($messenger_name)) {
359
-            return $message_types;
360
-        }
361
-        $installed_message_types = $this->installed_message_types();
362
-        foreach ($installed_message_types as $message_type_name => $message_type) {
363
-            if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
364
-                $message_types[ $message_type_name ] = $message_type;
365
-            }
366
-        }
367
-        return $message_types;
368
-    }
369
-
370
-
371
-    /**
372
-     * This does NOT return the _active_message_types property but
373
-     * simply returns an array of active message type names from that property.
374
-     * (The _active_message_types property is indexed by messenger and active message_types per messenger).
375
-     *
376
-     * @return array message_type references (string)
377
-     */
378
-    public function list_of_active_message_types()
379
-    {
380
-        $active_message_type_names = array();
381
-        $this->_initialize_collections();
382
-        foreach ($this->_active_message_types as $messenger => $messenger_settings) {
383
-            if (! isset($messenger_settings['settings'][ $messenger . '-message_types' ])) {
384
-                continue;
385
-            }
386
-            foreach ($messenger_settings['settings'][ $messenger . '-message_types' ] as $message_type_name => $message_type_config) {
387
-                if (! in_array($message_type_name, $active_message_type_names)) {
388
-                    $active_message_type_names[] = $message_type_name;
389
-                }
390
-            }
391
-        }
392
-        return $active_message_type_names;
393
-    }
394
-
395
-
396
-    /**
397
-     * Same as list_of_active_message_types() except this returns actual EE_message_type objects
398
-     *
399
-     * @since 4.9.0
400
-     * @return \EE_message_type[]
401
-     */
402
-    public function get_active_message_type_objects()
403
-    {
404
-        $active_message_types      = array();
405
-        $installed_message_types   = $this->installed_message_types();
406
-        $active_message_type_names = $this->list_of_active_message_types();
407
-        foreach ($active_message_type_names as $active_message_type_name) {
408
-            if (isset($installed_message_types[ $active_message_type_name ])) {
409
-                $active_message_types[ $active_message_type_name ] = $installed_message_types[ $active_message_type_name ];
410
-            }
411
-        }
412
-        return $active_message_types;
413
-    }
414
-
415
-
416
-    /**
417
-     * @return \EE_message_type[]
418
-     */
419
-    public function installed_message_types()
420
-    {
421
-        if (empty($this->_installed_message_types)) {
422
-            $this->message_type_collection()->rewind();
423
-            while ($this->message_type_collection()->valid()) {
424
-                $this->_installed_message_types[ $this->message_type_collection()->current()->name ] = $this->message_type_collection()->current();
425
-                $this->message_type_collection()->next();
426
-            }
427
-        }
428
-        return $this->_installed_message_types;
429
-    }
430
-
431
-
432
-    /**
433
-     * @param string $message_type_name
434
-     * @return \EE_message_type
435
-     * @throws EE_Error
436
-     */
437
-    public function valid_message_type($message_type_name)
438
-    {
439
-        $message_type = $this->get_message_type($message_type_name);
440
-        if ($message_type instanceof EE_message_type) {
441
-            return $message_type;
442
-        }
443
-        throw new EE_Error(
444
-            sprintf(
445
-                __('The "%1$s" message type is either invalid or not installed', 'event_espresso'),
446
-                $message_type_name
447
-            )
448
-        );
449
-    }
450
-
451
-
452
-    /**
453
-     * valid_message_type_for_messenger
454
-     *
455
-     * @param EE_messenger $messenger
456
-     * @param string       $message_type_name
457
-     * @return boolean
458
-     * @throws EE_Error
459
-     */
460
-    public function valid_message_type_for_messenger(EE_messenger $messenger, $message_type_name)
461
-    {
462
-        $valid_message_types = $messenger->get_valid_message_types();
463
-        if (! in_array($message_type_name, $valid_message_types)) {
464
-            throw new EE_Error(
465
-                sprintf(
466
-                    __(
467
-                        'The message type (%1$s) sent to "%2$s" is not valid for the "%3$s" messenger.  Double-check the spelling and verify that message type has been registered as a valid type with the messenger.',
468
-                        'event_espresso'
469
-                    ),
470
-                    $message_type_name,
471
-                    __METHOD__,
472
-                    $messenger->name
473
-                )
474
-            );
475
-        }
476
-        return true;
477
-    }
478
-
479
-
480
-    /**
481
-     * Used to return active messengers array stored in the wp options table.
482
-     * If no value is present in the option then an empty array is returned.
483
-     *
484
-     * @param   bool $reset     If true then we ignore whether the option is cached on the _active_message_types
485
-     *                          property and pull directly from the db.  Otherwise whatever is currently on the
486
-     *                          $_active_message_types property is pulled.
487
-     * @return array
488
-     */
489
-    public function get_active_messengers_option($reset = false)
490
-    {
491
-        if ($reset) {
492
-            $this->_active_message_types = get_option('ee_active_messengers', array());
493
-        }
494
-        return $this->_active_message_types;
495
-    }
496
-
497
-
498
-    /**
499
-     * Used to update the active messengers array stored in the wp options table.
500
-     *
501
-     * @param array $active_messenger_settings Incoming data to save.  If empty, then the internal cached property
502
-     *                                         representing this data is used.
503
-     * @return bool FALSE if not updated, TRUE if updated.
504
-     */
505
-    public function update_active_messengers_option($active_messenger_settings = array())
506
-    {
507
-        $active_messenger_settings = empty($active_messenger_settings) ? $this->_active_message_types : $active_messenger_settings;
508
-        // make sure _active_message_types is updated (this is the internal cache for the settings).
509
-        $this->_active_message_types = $active_messenger_settings;
510
-        return update_option('ee_active_messengers', $active_messenger_settings);
511
-    }
512
-
513
-
514
-    /**
515
-     * Used to return has activated message types for messengers array stored in the wp options table.
516
-     * If no value is present in the option then an empty array is returned.
517
-     * The value is cached on the $_has_activated_messengers_and_message_types property for future calls.
518
-     * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
519
-     *
520
-     * @param   bool $reset Used to indicate that any cached value should be ignored.
521
-     * @return array
522
-     */
523
-    public function get_has_activated_messengers_option($reset = false)
524
-    {
525
-        if ($reset || empty($this->_has_activated_messengers_and_message_types)) {
526
-            $this->_has_activated_messengers_and_message_types = get_option(self::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME, array());
527
-        }
528
-        return $this->_has_activated_messengers_and_message_types;
529
-    }
530
-
531
-
532
-    /**
533
-     * Used to update the has activated option in the db.
534
-     *
535
-     * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
536
-     *
537
-     * @param array $has_activated_messengers Incoming data to save.  If empty, then the internal cached property
538
-     *                                        representing this data is used.
539
-     * @return bool FALSE if not updated, TRUE if updated.
540
-     */
541
-    public function update_has_activated_messengers_option($has_activated_messengers = array())
542
-    {
543
-        // make sure the option has been retrieved from first so we don't overwrite it accidentally.
544
-        if (empty($has_activated_messengers) && empty($this->_has_activated_messengers_and_message_types)) {
545
-            $this->get_has_activated_messengers_option();
546
-        }
547
-        $has_activated_messengers = empty($has_activated_messengers)
548
-            ? $this->_has_activated_messengers_and_message_types
549
-            : $has_activated_messengers;
550
-        return update_option(self::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME, $has_activated_messengers);
551
-    }
552
-
553
-
554
-    /**
555
-     * wrapper for _set_active_messengers_and_message_types()
556
-     */
557
-    public function reset_active_messengers_and_message_types()
558
-    {
559
-        $this->_set_active_messengers_and_message_types();
560
-    }
561
-
562
-
563
-    /**
564
-     * Generate list of active messengers and message types from collection.
565
-     * This sets up the active messengers from what is present in the database.
566
-     */
567
-    protected function _set_active_messengers_and_message_types()
568
-    {
569
-        // echo "\n\n " . __LINE__ . ") " . __METHOD__ . "() \n";
570
-        // list of activated messengers as set via the admin
571
-        // note calling `get_active_messengers_options` also initializes the _active_message_types property.
572
-        $this->get_active_messengers_option(true);
573
-        $this->ensure_messengers_are_active(array(), false, true);
574
-        $this->update_active_messengers_option();
575
-        $this->update_has_activated_messengers_option();
576
-    }
577
-
578
-
579
-    /**
580
-     * Ensures that the specified messenger is currently active.
581
-     * If not, activates it and its default message types.
582
-     *
583
-     * @param string $messenger_name
584
-     * @param bool   $update_option Whether to update the option in the db or not.
585
-     * @return boolean true if either already active or successfully activated.
586
-     */
587
-    public function ensure_messenger_is_active($messenger_name, $update_option = true)
588
-    {
589
-        if (! isset($this->_active_messengers[ $messenger_name ])) {
590
-            try {
591
-                $this->activate_messenger($messenger_name, array(), $update_option);
592
-            } catch (EE_Error $e) {
593
-                EE_Error::add_error(
594
-                    $e->getMessage(),
595
-                    __FILE__,
596
-                    __FUNCTION__,
597
-                    __LINE__
598
-                );
599
-                return false;
600
-            }
601
-        }
602
-        return true;
603
-    }
604
-
605
-
606
-    /**
607
-     * This ensures the given array of messenger names is active in the system.
608
-     * Note, this method will not activate any NEW message types for the messenger when it is called. Instead,
609
-     * it will automatically activate the default message types for the messenger if its not active.
610
-     *
611
-     * @param array $messenger_names  Array of messenger names for messengers to be activated.  If an empty array
612
-     *                                (default) then will attempt to set the active messengers from the
613
-     *                                activated_messengers option
614
-     *                                (stored in $_active_message_types property).
615
-     * @param bool  $update_option    Whether to update the related active messengers option.
616
-     * @param bool  $verify           Whether to verify the messengers are installed before activating. Note if this is
617
-     *                                set to true and a messenger is indicated as active, but is NOT installed, then it
618
-     *                                will automatically be deactivated.
619
-     */
620
-    public function ensure_messengers_are_active($messenger_names = array(), $update_option = true, $verify = false)
621
-    {
622
-        $messenger_names = empty($messenger_names) ? array_keys($this->_active_message_types) : $messenger_names;
623
-
624
-        $not_installed = array();
625
-        foreach ($messenger_names as $messenger_name) {
626
-            if ($verify && ! $this->messenger_collection()->has_by_name($messenger_name)) {
627
-                $not_installed[] = $messenger_name;
628
-                $this->deactivate_messenger($messenger_name);
629
-                continue;
630
-            }
631
-            $this->ensure_messenger_is_active($messenger_name, $update_option);
632
-        }
633
-
634
-        if (! empty($not_installed)) {
635
-            EE_Error::add_error(
636
-                sprintf(
637
-                    __('The following messengers are either not installed or are invalid:%1$s %2$s', 'event_espresso'),
638
-                    '<br />',
639
-                    implode(', ', $not_installed)
640
-                ),
641
-                __FILE__,
642
-                __FUNCTION__,
643
-                __LINE__
644
-            );
645
-        }
646
-    }
647
-
648
-
649
-    /**
650
-     * Ensures that the specified message type for the given messenger is currently active, if not activates it.
651
-     * This ALSO ensures that the given messenger is active as well!
652
-     *
653
-     * @param string $message_type_name message type name.
654
-     * @param        $messenger_name
655
-     * @param bool   $update_option     Whether to update the option in the db or not.
656
-     * @return bool  Returns true if already is active or if was activated successfully.
657
-     * @throws EE_Error
658
-     */
659
-    public function ensure_message_type_is_active($message_type_name, $messenger_name, $update_option = true)
660
-    {
661
-        // grab the messenger to work with.
662
-        $messenger = $this->valid_messenger($messenger_name);
663
-        if ($this->valid_message_type_for_messenger($messenger, $message_type_name)) {
664
-            // ensure messenger is active (that's an inherent coupling between active message types and the
665
-            // messenger they are being activated for.
666
-            try {
667
-                if (! $this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
668
-                    // all is good so let's just get it active
669
-                    $this->activate_messenger($messenger, array($message_type_name), $update_option);
670
-                }
671
-            } catch (EE_Error $e) {
672
-                EE_Error::add_error(
673
-                    $e->getMessage(),
674
-                    __FILE__,
675
-                    __FUNCTION__,
676
-                    __LINE__
677
-                );
678
-                return false;
679
-            }
680
-        }
681
-        return true;
682
-    }
683
-
684
-
685
-    /**
686
-     * This is a wrapper for `ensure_message_type_is_active` that will handle ensuring multiple message types for a
687
-     * messenger are active in one go.
688
-     *
689
-     * @param array  $message_type_names Array of message type names to ensure are active.
690
-     * @param string $messenger_name     The name of the messenger that the message types are to be activated on.
691
-     * @param bool   $update_option      Whether to persist the activation to the database or not (default true).
692
-     */
693
-    public function ensure_message_types_are_active($message_type_names, $messenger_name, $update_option = true)
694
-    {
695
-        $message_type_names = (array) $message_type_names;
696
-        foreach ($message_type_names as $message_type_name) {
697
-            // note, intentionally not updating option here because we're in a loop.
698
-            // We'll follow the instructions of the incoming $update_option argument after the loop.
699
-            $this->ensure_message_type_is_active($message_type_name, $messenger_name, false);
700
-        }
701
-        if ($update_option) {
702
-            $this->update_active_messengers_option();
703
-            $this->update_has_activated_messengers_option();
704
-        }
705
-    }
706
-
707
-
708
-    /**
709
-     * Activates the specified messenger.
710
-     *
711
-     * @param EE_messenger|string $messenger    Instantiated EE_messenger OR messenger name if not already loaded!
712
-     * @param array  $message_type_names        An array of message type names to activate with this messenger.
713
-     *                                          If included we do NOT setup the default message types
714
-     *                                          (assuming they are already setup.)
715
-     * @param bool   $update_active_messengers_option
716
-     * @return array of generated templates
717
-     * @throws EE_Error
718
-     */
719
-    public function activate_messenger(
720
-        $messenger,
721
-        $message_type_names = array(),
722
-        $update_active_messengers_option = true
723
-    ) {
724
-        $templates = array();
725
-        // grab the messenger to work with.
726
-        $messenger = $messenger instanceof EE_messenger
727
-            ? $messenger
728
-            : $this->messenger_collection()->get_by_info($messenger);
729
-        // it's inactive. Activate it.
730
-        if ($messenger instanceof EE_messenger) {
731
-            $this->_active_messengers[ $messenger->name ] = $messenger;
732
-            // activate incoming message types set to be activated with messenger.
733
-            $message_type_names = $this->_activate_message_types($messenger, $message_type_names);
734
-            // setup any initial settings for the messenger if necessary.
735
-            $this->add_settings_for_messenger($messenger->name);
736
-            if ($update_active_messengers_option) {
737
-                $this->update_active_messengers_option();
738
-                $this->update_has_activated_messengers_option();
739
-            }
740
-            // generate new templates if necessary and ensure all related templates that are already in the database are
741
-            // marked active.  Note, this will also deactivate a message type for a messenger if the template
742
-            // cannot be successfully created during its attempt (only happens for global template attempts).
743
-            if (! empty($message_type_names)) {
744
-                $templates = EEH_MSG_Template::generate_new_templates($messenger->name, $message_type_names, 0, true);
745
-                EEH_MSG_Template::update_to_active(array($messenger->name), $message_type_names);
746
-            }
747
-        }
748
-        return $templates;
749
-    }
750
-
751
-
752
-    /**
753
-     * Activates given message types for the given EE_messenger object.
754
-     * Note: (very important) This method does not persist the activation to the database.
755
-     * See code implementing this method in this class for examples of how to persist.
756
-     *
757
-     * @param \EE_messenger $messenger
758
-     * @param  array        $message_type_names
759
-     * @return array
760
-     */
761
-    protected function _activate_message_types(EE_messenger $messenger, $message_type_names = array())
762
-    {
763
-        // If $message_type_names is empty, AND $this->_active_message_types is empty, then that means
764
-        // things have never been initialized (which should happen on EEH_Activation::generate_message_templates).
765
-        // So ONLY then do we need to actually grab defaults and cycle through them.  Otherwise we
766
-        // only override _active_message_types when an explicit array of $message_type_names has been provided.
767
-        $message_type_names = empty($message_type_names) && ! isset($this->_active_message_types[ $messenger->name ])
768
-            ? $messenger->get_default_message_types()
769
-            : (array) $message_type_names;
770
-
771
-        // now we ALWAYS need to make sure that the messenger is active for the message types we're activating!
772
-        if (! isset($this->_active_message_types[ $messenger->name ])) {
773
-            $this->_active_message_types[ $messenger->name ]['settings'] = array();
774
-        }
775
-
776
-        if ($message_type_names) {
777
-            // cycle thru message types
778
-            foreach ($message_type_names as $message_type_name) {
779
-                // only register the message type as active IF it isn't already active
780
-                // and if its actually installed.
781
-                if (! $this->is_message_type_active_for_messenger($messenger->name, $message_type_name)
782
-                ) {
783
-                    $this->add_settings_for_message_type($messenger->name, $message_type_name);
784
-                    $this->_set_messenger_has_activated_message_type(
785
-                        $messenger,
786
-                        $message_type_name
787
-                    );
788
-                }
789
-            }
790
-        }
791
-        return $message_type_names;
792
-    }
793
-
794
-
795
-    /**
796
-     * add_settings_for_message_type
797
-     * NOTE This does NOT automatically persist any settings to the db.  Client code should call
798
-     * $this->update_active_messengers_option to persist.
799
-     *
800
-     * @param  string $messenger_name    The name of the messenger adding the settings for
801
-     * @param  string $message_type_name The name of the message type adding the settings for
802
-     * @param  array  $new_settings      Any new settings being set for the message type and messenger
803
-     */
804
-    public function add_settings_for_message_type($messenger_name, $message_type_name, $new_settings = array())
805
-    {
806
-        // get installed message type from collection
807
-        $message_type      = $this->message_type_collection()->get_by_info($message_type_name);
808
-        $existing_settings = $this->get_message_type_settings_for_messenger($messenger_name, $message_type_name);
809
-        // we need to setup any initial settings for message types
810
-        if ($message_type instanceof EE_message_type) {
811
-            $default_settings = $message_type->get_admin_settings_fields();
812
-            foreach ($default_settings as $field => $values) {
813
-                if (isset($new_settings[ $field ])) {
814
-                    $existing_settings[ $field ] = $new_settings[ $field ];
815
-                    continue;
816
-                }
817
-                if (! isset($existing_settings[ $field ])) {
818
-                    $existing_settings[ $field ] = $values['default'];
819
-                }
820
-            }
821
-        }
822
-        $this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings'] = $existing_settings;
823
-    }
824
-
825
-
826
-    /**
827
-     * Updates the internal cached _has_activated_messengers_and_message_types property with the given messenger
828
-     * and message type.
829
-     *
830
-     * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
831
-     *
832
-     * @access protected
833
-     * @param \EE_messenger $messenger
834
-     * @param string        $message_type_name
835
-     */
836
-    protected function _set_messenger_has_activated_message_type(EE_messenger $messenger, $message_type_name)
837
-    {
838
-
839
-        // if _has_activated_messengers_and_message_types is empty then lets ensure its initialized
840
-        if (empty($this->_has_activated_messengers_and_message_types)) {
841
-            $this->get_has_activated_messengers_option();
842
-        }
843
-
844
-        // make sure this messenger has a record in the has_activated array
845
-        if (! isset($this->_has_activated_messengers_and_message_types[ $messenger->name ])) {
846
-            $this->_has_activated_messengers_and_message_types[ $messenger->name ] = array();
847
-        }
848
-        // check if message type has already been added
849
-        if (! in_array($message_type_name, $this->_has_activated_messengers_and_message_types[ $messenger->name ])) {
850
-            $this->_has_activated_messengers_and_message_types[ $messenger->name ][] = $message_type_name;
851
-        }
852
-    }
853
-
854
-
855
-    /**
856
-     * add_settings_for_messenger
857
-     * NOTE This does NOT automatically persist any settings to the db.  Client code should call
858
-     * $this->update_active_messengers_option to persist.
859
-     *
860
-     * @param string $messenger_name The name of the messenger the settings is being added for.
861
-     * @param array  $new_settings   An array of settings to update the existing settings.
862
-     */
863
-    public function add_settings_for_messenger($messenger_name, $new_settings = array())
864
-    {
865
-        $messenger = $this->get_messenger($messenger_name);
866
-        if ($messenger instanceof EE_messenger) {
867
-            $msgr_settings = $messenger->get_admin_settings_fields();
868
-            if (! empty($msgr_settings)) {
869
-                foreach ($msgr_settings as $field => $value) {
870
-                    // is there a new setting for this?
871
-                    if (isset($new_settings[ $field ])) {
872
-                        $this->_active_message_types[ $messenger->name ]['settings'][ $field ] = $new_settings[ $field ];
873
-                        continue;
874
-                    }
875
-                    // only set the default if it isn't already set.
876
-                    if (! isset($this->_active_message_types[ $messenger->name ]['settings'][ $field ])) {
877
-                        $this->_active_message_types[ $messenger->name ]['settings'][ $field ] = $value;
878
-                    }
879
-                }
880
-            }
881
-        }
882
-    }
883
-
884
-
885
-    /**
886
-     * deactivate_messenger
887
-     *
888
-     * @param  string|EE_messenger $messenger_name name of messenger
889
-     * @return void
890
-     */
891
-    public function deactivate_messenger($messenger_name)
892
-    {
893
-        $this->_initialize_collections();
894
-        if ($messenger_name instanceof EE_messenger) {
895
-            $messenger_name = $messenger_name->name;
896
-        }
897
-        unset($this->_active_messengers[ $messenger_name ]);
898
-        unset($this->_active_message_types[ $messenger_name ]);
899
-        $this->_message_template_group_model->deactivate_message_template_groups_for($messenger_name);
900
-        $this->update_active_messengers_option();
901
-    }
902
-
903
-
904
-    /**
905
-     * Deactivates a message type (note this will deactivate across all messenger's it is active on.
906
-     *
907
-     * @param  string $message_type_name     name of message type being deactivated
908
-     * @param bool    $set_has_active_record By default we always record the has_active record when deactivating a message
909
-     *                                       type.  However, this can be overridden if we don't want this set (usually when
910
-     *                                       this is called as a part of deregistration of a custom message type)
911
-     */
912
-    public function deactivate_message_type($message_type_name, $set_has_active_record = true)
913
-    {
914
-        $this->_initialize_collections();
915
-        if ($message_type_name instanceof EE_message_type) {
916
-            $message_type_name = $message_type_name->name;
917
-        }
918
-        foreach ($this->_active_message_types as $messenger_name => $settings) {
919
-            unset(
920
-                $this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]
921
-            );
922
-
923
-            // we always record (even on deactivation) that a message type has been activated because there should at
924
-            // least be a record in the "has_activated" option that it WAS active at one point.
925
-            if ($set_has_active_record) {
926
-                $messenger = $this->get_messenger($messenger_name);
927
-                $this->_set_messenger_has_activated_message_type($messenger, $message_type_name);
928
-            }
929
-        }
930
-        $this->_message_template_group_model->deactivate_message_template_groups_for('', $message_type_name);
931
-        $this->update_active_messengers_option();
932
-        $this->update_has_activated_messengers_option();
933
-    }
934
-
935
-
936
-    /**
937
-     * Deactivates a message type for a specific messenger as opposed to all messengers.
938
-     *
939
-     * @param string $message_type_name Name of message type being deactivated.
940
-     * @param string $messenger_name    Name of messenger the message type is being deactivated for.
941
-     */
942
-    public function deactivate_message_type_for_messenger($message_type_name, $messenger_name)
943
-    {
944
-        $this->_initialize_collections();
945
-        if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
946
-            unset($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]);
947
-        }
948
-        $this->_message_template_group_model->deactivate_message_template_groups_for(
949
-            array($messenger_name),
950
-            array($message_type_name)
951
-        );
952
-        $this->update_active_messengers_option();
953
-    }
954
-
955
-
956
-    /**
957
-     * Used to verify if a message can be sent for the given messenger and message type
958
-     * and that it is a generating messenger (used for generating message templates).
959
-     *
960
-     * @param EE_messenger    $messenger    messenger used in trigger
961
-     * @param EE_message_type $message_type message type used in trigger
962
-     * @return bool true is a generating messenger and can be sent OR FALSE meaning cannot send.
963
-     */
964
-    public function is_generating_messenger_and_active(EE_messenger $messenger, EE_message_type $message_type)
965
-    {
966
-        // get the $messengers the message type says it can be used with.
967
-        foreach ($message_type->with_messengers() as $generating_messenger => $secondary_messengers) {
968
-            if ($messenger->name === $generating_messenger
969
-                && $this->is_message_type_active_for_messenger($messenger->name, $message_type->name)
970
-            ) {
971
-                return true;
972
-            }
973
-        }
974
-        return false;
975
-    }
976
-
977
-
978
-    /**
979
-     * This returns all the contexts that are registered by all message types.
980
-     * If $slugs_only is true,
981
-     * then just an array indexed by unique context slugs with the latest label representation for that slug.
982
-     * array(
983
-     *      'context_slug' => 'localized label for context obtained from latest message type in the loop'.
984
-     * );
985
-     * If $slugs_only is false, then the format is:
986
-     * array(
987
-     *      'message_type_name' => array(
988
-     *          'context_slug' => array(
989
-     *              'label' => 'localized label for context',
990
-     *              'description' => 'localized description for context'
991
-     *          )
992
-     *      )
993
-     * );
994
-     * Keep in mind that although different message types may share the same context slugs,
995
-     * it is possible that the context is described differently by the message type.
996
-     *
997
-     * @since 4.9.0
998
-     * @param   bool $slugs_only Whether to return an array of just slugs and labels (true)
999
-     *                           or all contexts indexed by message type.
1000
-     * @return array
1001
-     */
1002
-    public function get_all_contexts($slugs_only = true)
1003
-    {
1004
-        $key = $slugs_only ? 'slugs' : 'all';
1005
-        // check if contexts has been setup yet.
1006
-        if (empty($this->_contexts[ $key ])) {
1007
-            // So let's get all active message type objects and loop through to get all unique contexts
1008
-            foreach ($this->get_active_message_type_objects() as $message_type) {
1009
-                if ($message_type instanceof EE_message_type) {
1010
-                    $message_type_contexts = $message_type->get_contexts();
1011
-                    if ($slugs_only) {
1012
-                        foreach ($message_type_contexts as $context => $context_details) {
1013
-                            $this->_contexts[ $key ][ $context ] = $context_details['label'];
1014
-                        }
1015
-                    } else {
1016
-                        $this->_contexts[ $key ][ $message_type->name ] = $message_type_contexts;
1017
-                    }
1018
-                }
1019
-            }
1020
-        }
1021
-        return ! empty($this->_contexts[ $key ]) ? $this->_contexts[ $key ] : array();
1022
-    }
1023
-
1024
-
1025
-    /**
1026
-     * This checks the internal record of what message types are considered "active" and verifies that
1027
-     * there is an installed class definition for that message type.  If the active message type does not have a
1028
-     * corresponding accessible message type class then it will be deactivated from all messengers it is active on and
1029
-     * any related message templates will be inactivated as well.
1030
-     *
1031
-     * @return bool   true means all active message types are valid, false means at least one message type was
1032
-     *                deactivated.
1033
-     */
1034
-    public function validate_active_message_types_are_installed()
1035
-    {
1036
-        $list_of_active_message_type_names = $this->list_of_active_message_types();
1037
-        $installed_message_types           = $this->installed_message_types();
1038
-        $all_message_types_valid           = true;
1039
-        // loop through list of active message types and verify they are installed.
1040
-        foreach ($list_of_active_message_type_names as $message_type_name) {
1041
-            if (! isset($installed_message_types[ $message_type_name ])) {
1042
-                $this->remove_message_type_has_been_activated_from_all_messengers(
1043
-                    $message_type_name,
1044
-                    true
1045
-                );
1046
-                $this->deactivate_message_type($message_type_name, false);
1047
-                $all_message_types_valid = false;
1048
-            }
1049
-        }
1050
-        return $all_message_types_valid;
1051
-    }
1052
-
1053
-
1054
-    /**
1055
-     * This method checks the `ee_has_activated_messenger` option to see if the message type has ever been
1056
-     * activated for the given messenger.  This can be called by client code on plugin updates etc to determine whether
1057
-     * to attempt automatically reactivating message types that should be activated by default or not.
1058
-     *
1059
-     * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
1060
-     *
1061
-     * @param $message_type_name
1062
-     * @param $messenger_name
1063
-     * @return bool
1064
-     */
1065
-    public function has_message_type_been_activated_for_messenger($message_type_name, $messenger_name)
1066
-    {
1067
-        $has_activated = $this->get_has_activated_messengers_option();
1068
-        return isset($has_activated[ $messenger_name ])
1069
-               && in_array($message_type_name, $has_activated[ $messenger_name ]);
1070
-    }
1071
-
1072
-
1073
-    /**
1074
-     * This method unsets a message type from the given messenger has activated option.
1075
-     *
1076
-     * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
1077
-     *
1078
-     * @param string $message_type_name
1079
-     * @param string $messenger_name
1080
-     * @param bool   $consider_current_state  Whether to consider whether the  message type is currently active or not.
1081
-     *                                        If it is currently active, then remove.  Otherwise leave it alone.
1082
-     */
1083
-    public function remove_message_type_has_been_activated_for_messenger(
1084
-        $message_type_name,
1085
-        $messenger_name,
1086
-        $consider_current_state = false
1087
-    ) {
1088
-        if ($consider_current_state
1089
-            && ! $this->is_message_type_active_for_messenger($messenger_name, $message_type_name)
1090
-        ) {
1091
-            // when consider current state is true, this means we don't want to change anything on the "has_activated"
1092
-            // record if the message type is currently active for this messenger.  This is used when we want to retain
1093
-            // the record for user initiated inactivations of the message type.
1094
-            return;
1095
-        }
1096
-        $has_activated = $this->get_has_activated_messengers_option();
1097
-        $key_for_message_type = isset($has_activated[ $messenger_name ])
1098
-            ? array_search($message_type_name, $has_activated[ $messenger_name ], true)
1099
-            : false;
1100
-        if ($key_for_message_type !== false) {
1101
-            unset($has_activated[ $messenger_name ][ $key_for_message_type ]);
1102
-            $this->update_has_activated_messengers_option($has_activated);
1103
-            // reset the internal cached property
1104
-            $this->get_has_activated_messengers_option(true);
1105
-        }
1106
-    }
1107
-
1108
-
1109
-    /**
1110
-     * Removes a message type active record from all messengers it is attached to.
1111
-     *
1112
-     * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
1113
-     *
1114
-     * @param      $message_type_name
1115
-     * @param bool $consider_current_state  Whether to consider whether the  message type is currently active or not.
1116
-     *                                      If it is currently active, then remove.  Otherwise leave it alone.
1117
-     */
1118
-    public function remove_message_type_has_been_activated_from_all_messengers(
1119
-        $message_type_name,
1120
-        $consider_current_state = false
1121
-    ) {
1122
-        foreach (array_keys($this->get_has_activated_messengers_option()) as $messenger_name) {
1123
-            $this->remove_message_type_has_been_activated_for_messenger(
1124
-                $message_type_name,
1125
-                $messenger_name,
1126
-                $consider_current_state
1127
-            );
1128
-        }
1129
-    }
15
+	/**
16
+	 * This option in the database is used to keep a record of message types that have been activated for a messenger
17
+	 * at some point in the history of the site.  It is utilized by the implementation of the 'force' flag in
18
+	 * EE_Register_Message_Type.  The force flag is an indication of whether a message type should be activated by
19
+	 * default when the message type is registered.  However, if a user has explicitly deactivated a message type, then
20
+	 * the force flag is ignored.  The method by which the code knows whether to ignore this flag is via this option.
21
+	 * Note, that this is NOT a historical record.  Its entirely possible for a message type to have been activated for
22
+	 * a messenger and yet not have a record in this option.  This occurs when a message type is inactivated through an
23
+	 * automated process (when an add-on registering the message type deactivates, or when some other code calls the
24
+	 * EE_Registery_Message_Type::deregister method) and the related record(s) is(are) removed from this option to ensure
25
+	 * the "force" flag is respected if that message type is later re-registered.
26
+	 *
27
+	 * This option should NOT be used to determine the current "active" state of a message type for a given messenger.
28
+	 *
29
+	 * The name of this option (and related methods/properties) is due to matching the original intended purpose for the
30
+	 * option that got superseded by later behaviour requirements.
31
+	 */
32
+	const HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME = 'ee_has_activated_messenger';
33
+
34
+	/**
35
+	 * @type boolean $_initialized
36
+	 */
37
+	protected $_initialized = false;
38
+
39
+	/**
40
+	 * @type EE_Messenger_Collection $_messenger_collection_loader
41
+	 */
42
+	protected $_messenger_collection_loader;
43
+
44
+	/**
45
+	 * @type EE_Message_Type_Collection $_message_type_collection_loader
46
+	 */
47
+	protected $_message_type_collection_loader;
48
+
49
+	/**
50
+	 * @type EEM_Message_Template_Group $_message_template_group_model
51
+	 */
52
+	protected $_message_template_group_model;
53
+
54
+	/**
55
+	 * @type EE_messenger[]
56
+	 */
57
+	protected $_installed_messengers = array();
58
+
59
+	/**
60
+	 * @type EE_message_type[]
61
+	 */
62
+	protected $_installed_message_types = array();
63
+
64
+	/**
65
+	 * Array of active messengers.
66
+	 * Format is this:
67
+	 * array(
68
+	 *      'messenger_name' => EE_messenger
69
+	 * )
70
+	 *
71
+	 * @type EE_messenger[]
72
+	 */
73
+	protected $_active_messengers = array();
74
+
75
+	/**
76
+	 * Formatted array of active message types grouped per messenger.
77
+	 * Format is this:
78
+	 * array(
79
+	 *      'messenger_name' => array(
80
+	 *          'settings' => array(
81
+	 *              '{messenger_name}-message_types' => array(
82
+	 *                  'message_type_name' => array() //variable array of settings corresponding to message type.
83
+	 *              )
84
+	 *          )
85
+	 *      )
86
+	 * )
87
+	 *
88
+	 * @type array
89
+	 */
90
+	protected $_active_message_types = array();
91
+
92
+
93
+	/**
94
+	 * This holds the array of messengers and their corresponding message types that have
95
+	 * been activated on a site at some point.  This is an important record that helps the messages system
96
+	 * not accidentally reactivate something that was intentionally deactivated by a user.
97
+	 *
98
+	 * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
99
+	 *
100
+	 * @type array
101
+	 */
102
+	protected $_has_activated_messengers_and_message_types = array();
103
+
104
+	/**
105
+	 * An array of unique message type contexts across all active message types.
106
+	 * The array will be indexed by either 'slugs' or 'all'.
107
+	 * The slugs index contains an array indexed by unique context slugs with the latest label representation for that
108
+	 * slug. array(
109
+	 *      'context_slug' => 'localized label for context obtained from latest message type in the loop'.
110
+	 * );
111
+	 * The all index returns an array in this format:
112
+	 * array(
113
+	 *      'message_type_name' => array(
114
+	 *          'context_slug' => array(
115
+	 *              'label' => 'localized label for context',
116
+	 *              'description' => 'localized description for context'
117
+	 *          )
118
+	 *      )
119
+	 * );
120
+	 *
121
+	 * @type array
122
+	 */
123
+	protected $_contexts = array();
124
+
125
+
126
+	/**
127
+	 * EE_Message_Resource_Manager constructor.
128
+	 *
129
+	 * @param \EE_Messenger_Collection_Loader    $Messenger_Collection_Loader
130
+	 * @param \EE_Message_Type_Collection_Loader $Message_Type_Collection_Loader
131
+	 * @param \EEM_Message_Template_Group        $Message_Template_Group_Model
132
+	 */
133
+	public function __construct(
134
+		EE_Messenger_Collection_Loader $Messenger_Collection_Loader,
135
+		EE_Message_Type_Collection_Loader $Message_Type_Collection_Loader,
136
+		EEM_Message_Template_Group $Message_Template_Group_Model
137
+	) {
138
+		$this->_messenger_collection_loader    = $Messenger_Collection_Loader;
139
+		$this->_message_type_collection_loader = $Message_Type_Collection_Loader;
140
+		$this->_message_template_group_model   = $Message_Template_Group_Model;
141
+	}
142
+
143
+
144
+	/**
145
+	 * @return void
146
+	 */
147
+	protected function _initialize_collections()
148
+	{
149
+		if ($this->_initialized) {
150
+			return;
151
+		}
152
+		$this->_initialized = true;
153
+		$this->_messenger_collection_loader->load_messengers_from_folder();
154
+		$this->_message_type_collection_loader->load_message_types_from_folder();
155
+		$this->get_has_activated_messengers_option(true);
156
+		$this->_set_active_messengers_and_message_types();
157
+	}
158
+
159
+
160
+	/**
161
+	 * @return EE_Messenger_Collection
162
+	 */
163
+	public function messenger_collection()
164
+	{
165
+		$this->_initialize_collections();
166
+		return $this->_messenger_collection_loader->messenger_collection();
167
+	}
168
+
169
+
170
+	/**
171
+	 * @return EE_messenger[]
172
+	 */
173
+	public function active_messengers()
174
+	{
175
+		$this->_initialize_collections();
176
+		return $this->_active_messengers;
177
+	}
178
+
179
+
180
+	/**
181
+	 * @param string $messenger_name
182
+	 * @return \EE_messenger
183
+	 */
184
+	public function get_messenger($messenger_name)
185
+	{
186
+		return $this->messenger_collection()->get_by_info($messenger_name);
187
+	}
188
+
189
+
190
+	/**
191
+	 * This returns the corresponding EE_messenger object for the given string if it is active.
192
+	 *
193
+	 * @param string $messenger
194
+	 * @return EE_messenger | null
195
+	 */
196
+	public function get_active_messenger($messenger)
197
+	{
198
+		$this->_initialize_collections();
199
+		return ! empty($this->_active_messengers[ $messenger ]) ? $this->_active_messengers[ $messenger ] : null;
200
+	}
201
+
202
+
203
+	/**
204
+	 * @return \EE_messenger[]
205
+	 */
206
+	public function installed_messengers()
207
+	{
208
+		if (empty($this->_installed_messengers)) {
209
+			$this->_installed_messengers = array();
210
+			$this->messenger_collection()->rewind();
211
+			while ($this->messenger_collection()->valid()) {
212
+				$this->_installed_messengers[ $this->messenger_collection()->current()->name ] = $this->messenger_collection()->current();
213
+				$this->messenger_collection()->next();
214
+			}
215
+		}
216
+		return $this->_installed_messengers;
217
+	}
218
+
219
+
220
+	/**
221
+	 * @param string $messenger_name
222
+	 * @return \EE_messenger
223
+	 * @throws EE_Error
224
+	 */
225
+	public function valid_messenger($messenger_name)
226
+	{
227
+		$messenger = $this->get_messenger($messenger_name);
228
+		if ($messenger instanceof EE_messenger) {
229
+			return $messenger;
230
+		}
231
+		throw new EE_Error(
232
+			sprintf(
233
+				__('The "%1$s" messenger is either invalid or not installed', 'event_espresso'),
234
+				$messenger_name
235
+			)
236
+		);
237
+	}
238
+
239
+
240
+	/**
241
+	 * @return EE_Message_Type_Collection
242
+	 */
243
+	public function message_type_collection()
244
+	{
245
+		$this->_initialize_collections();
246
+		return $this->_message_type_collection_loader->message_type_collection();
247
+	}
248
+
249
+
250
+	/**
251
+	 * @return array
252
+	 */
253
+	public function active_message_types()
254
+	{
255
+		$this->_initialize_collections();
256
+		return $this->_active_message_types;
257
+	}
258
+
259
+
260
+	/**
261
+	 * @param string $message_type_name
262
+	 * @return \EE_message_type
263
+	 */
264
+	public function get_message_type($message_type_name)
265
+	{
266
+		return $this->message_type_collection()->get_by_info($message_type_name);
267
+	}
268
+
269
+
270
+	/**
271
+	 * This returns the EE_message_type from the active message types array ( if present );
272
+	 *
273
+	 * @param string $messenger_name
274
+	 * @param string $message_type_name
275
+	 * @return \EE_message_type|null
276
+	 */
277
+	public function get_active_message_type_for_messenger($messenger_name, $message_type_name)
278
+	{
279
+		return $this->is_message_type_active_for_messenger($messenger_name, $message_type_name)
280
+			? $this->get_message_type($message_type_name)
281
+			: null;
282
+	}
283
+
284
+
285
+	/**
286
+	 * Returns whether the given message type is active for the given messenger.
287
+	 *
288
+	 * @param string $messenger_name
289
+	 * @param string $message_type_name
290
+	 * @return bool
291
+	 */
292
+	public function is_message_type_active_for_messenger($messenger_name, $message_type_name)
293
+	{
294
+		$this->_initialize_collections();
295
+		return ! empty($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]);
296
+	}
297
+
298
+
299
+	/**
300
+	 * Returns whether the given messenger is active.
301
+	 *
302
+	 * @param string $messenger_name the name of the messenger to check if active.
303
+	 * @return bool
304
+	 */
305
+	public function is_messenger_active($messenger_name)
306
+	{
307
+		$this->_initialize_collections();
308
+		return ! empty($this->_active_message_types[ $messenger_name ]);
309
+	}
310
+
311
+
312
+	/**
313
+	 * This returns any settings that might be on a message type for a messenger
314
+	 *
315
+	 * @param string $messenger_name    The slug of the messenger
316
+	 * @param string $message_type_name The slug of the message type getting the settings for.
317
+	 * @return array
318
+	 */
319
+	public function get_message_type_settings_for_messenger($messenger_name, $message_type_name)
320
+	{
321
+		$settings = array();
322
+		if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
323
+			$settings = isset($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings'])
324
+				? $this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings']
325
+				: array();
326
+		}
327
+		return $settings;
328
+	}
329
+
330
+
331
+	/**
332
+	 * Returns whether the given messenger name has active message types on it.
333
+	 * Infers whether the messenger is active or not as well.
334
+	 *
335
+	 * @param string $messenger_name
336
+	 * @return bool
337
+	 */
338
+	public function messenger_has_active_message_types($messenger_name)
339
+	{
340
+		$this->_initialize_collections();
341
+		return
342
+			! empty($this->_active_message_types[ $messenger_name ])
343
+			&& ! empty($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ]);
344
+	}
345
+
346
+
347
+	/**
348
+	 * This checks the _active_message_types property for any active message types
349
+	 * that are present for the given messenger and returns them.
350
+	 *
351
+	 * @since 4.9.0
352
+	 * @param string $messenger_name The messenger being checked
353
+	 * @return EE_message_type[]|array    (empty array if no active_message_types)
354
+	 */
355
+	public function get_active_message_types_for_messenger($messenger_name)
356
+	{
357
+		$message_types = array();
358
+		if (! $this->messenger_has_active_message_types($messenger_name)) {
359
+			return $message_types;
360
+		}
361
+		$installed_message_types = $this->installed_message_types();
362
+		foreach ($installed_message_types as $message_type_name => $message_type) {
363
+			if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
364
+				$message_types[ $message_type_name ] = $message_type;
365
+			}
366
+		}
367
+		return $message_types;
368
+	}
369
+
370
+
371
+	/**
372
+	 * This does NOT return the _active_message_types property but
373
+	 * simply returns an array of active message type names from that property.
374
+	 * (The _active_message_types property is indexed by messenger and active message_types per messenger).
375
+	 *
376
+	 * @return array message_type references (string)
377
+	 */
378
+	public function list_of_active_message_types()
379
+	{
380
+		$active_message_type_names = array();
381
+		$this->_initialize_collections();
382
+		foreach ($this->_active_message_types as $messenger => $messenger_settings) {
383
+			if (! isset($messenger_settings['settings'][ $messenger . '-message_types' ])) {
384
+				continue;
385
+			}
386
+			foreach ($messenger_settings['settings'][ $messenger . '-message_types' ] as $message_type_name => $message_type_config) {
387
+				if (! in_array($message_type_name, $active_message_type_names)) {
388
+					$active_message_type_names[] = $message_type_name;
389
+				}
390
+			}
391
+		}
392
+		return $active_message_type_names;
393
+	}
394
+
395
+
396
+	/**
397
+	 * Same as list_of_active_message_types() except this returns actual EE_message_type objects
398
+	 *
399
+	 * @since 4.9.0
400
+	 * @return \EE_message_type[]
401
+	 */
402
+	public function get_active_message_type_objects()
403
+	{
404
+		$active_message_types      = array();
405
+		$installed_message_types   = $this->installed_message_types();
406
+		$active_message_type_names = $this->list_of_active_message_types();
407
+		foreach ($active_message_type_names as $active_message_type_name) {
408
+			if (isset($installed_message_types[ $active_message_type_name ])) {
409
+				$active_message_types[ $active_message_type_name ] = $installed_message_types[ $active_message_type_name ];
410
+			}
411
+		}
412
+		return $active_message_types;
413
+	}
414
+
415
+
416
+	/**
417
+	 * @return \EE_message_type[]
418
+	 */
419
+	public function installed_message_types()
420
+	{
421
+		if (empty($this->_installed_message_types)) {
422
+			$this->message_type_collection()->rewind();
423
+			while ($this->message_type_collection()->valid()) {
424
+				$this->_installed_message_types[ $this->message_type_collection()->current()->name ] = $this->message_type_collection()->current();
425
+				$this->message_type_collection()->next();
426
+			}
427
+		}
428
+		return $this->_installed_message_types;
429
+	}
430
+
431
+
432
+	/**
433
+	 * @param string $message_type_name
434
+	 * @return \EE_message_type
435
+	 * @throws EE_Error
436
+	 */
437
+	public function valid_message_type($message_type_name)
438
+	{
439
+		$message_type = $this->get_message_type($message_type_name);
440
+		if ($message_type instanceof EE_message_type) {
441
+			return $message_type;
442
+		}
443
+		throw new EE_Error(
444
+			sprintf(
445
+				__('The "%1$s" message type is either invalid or not installed', 'event_espresso'),
446
+				$message_type_name
447
+			)
448
+		);
449
+	}
450
+
451
+
452
+	/**
453
+	 * valid_message_type_for_messenger
454
+	 *
455
+	 * @param EE_messenger $messenger
456
+	 * @param string       $message_type_name
457
+	 * @return boolean
458
+	 * @throws EE_Error
459
+	 */
460
+	public function valid_message_type_for_messenger(EE_messenger $messenger, $message_type_name)
461
+	{
462
+		$valid_message_types = $messenger->get_valid_message_types();
463
+		if (! in_array($message_type_name, $valid_message_types)) {
464
+			throw new EE_Error(
465
+				sprintf(
466
+					__(
467
+						'The message type (%1$s) sent to "%2$s" is not valid for the "%3$s" messenger.  Double-check the spelling and verify that message type has been registered as a valid type with the messenger.',
468
+						'event_espresso'
469
+					),
470
+					$message_type_name,
471
+					__METHOD__,
472
+					$messenger->name
473
+				)
474
+			);
475
+		}
476
+		return true;
477
+	}
478
+
479
+
480
+	/**
481
+	 * Used to return active messengers array stored in the wp options table.
482
+	 * If no value is present in the option then an empty array is returned.
483
+	 *
484
+	 * @param   bool $reset     If true then we ignore whether the option is cached on the _active_message_types
485
+	 *                          property and pull directly from the db.  Otherwise whatever is currently on the
486
+	 *                          $_active_message_types property is pulled.
487
+	 * @return array
488
+	 */
489
+	public function get_active_messengers_option($reset = false)
490
+	{
491
+		if ($reset) {
492
+			$this->_active_message_types = get_option('ee_active_messengers', array());
493
+		}
494
+		return $this->_active_message_types;
495
+	}
496
+
497
+
498
+	/**
499
+	 * Used to update the active messengers array stored in the wp options table.
500
+	 *
501
+	 * @param array $active_messenger_settings Incoming data to save.  If empty, then the internal cached property
502
+	 *                                         representing this data is used.
503
+	 * @return bool FALSE if not updated, TRUE if updated.
504
+	 */
505
+	public function update_active_messengers_option($active_messenger_settings = array())
506
+	{
507
+		$active_messenger_settings = empty($active_messenger_settings) ? $this->_active_message_types : $active_messenger_settings;
508
+		// make sure _active_message_types is updated (this is the internal cache for the settings).
509
+		$this->_active_message_types = $active_messenger_settings;
510
+		return update_option('ee_active_messengers', $active_messenger_settings);
511
+	}
512
+
513
+
514
+	/**
515
+	 * Used to return has activated message types for messengers array stored in the wp options table.
516
+	 * If no value is present in the option then an empty array is returned.
517
+	 * The value is cached on the $_has_activated_messengers_and_message_types property for future calls.
518
+	 * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
519
+	 *
520
+	 * @param   bool $reset Used to indicate that any cached value should be ignored.
521
+	 * @return array
522
+	 */
523
+	public function get_has_activated_messengers_option($reset = false)
524
+	{
525
+		if ($reset || empty($this->_has_activated_messengers_and_message_types)) {
526
+			$this->_has_activated_messengers_and_message_types = get_option(self::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME, array());
527
+		}
528
+		return $this->_has_activated_messengers_and_message_types;
529
+	}
530
+
531
+
532
+	/**
533
+	 * Used to update the has activated option in the db.
534
+	 *
535
+	 * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
536
+	 *
537
+	 * @param array $has_activated_messengers Incoming data to save.  If empty, then the internal cached property
538
+	 *                                        representing this data is used.
539
+	 * @return bool FALSE if not updated, TRUE if updated.
540
+	 */
541
+	public function update_has_activated_messengers_option($has_activated_messengers = array())
542
+	{
543
+		// make sure the option has been retrieved from first so we don't overwrite it accidentally.
544
+		if (empty($has_activated_messengers) && empty($this->_has_activated_messengers_and_message_types)) {
545
+			$this->get_has_activated_messengers_option();
546
+		}
547
+		$has_activated_messengers = empty($has_activated_messengers)
548
+			? $this->_has_activated_messengers_and_message_types
549
+			: $has_activated_messengers;
550
+		return update_option(self::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME, $has_activated_messengers);
551
+	}
552
+
553
+
554
+	/**
555
+	 * wrapper for _set_active_messengers_and_message_types()
556
+	 */
557
+	public function reset_active_messengers_and_message_types()
558
+	{
559
+		$this->_set_active_messengers_and_message_types();
560
+	}
561
+
562
+
563
+	/**
564
+	 * Generate list of active messengers and message types from collection.
565
+	 * This sets up the active messengers from what is present in the database.
566
+	 */
567
+	protected function _set_active_messengers_and_message_types()
568
+	{
569
+		// echo "\n\n " . __LINE__ . ") " . __METHOD__ . "() \n";
570
+		// list of activated messengers as set via the admin
571
+		// note calling `get_active_messengers_options` also initializes the _active_message_types property.
572
+		$this->get_active_messengers_option(true);
573
+		$this->ensure_messengers_are_active(array(), false, true);
574
+		$this->update_active_messengers_option();
575
+		$this->update_has_activated_messengers_option();
576
+	}
577
+
578
+
579
+	/**
580
+	 * Ensures that the specified messenger is currently active.
581
+	 * If not, activates it and its default message types.
582
+	 *
583
+	 * @param string $messenger_name
584
+	 * @param bool   $update_option Whether to update the option in the db or not.
585
+	 * @return boolean true if either already active or successfully activated.
586
+	 */
587
+	public function ensure_messenger_is_active($messenger_name, $update_option = true)
588
+	{
589
+		if (! isset($this->_active_messengers[ $messenger_name ])) {
590
+			try {
591
+				$this->activate_messenger($messenger_name, array(), $update_option);
592
+			} catch (EE_Error $e) {
593
+				EE_Error::add_error(
594
+					$e->getMessage(),
595
+					__FILE__,
596
+					__FUNCTION__,
597
+					__LINE__
598
+				);
599
+				return false;
600
+			}
601
+		}
602
+		return true;
603
+	}
604
+
605
+
606
+	/**
607
+	 * This ensures the given array of messenger names is active in the system.
608
+	 * Note, this method will not activate any NEW message types for the messenger when it is called. Instead,
609
+	 * it will automatically activate the default message types for the messenger if its not active.
610
+	 *
611
+	 * @param array $messenger_names  Array of messenger names for messengers to be activated.  If an empty array
612
+	 *                                (default) then will attempt to set the active messengers from the
613
+	 *                                activated_messengers option
614
+	 *                                (stored in $_active_message_types property).
615
+	 * @param bool  $update_option    Whether to update the related active messengers option.
616
+	 * @param bool  $verify           Whether to verify the messengers are installed before activating. Note if this is
617
+	 *                                set to true and a messenger is indicated as active, but is NOT installed, then it
618
+	 *                                will automatically be deactivated.
619
+	 */
620
+	public function ensure_messengers_are_active($messenger_names = array(), $update_option = true, $verify = false)
621
+	{
622
+		$messenger_names = empty($messenger_names) ? array_keys($this->_active_message_types) : $messenger_names;
623
+
624
+		$not_installed = array();
625
+		foreach ($messenger_names as $messenger_name) {
626
+			if ($verify && ! $this->messenger_collection()->has_by_name($messenger_name)) {
627
+				$not_installed[] = $messenger_name;
628
+				$this->deactivate_messenger($messenger_name);
629
+				continue;
630
+			}
631
+			$this->ensure_messenger_is_active($messenger_name, $update_option);
632
+		}
633
+
634
+		if (! empty($not_installed)) {
635
+			EE_Error::add_error(
636
+				sprintf(
637
+					__('The following messengers are either not installed or are invalid:%1$s %2$s', 'event_espresso'),
638
+					'<br />',
639
+					implode(', ', $not_installed)
640
+				),
641
+				__FILE__,
642
+				__FUNCTION__,
643
+				__LINE__
644
+			);
645
+		}
646
+	}
647
+
648
+
649
+	/**
650
+	 * Ensures that the specified message type for the given messenger is currently active, if not activates it.
651
+	 * This ALSO ensures that the given messenger is active as well!
652
+	 *
653
+	 * @param string $message_type_name message type name.
654
+	 * @param        $messenger_name
655
+	 * @param bool   $update_option     Whether to update the option in the db or not.
656
+	 * @return bool  Returns true if already is active or if was activated successfully.
657
+	 * @throws EE_Error
658
+	 */
659
+	public function ensure_message_type_is_active($message_type_name, $messenger_name, $update_option = true)
660
+	{
661
+		// grab the messenger to work with.
662
+		$messenger = $this->valid_messenger($messenger_name);
663
+		if ($this->valid_message_type_for_messenger($messenger, $message_type_name)) {
664
+			// ensure messenger is active (that's an inherent coupling between active message types and the
665
+			// messenger they are being activated for.
666
+			try {
667
+				if (! $this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
668
+					// all is good so let's just get it active
669
+					$this->activate_messenger($messenger, array($message_type_name), $update_option);
670
+				}
671
+			} catch (EE_Error $e) {
672
+				EE_Error::add_error(
673
+					$e->getMessage(),
674
+					__FILE__,
675
+					__FUNCTION__,
676
+					__LINE__
677
+				);
678
+				return false;
679
+			}
680
+		}
681
+		return true;
682
+	}
683
+
684
+
685
+	/**
686
+	 * This is a wrapper for `ensure_message_type_is_active` that will handle ensuring multiple message types for a
687
+	 * messenger are active in one go.
688
+	 *
689
+	 * @param array  $message_type_names Array of message type names to ensure are active.
690
+	 * @param string $messenger_name     The name of the messenger that the message types are to be activated on.
691
+	 * @param bool   $update_option      Whether to persist the activation to the database or not (default true).
692
+	 */
693
+	public function ensure_message_types_are_active($message_type_names, $messenger_name, $update_option = true)
694
+	{
695
+		$message_type_names = (array) $message_type_names;
696
+		foreach ($message_type_names as $message_type_name) {
697
+			// note, intentionally not updating option here because we're in a loop.
698
+			// We'll follow the instructions of the incoming $update_option argument after the loop.
699
+			$this->ensure_message_type_is_active($message_type_name, $messenger_name, false);
700
+		}
701
+		if ($update_option) {
702
+			$this->update_active_messengers_option();
703
+			$this->update_has_activated_messengers_option();
704
+		}
705
+	}
706
+
707
+
708
+	/**
709
+	 * Activates the specified messenger.
710
+	 *
711
+	 * @param EE_messenger|string $messenger    Instantiated EE_messenger OR messenger name if not already loaded!
712
+	 * @param array  $message_type_names        An array of message type names to activate with this messenger.
713
+	 *                                          If included we do NOT setup the default message types
714
+	 *                                          (assuming they are already setup.)
715
+	 * @param bool   $update_active_messengers_option
716
+	 * @return array of generated templates
717
+	 * @throws EE_Error
718
+	 */
719
+	public function activate_messenger(
720
+		$messenger,
721
+		$message_type_names = array(),
722
+		$update_active_messengers_option = true
723
+	) {
724
+		$templates = array();
725
+		// grab the messenger to work with.
726
+		$messenger = $messenger instanceof EE_messenger
727
+			? $messenger
728
+			: $this->messenger_collection()->get_by_info($messenger);
729
+		// it's inactive. Activate it.
730
+		if ($messenger instanceof EE_messenger) {
731
+			$this->_active_messengers[ $messenger->name ] = $messenger;
732
+			// activate incoming message types set to be activated with messenger.
733
+			$message_type_names = $this->_activate_message_types($messenger, $message_type_names);
734
+			// setup any initial settings for the messenger if necessary.
735
+			$this->add_settings_for_messenger($messenger->name);
736
+			if ($update_active_messengers_option) {
737
+				$this->update_active_messengers_option();
738
+				$this->update_has_activated_messengers_option();
739
+			}
740
+			// generate new templates if necessary and ensure all related templates that are already in the database are
741
+			// marked active.  Note, this will also deactivate a message type for a messenger if the template
742
+			// cannot be successfully created during its attempt (only happens for global template attempts).
743
+			if (! empty($message_type_names)) {
744
+				$templates = EEH_MSG_Template::generate_new_templates($messenger->name, $message_type_names, 0, true);
745
+				EEH_MSG_Template::update_to_active(array($messenger->name), $message_type_names);
746
+			}
747
+		}
748
+		return $templates;
749
+	}
750
+
751
+
752
+	/**
753
+	 * Activates given message types for the given EE_messenger object.
754
+	 * Note: (very important) This method does not persist the activation to the database.
755
+	 * See code implementing this method in this class for examples of how to persist.
756
+	 *
757
+	 * @param \EE_messenger $messenger
758
+	 * @param  array        $message_type_names
759
+	 * @return array
760
+	 */
761
+	protected function _activate_message_types(EE_messenger $messenger, $message_type_names = array())
762
+	{
763
+		// If $message_type_names is empty, AND $this->_active_message_types is empty, then that means
764
+		// things have never been initialized (which should happen on EEH_Activation::generate_message_templates).
765
+		// So ONLY then do we need to actually grab defaults and cycle through them.  Otherwise we
766
+		// only override _active_message_types when an explicit array of $message_type_names has been provided.
767
+		$message_type_names = empty($message_type_names) && ! isset($this->_active_message_types[ $messenger->name ])
768
+			? $messenger->get_default_message_types()
769
+			: (array) $message_type_names;
770
+
771
+		// now we ALWAYS need to make sure that the messenger is active for the message types we're activating!
772
+		if (! isset($this->_active_message_types[ $messenger->name ])) {
773
+			$this->_active_message_types[ $messenger->name ]['settings'] = array();
774
+		}
775
+
776
+		if ($message_type_names) {
777
+			// cycle thru message types
778
+			foreach ($message_type_names as $message_type_name) {
779
+				// only register the message type as active IF it isn't already active
780
+				// and if its actually installed.
781
+				if (! $this->is_message_type_active_for_messenger($messenger->name, $message_type_name)
782
+				) {
783
+					$this->add_settings_for_message_type($messenger->name, $message_type_name);
784
+					$this->_set_messenger_has_activated_message_type(
785
+						$messenger,
786
+						$message_type_name
787
+					);
788
+				}
789
+			}
790
+		}
791
+		return $message_type_names;
792
+	}
793
+
794
+
795
+	/**
796
+	 * add_settings_for_message_type
797
+	 * NOTE This does NOT automatically persist any settings to the db.  Client code should call
798
+	 * $this->update_active_messengers_option to persist.
799
+	 *
800
+	 * @param  string $messenger_name    The name of the messenger adding the settings for
801
+	 * @param  string $message_type_name The name of the message type adding the settings for
802
+	 * @param  array  $new_settings      Any new settings being set for the message type and messenger
803
+	 */
804
+	public function add_settings_for_message_type($messenger_name, $message_type_name, $new_settings = array())
805
+	{
806
+		// get installed message type from collection
807
+		$message_type      = $this->message_type_collection()->get_by_info($message_type_name);
808
+		$existing_settings = $this->get_message_type_settings_for_messenger($messenger_name, $message_type_name);
809
+		// we need to setup any initial settings for message types
810
+		if ($message_type instanceof EE_message_type) {
811
+			$default_settings = $message_type->get_admin_settings_fields();
812
+			foreach ($default_settings as $field => $values) {
813
+				if (isset($new_settings[ $field ])) {
814
+					$existing_settings[ $field ] = $new_settings[ $field ];
815
+					continue;
816
+				}
817
+				if (! isset($existing_settings[ $field ])) {
818
+					$existing_settings[ $field ] = $values['default'];
819
+				}
820
+			}
821
+		}
822
+		$this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings'] = $existing_settings;
823
+	}
824
+
825
+
826
+	/**
827
+	 * Updates the internal cached _has_activated_messengers_and_message_types property with the given messenger
828
+	 * and message type.
829
+	 *
830
+	 * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
831
+	 *
832
+	 * @access protected
833
+	 * @param \EE_messenger $messenger
834
+	 * @param string        $message_type_name
835
+	 */
836
+	protected function _set_messenger_has_activated_message_type(EE_messenger $messenger, $message_type_name)
837
+	{
838
+
839
+		// if _has_activated_messengers_and_message_types is empty then lets ensure its initialized
840
+		if (empty($this->_has_activated_messengers_and_message_types)) {
841
+			$this->get_has_activated_messengers_option();
842
+		}
843
+
844
+		// make sure this messenger has a record in the has_activated array
845
+		if (! isset($this->_has_activated_messengers_and_message_types[ $messenger->name ])) {
846
+			$this->_has_activated_messengers_and_message_types[ $messenger->name ] = array();
847
+		}
848
+		// check if message type has already been added
849
+		if (! in_array($message_type_name, $this->_has_activated_messengers_and_message_types[ $messenger->name ])) {
850
+			$this->_has_activated_messengers_and_message_types[ $messenger->name ][] = $message_type_name;
851
+		}
852
+	}
853
+
854
+
855
+	/**
856
+	 * add_settings_for_messenger
857
+	 * NOTE This does NOT automatically persist any settings to the db.  Client code should call
858
+	 * $this->update_active_messengers_option to persist.
859
+	 *
860
+	 * @param string $messenger_name The name of the messenger the settings is being added for.
861
+	 * @param array  $new_settings   An array of settings to update the existing settings.
862
+	 */
863
+	public function add_settings_for_messenger($messenger_name, $new_settings = array())
864
+	{
865
+		$messenger = $this->get_messenger($messenger_name);
866
+		if ($messenger instanceof EE_messenger) {
867
+			$msgr_settings = $messenger->get_admin_settings_fields();
868
+			if (! empty($msgr_settings)) {
869
+				foreach ($msgr_settings as $field => $value) {
870
+					// is there a new setting for this?
871
+					if (isset($new_settings[ $field ])) {
872
+						$this->_active_message_types[ $messenger->name ]['settings'][ $field ] = $new_settings[ $field ];
873
+						continue;
874
+					}
875
+					// only set the default if it isn't already set.
876
+					if (! isset($this->_active_message_types[ $messenger->name ]['settings'][ $field ])) {
877
+						$this->_active_message_types[ $messenger->name ]['settings'][ $field ] = $value;
878
+					}
879
+				}
880
+			}
881
+		}
882
+	}
883
+
884
+
885
+	/**
886
+	 * deactivate_messenger
887
+	 *
888
+	 * @param  string|EE_messenger $messenger_name name of messenger
889
+	 * @return void
890
+	 */
891
+	public function deactivate_messenger($messenger_name)
892
+	{
893
+		$this->_initialize_collections();
894
+		if ($messenger_name instanceof EE_messenger) {
895
+			$messenger_name = $messenger_name->name;
896
+		}
897
+		unset($this->_active_messengers[ $messenger_name ]);
898
+		unset($this->_active_message_types[ $messenger_name ]);
899
+		$this->_message_template_group_model->deactivate_message_template_groups_for($messenger_name);
900
+		$this->update_active_messengers_option();
901
+	}
902
+
903
+
904
+	/**
905
+	 * Deactivates a message type (note this will deactivate across all messenger's it is active on.
906
+	 *
907
+	 * @param  string $message_type_name     name of message type being deactivated
908
+	 * @param bool    $set_has_active_record By default we always record the has_active record when deactivating a message
909
+	 *                                       type.  However, this can be overridden if we don't want this set (usually when
910
+	 *                                       this is called as a part of deregistration of a custom message type)
911
+	 */
912
+	public function deactivate_message_type($message_type_name, $set_has_active_record = true)
913
+	{
914
+		$this->_initialize_collections();
915
+		if ($message_type_name instanceof EE_message_type) {
916
+			$message_type_name = $message_type_name->name;
917
+		}
918
+		foreach ($this->_active_message_types as $messenger_name => $settings) {
919
+			unset(
920
+				$this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]
921
+			);
922
+
923
+			// we always record (even on deactivation) that a message type has been activated because there should at
924
+			// least be a record in the "has_activated" option that it WAS active at one point.
925
+			if ($set_has_active_record) {
926
+				$messenger = $this->get_messenger($messenger_name);
927
+				$this->_set_messenger_has_activated_message_type($messenger, $message_type_name);
928
+			}
929
+		}
930
+		$this->_message_template_group_model->deactivate_message_template_groups_for('', $message_type_name);
931
+		$this->update_active_messengers_option();
932
+		$this->update_has_activated_messengers_option();
933
+	}
934
+
935
+
936
+	/**
937
+	 * Deactivates a message type for a specific messenger as opposed to all messengers.
938
+	 *
939
+	 * @param string $message_type_name Name of message type being deactivated.
940
+	 * @param string $messenger_name    Name of messenger the message type is being deactivated for.
941
+	 */
942
+	public function deactivate_message_type_for_messenger($message_type_name, $messenger_name)
943
+	{
944
+		$this->_initialize_collections();
945
+		if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
946
+			unset($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]);
947
+		}
948
+		$this->_message_template_group_model->deactivate_message_template_groups_for(
949
+			array($messenger_name),
950
+			array($message_type_name)
951
+		);
952
+		$this->update_active_messengers_option();
953
+	}
954
+
955
+
956
+	/**
957
+	 * Used to verify if a message can be sent for the given messenger and message type
958
+	 * and that it is a generating messenger (used for generating message templates).
959
+	 *
960
+	 * @param EE_messenger    $messenger    messenger used in trigger
961
+	 * @param EE_message_type $message_type message type used in trigger
962
+	 * @return bool true is a generating messenger and can be sent OR FALSE meaning cannot send.
963
+	 */
964
+	public function is_generating_messenger_and_active(EE_messenger $messenger, EE_message_type $message_type)
965
+	{
966
+		// get the $messengers the message type says it can be used with.
967
+		foreach ($message_type->with_messengers() as $generating_messenger => $secondary_messengers) {
968
+			if ($messenger->name === $generating_messenger
969
+				&& $this->is_message_type_active_for_messenger($messenger->name, $message_type->name)
970
+			) {
971
+				return true;
972
+			}
973
+		}
974
+		return false;
975
+	}
976
+
977
+
978
+	/**
979
+	 * This returns all the contexts that are registered by all message types.
980
+	 * If $slugs_only is true,
981
+	 * then just an array indexed by unique context slugs with the latest label representation for that slug.
982
+	 * array(
983
+	 *      'context_slug' => 'localized label for context obtained from latest message type in the loop'.
984
+	 * );
985
+	 * If $slugs_only is false, then the format is:
986
+	 * array(
987
+	 *      'message_type_name' => array(
988
+	 *          'context_slug' => array(
989
+	 *              'label' => 'localized label for context',
990
+	 *              'description' => 'localized description for context'
991
+	 *          )
992
+	 *      )
993
+	 * );
994
+	 * Keep in mind that although different message types may share the same context slugs,
995
+	 * it is possible that the context is described differently by the message type.
996
+	 *
997
+	 * @since 4.9.0
998
+	 * @param   bool $slugs_only Whether to return an array of just slugs and labels (true)
999
+	 *                           or all contexts indexed by message type.
1000
+	 * @return array
1001
+	 */
1002
+	public function get_all_contexts($slugs_only = true)
1003
+	{
1004
+		$key = $slugs_only ? 'slugs' : 'all';
1005
+		// check if contexts has been setup yet.
1006
+		if (empty($this->_contexts[ $key ])) {
1007
+			// So let's get all active message type objects and loop through to get all unique contexts
1008
+			foreach ($this->get_active_message_type_objects() as $message_type) {
1009
+				if ($message_type instanceof EE_message_type) {
1010
+					$message_type_contexts = $message_type->get_contexts();
1011
+					if ($slugs_only) {
1012
+						foreach ($message_type_contexts as $context => $context_details) {
1013
+							$this->_contexts[ $key ][ $context ] = $context_details['label'];
1014
+						}
1015
+					} else {
1016
+						$this->_contexts[ $key ][ $message_type->name ] = $message_type_contexts;
1017
+					}
1018
+				}
1019
+			}
1020
+		}
1021
+		return ! empty($this->_contexts[ $key ]) ? $this->_contexts[ $key ] : array();
1022
+	}
1023
+
1024
+
1025
+	/**
1026
+	 * This checks the internal record of what message types are considered "active" and verifies that
1027
+	 * there is an installed class definition for that message type.  If the active message type does not have a
1028
+	 * corresponding accessible message type class then it will be deactivated from all messengers it is active on and
1029
+	 * any related message templates will be inactivated as well.
1030
+	 *
1031
+	 * @return bool   true means all active message types are valid, false means at least one message type was
1032
+	 *                deactivated.
1033
+	 */
1034
+	public function validate_active_message_types_are_installed()
1035
+	{
1036
+		$list_of_active_message_type_names = $this->list_of_active_message_types();
1037
+		$installed_message_types           = $this->installed_message_types();
1038
+		$all_message_types_valid           = true;
1039
+		// loop through list of active message types and verify they are installed.
1040
+		foreach ($list_of_active_message_type_names as $message_type_name) {
1041
+			if (! isset($installed_message_types[ $message_type_name ])) {
1042
+				$this->remove_message_type_has_been_activated_from_all_messengers(
1043
+					$message_type_name,
1044
+					true
1045
+				);
1046
+				$this->deactivate_message_type($message_type_name, false);
1047
+				$all_message_types_valid = false;
1048
+			}
1049
+		}
1050
+		return $all_message_types_valid;
1051
+	}
1052
+
1053
+
1054
+	/**
1055
+	 * This method checks the `ee_has_activated_messenger` option to see if the message type has ever been
1056
+	 * activated for the given messenger.  This can be called by client code on plugin updates etc to determine whether
1057
+	 * to attempt automatically reactivating message types that should be activated by default or not.
1058
+	 *
1059
+	 * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
1060
+	 *
1061
+	 * @param $message_type_name
1062
+	 * @param $messenger_name
1063
+	 * @return bool
1064
+	 */
1065
+	public function has_message_type_been_activated_for_messenger($message_type_name, $messenger_name)
1066
+	{
1067
+		$has_activated = $this->get_has_activated_messengers_option();
1068
+		return isset($has_activated[ $messenger_name ])
1069
+			   && in_array($message_type_name, $has_activated[ $messenger_name ]);
1070
+	}
1071
+
1072
+
1073
+	/**
1074
+	 * This method unsets a message type from the given messenger has activated option.
1075
+	 *
1076
+	 * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
1077
+	 *
1078
+	 * @param string $message_type_name
1079
+	 * @param string $messenger_name
1080
+	 * @param bool   $consider_current_state  Whether to consider whether the  message type is currently active or not.
1081
+	 *                                        If it is currently active, then remove.  Otherwise leave it alone.
1082
+	 */
1083
+	public function remove_message_type_has_been_activated_for_messenger(
1084
+		$message_type_name,
1085
+		$messenger_name,
1086
+		$consider_current_state = false
1087
+	) {
1088
+		if ($consider_current_state
1089
+			&& ! $this->is_message_type_active_for_messenger($messenger_name, $message_type_name)
1090
+		) {
1091
+			// when consider current state is true, this means we don't want to change anything on the "has_activated"
1092
+			// record if the message type is currently active for this messenger.  This is used when we want to retain
1093
+			// the record for user initiated inactivations of the message type.
1094
+			return;
1095
+		}
1096
+		$has_activated = $this->get_has_activated_messengers_option();
1097
+		$key_for_message_type = isset($has_activated[ $messenger_name ])
1098
+			? array_search($message_type_name, $has_activated[ $messenger_name ], true)
1099
+			: false;
1100
+		if ($key_for_message_type !== false) {
1101
+			unset($has_activated[ $messenger_name ][ $key_for_message_type ]);
1102
+			$this->update_has_activated_messengers_option($has_activated);
1103
+			// reset the internal cached property
1104
+			$this->get_has_activated_messengers_option(true);
1105
+		}
1106
+	}
1107
+
1108
+
1109
+	/**
1110
+	 * Removes a message type active record from all messengers it is attached to.
1111
+	 *
1112
+	 * @see phpdocs on EE_Message_Resource_Manager::HAS_ACTIVATED_MESSAGE_TYPE_FOR_MESSENGER_OPTION_NAME for more details.
1113
+	 *
1114
+	 * @param      $message_type_name
1115
+	 * @param bool $consider_current_state  Whether to consider whether the  message type is currently active or not.
1116
+	 *                                      If it is currently active, then remove.  Otherwise leave it alone.
1117
+	 */
1118
+	public function remove_message_type_has_been_activated_from_all_messengers(
1119
+		$message_type_name,
1120
+		$consider_current_state = false
1121
+	) {
1122
+		foreach (array_keys($this->get_has_activated_messengers_option()) as $messenger_name) {
1123
+			$this->remove_message_type_has_been_activated_for_messenger(
1124
+				$message_type_name,
1125
+				$messenger_name,
1126
+				$consider_current_state
1127
+			);
1128
+		}
1129
+	}
1130 1130
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
     public function get_active_messenger($messenger)
197 197
     {
198 198
         $this->_initialize_collections();
199
-        return ! empty($this->_active_messengers[ $messenger ]) ? $this->_active_messengers[ $messenger ] : null;
199
+        return ! empty($this->_active_messengers[$messenger]) ? $this->_active_messengers[$messenger] : null;
200 200
     }
201 201
 
202 202
 
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
             $this->_installed_messengers = array();
210 210
             $this->messenger_collection()->rewind();
211 211
             while ($this->messenger_collection()->valid()) {
212
-                $this->_installed_messengers[ $this->messenger_collection()->current()->name ] = $this->messenger_collection()->current();
212
+                $this->_installed_messengers[$this->messenger_collection()->current()->name] = $this->messenger_collection()->current();
213 213
                 $this->messenger_collection()->next();
214 214
             }
215 215
         }
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
     public function is_message_type_active_for_messenger($messenger_name, $message_type_name)
293 293
     {
294 294
         $this->_initialize_collections();
295
-        return ! empty($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]);
295
+        return ! empty($this->_active_message_types[$messenger_name]['settings'][$messenger_name.'-message_types'][$message_type_name]);
296 296
     }
297 297
 
298 298
 
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
     public function is_messenger_active($messenger_name)
306 306
     {
307 307
         $this->_initialize_collections();
308
-        return ! empty($this->_active_message_types[ $messenger_name ]);
308
+        return ! empty($this->_active_message_types[$messenger_name]);
309 309
     }
310 310
 
311 311
 
@@ -320,8 +320,8 @@  discard block
 block discarded – undo
320 320
     {
321 321
         $settings = array();
322 322
         if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
323
-            $settings = isset($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings'])
324
-                ? $this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings']
323
+            $settings = isset($this->_active_message_types[$messenger_name]['settings'][$messenger_name.'-message_types'][$message_type_name]['settings'])
324
+                ? $this->_active_message_types[$messenger_name]['settings'][$messenger_name.'-message_types'][$message_type_name]['settings']
325 325
                 : array();
326 326
         }
327 327
         return $settings;
@@ -339,8 +339,8 @@  discard block
 block discarded – undo
339 339
     {
340 340
         $this->_initialize_collections();
341 341
         return
342
-            ! empty($this->_active_message_types[ $messenger_name ])
343
-            && ! empty($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ]);
342
+            ! empty($this->_active_message_types[$messenger_name])
343
+            && ! empty($this->_active_message_types[$messenger_name]['settings'][$messenger_name.'-message_types']);
344 344
     }
345 345
 
346 346
 
@@ -355,13 +355,13 @@  discard block
 block discarded – undo
355 355
     public function get_active_message_types_for_messenger($messenger_name)
356 356
     {
357 357
         $message_types = array();
358
-        if (! $this->messenger_has_active_message_types($messenger_name)) {
358
+        if ( ! $this->messenger_has_active_message_types($messenger_name)) {
359 359
             return $message_types;
360 360
         }
361 361
         $installed_message_types = $this->installed_message_types();
362 362
         foreach ($installed_message_types as $message_type_name => $message_type) {
363 363
             if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
364
-                $message_types[ $message_type_name ] = $message_type;
364
+                $message_types[$message_type_name] = $message_type;
365 365
             }
366 366
         }
367 367
         return $message_types;
@@ -380,11 +380,11 @@  discard block
 block discarded – undo
380 380
         $active_message_type_names = array();
381 381
         $this->_initialize_collections();
382 382
         foreach ($this->_active_message_types as $messenger => $messenger_settings) {
383
-            if (! isset($messenger_settings['settings'][ $messenger . '-message_types' ])) {
383
+            if ( ! isset($messenger_settings['settings'][$messenger.'-message_types'])) {
384 384
                 continue;
385 385
             }
386
-            foreach ($messenger_settings['settings'][ $messenger . '-message_types' ] as $message_type_name => $message_type_config) {
387
-                if (! in_array($message_type_name, $active_message_type_names)) {
386
+            foreach ($messenger_settings['settings'][$messenger.'-message_types'] as $message_type_name => $message_type_config) {
387
+                if ( ! in_array($message_type_name, $active_message_type_names)) {
388 388
                     $active_message_type_names[] = $message_type_name;
389 389
                 }
390 390
             }
@@ -405,8 +405,8 @@  discard block
 block discarded – undo
405 405
         $installed_message_types   = $this->installed_message_types();
406 406
         $active_message_type_names = $this->list_of_active_message_types();
407 407
         foreach ($active_message_type_names as $active_message_type_name) {
408
-            if (isset($installed_message_types[ $active_message_type_name ])) {
409
-                $active_message_types[ $active_message_type_name ] = $installed_message_types[ $active_message_type_name ];
408
+            if (isset($installed_message_types[$active_message_type_name])) {
409
+                $active_message_types[$active_message_type_name] = $installed_message_types[$active_message_type_name];
410 410
             }
411 411
         }
412 412
         return $active_message_types;
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
         if (empty($this->_installed_message_types)) {
422 422
             $this->message_type_collection()->rewind();
423 423
             while ($this->message_type_collection()->valid()) {
424
-                $this->_installed_message_types[ $this->message_type_collection()->current()->name ] = $this->message_type_collection()->current();
424
+                $this->_installed_message_types[$this->message_type_collection()->current()->name] = $this->message_type_collection()->current();
425 425
                 $this->message_type_collection()->next();
426 426
             }
427 427
         }
@@ -460,7 +460,7 @@  discard block
 block discarded – undo
460 460
     public function valid_message_type_for_messenger(EE_messenger $messenger, $message_type_name)
461 461
     {
462 462
         $valid_message_types = $messenger->get_valid_message_types();
463
-        if (! in_array($message_type_name, $valid_message_types)) {
463
+        if ( ! in_array($message_type_name, $valid_message_types)) {
464 464
             throw new EE_Error(
465 465
                 sprintf(
466 466
                     __(
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
      */
587 587
     public function ensure_messenger_is_active($messenger_name, $update_option = true)
588 588
     {
589
-        if (! isset($this->_active_messengers[ $messenger_name ])) {
589
+        if ( ! isset($this->_active_messengers[$messenger_name])) {
590 590
             try {
591 591
                 $this->activate_messenger($messenger_name, array(), $update_option);
592 592
             } catch (EE_Error $e) {
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
             $this->ensure_messenger_is_active($messenger_name, $update_option);
632 632
         }
633 633
 
634
-        if (! empty($not_installed)) {
634
+        if ( ! empty($not_installed)) {
635 635
             EE_Error::add_error(
636 636
                 sprintf(
637 637
                     __('The following messengers are either not installed or are invalid:%1$s %2$s', 'event_espresso'),
@@ -664,7 +664,7 @@  discard block
 block discarded – undo
664 664
             // ensure messenger is active (that's an inherent coupling between active message types and the
665 665
             // messenger they are being activated for.
666 666
             try {
667
-                if (! $this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
667
+                if ( ! $this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
668 668
                     // all is good so let's just get it active
669 669
                     $this->activate_messenger($messenger, array($message_type_name), $update_option);
670 670
                 }
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
             : $this->messenger_collection()->get_by_info($messenger);
729 729
         // it's inactive. Activate it.
730 730
         if ($messenger instanceof EE_messenger) {
731
-            $this->_active_messengers[ $messenger->name ] = $messenger;
731
+            $this->_active_messengers[$messenger->name] = $messenger;
732 732
             // activate incoming message types set to be activated with messenger.
733 733
             $message_type_names = $this->_activate_message_types($messenger, $message_type_names);
734 734
             // setup any initial settings for the messenger if necessary.
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
             // generate new templates if necessary and ensure all related templates that are already in the database are
741 741
             // marked active.  Note, this will also deactivate a message type for a messenger if the template
742 742
             // cannot be successfully created during its attempt (only happens for global template attempts).
743
-            if (! empty($message_type_names)) {
743
+            if ( ! empty($message_type_names)) {
744 744
                 $templates = EEH_MSG_Template::generate_new_templates($messenger->name, $message_type_names, 0, true);
745 745
                 EEH_MSG_Template::update_to_active(array($messenger->name), $message_type_names);
746 746
             }
@@ -764,13 +764,13 @@  discard block
 block discarded – undo
764 764
         // things have never been initialized (which should happen on EEH_Activation::generate_message_templates).
765 765
         // So ONLY then do we need to actually grab defaults and cycle through them.  Otherwise we
766 766
         // only override _active_message_types when an explicit array of $message_type_names has been provided.
767
-        $message_type_names = empty($message_type_names) && ! isset($this->_active_message_types[ $messenger->name ])
767
+        $message_type_names = empty($message_type_names) && ! isset($this->_active_message_types[$messenger->name])
768 768
             ? $messenger->get_default_message_types()
769 769
             : (array) $message_type_names;
770 770
 
771 771
         // now we ALWAYS need to make sure that the messenger is active for the message types we're activating!
772
-        if (! isset($this->_active_message_types[ $messenger->name ])) {
773
-            $this->_active_message_types[ $messenger->name ]['settings'] = array();
772
+        if ( ! isset($this->_active_message_types[$messenger->name])) {
773
+            $this->_active_message_types[$messenger->name]['settings'] = array();
774 774
         }
775 775
 
776 776
         if ($message_type_names) {
@@ -778,7 +778,7 @@  discard block
 block discarded – undo
778 778
             foreach ($message_type_names as $message_type_name) {
779 779
                 // only register the message type as active IF it isn't already active
780 780
                 // and if its actually installed.
781
-                if (! $this->is_message_type_active_for_messenger($messenger->name, $message_type_name)
781
+                if ( ! $this->is_message_type_active_for_messenger($messenger->name, $message_type_name)
782 782
                 ) {
783 783
                     $this->add_settings_for_message_type($messenger->name, $message_type_name);
784 784
                     $this->_set_messenger_has_activated_message_type(
@@ -810,16 +810,16 @@  discard block
 block discarded – undo
810 810
         if ($message_type instanceof EE_message_type) {
811 811
             $default_settings = $message_type->get_admin_settings_fields();
812 812
             foreach ($default_settings as $field => $values) {
813
-                if (isset($new_settings[ $field ])) {
814
-                    $existing_settings[ $field ] = $new_settings[ $field ];
813
+                if (isset($new_settings[$field])) {
814
+                    $existing_settings[$field] = $new_settings[$field];
815 815
                     continue;
816 816
                 }
817
-                if (! isset($existing_settings[ $field ])) {
818
-                    $existing_settings[ $field ] = $values['default'];
817
+                if ( ! isset($existing_settings[$field])) {
818
+                    $existing_settings[$field] = $values['default'];
819 819
                 }
820 820
             }
821 821
         }
822
-        $this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]['settings'] = $existing_settings;
822
+        $this->_active_message_types[$messenger_name]['settings'][$messenger_name.'-message_types'][$message_type_name]['settings'] = $existing_settings;
823 823
     }
824 824
 
825 825
 
@@ -842,12 +842,12 @@  discard block
 block discarded – undo
842 842
         }
843 843
 
844 844
         // make sure this messenger has a record in the has_activated array
845
-        if (! isset($this->_has_activated_messengers_and_message_types[ $messenger->name ])) {
846
-            $this->_has_activated_messengers_and_message_types[ $messenger->name ] = array();
845
+        if ( ! isset($this->_has_activated_messengers_and_message_types[$messenger->name])) {
846
+            $this->_has_activated_messengers_and_message_types[$messenger->name] = array();
847 847
         }
848 848
         // check if message type has already been added
849
-        if (! in_array($message_type_name, $this->_has_activated_messengers_and_message_types[ $messenger->name ])) {
850
-            $this->_has_activated_messengers_and_message_types[ $messenger->name ][] = $message_type_name;
849
+        if ( ! in_array($message_type_name, $this->_has_activated_messengers_and_message_types[$messenger->name])) {
850
+            $this->_has_activated_messengers_and_message_types[$messenger->name][] = $message_type_name;
851 851
         }
852 852
     }
853 853
 
@@ -865,16 +865,16 @@  discard block
 block discarded – undo
865 865
         $messenger = $this->get_messenger($messenger_name);
866 866
         if ($messenger instanceof EE_messenger) {
867 867
             $msgr_settings = $messenger->get_admin_settings_fields();
868
-            if (! empty($msgr_settings)) {
868
+            if ( ! empty($msgr_settings)) {
869 869
                 foreach ($msgr_settings as $field => $value) {
870 870
                     // is there a new setting for this?
871
-                    if (isset($new_settings[ $field ])) {
872
-                        $this->_active_message_types[ $messenger->name ]['settings'][ $field ] = $new_settings[ $field ];
871
+                    if (isset($new_settings[$field])) {
872
+                        $this->_active_message_types[$messenger->name]['settings'][$field] = $new_settings[$field];
873 873
                         continue;
874 874
                     }
875 875
                     // only set the default if it isn't already set.
876
-                    if (! isset($this->_active_message_types[ $messenger->name ]['settings'][ $field ])) {
877
-                        $this->_active_message_types[ $messenger->name ]['settings'][ $field ] = $value;
876
+                    if ( ! isset($this->_active_message_types[$messenger->name]['settings'][$field])) {
877
+                        $this->_active_message_types[$messenger->name]['settings'][$field] = $value;
878 878
                     }
879 879
                 }
880 880
             }
@@ -894,8 +894,8 @@  discard block
 block discarded – undo
894 894
         if ($messenger_name instanceof EE_messenger) {
895 895
             $messenger_name = $messenger_name->name;
896 896
         }
897
-        unset($this->_active_messengers[ $messenger_name ]);
898
-        unset($this->_active_message_types[ $messenger_name ]);
897
+        unset($this->_active_messengers[$messenger_name]);
898
+        unset($this->_active_message_types[$messenger_name]);
899 899
         $this->_message_template_group_model->deactivate_message_template_groups_for($messenger_name);
900 900
         $this->update_active_messengers_option();
901 901
     }
@@ -917,7 +917,7 @@  discard block
 block discarded – undo
917 917
         }
918 918
         foreach ($this->_active_message_types as $messenger_name => $settings) {
919 919
             unset(
920
-                $this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]
920
+                $this->_active_message_types[$messenger_name]['settings'][$messenger_name.'-message_types'][$message_type_name]
921 921
             );
922 922
 
923 923
             // we always record (even on deactivation) that a message type has been activated because there should at
@@ -943,7 +943,7 @@  discard block
 block discarded – undo
943 943
     {
944 944
         $this->_initialize_collections();
945 945
         if ($this->is_message_type_active_for_messenger($messenger_name, $message_type_name)) {
946
-            unset($this->_active_message_types[ $messenger_name ]['settings'][ $messenger_name . '-message_types' ][ $message_type_name ]);
946
+            unset($this->_active_message_types[$messenger_name]['settings'][$messenger_name.'-message_types'][$message_type_name]);
947 947
         }
948 948
         $this->_message_template_group_model->deactivate_message_template_groups_for(
949 949
             array($messenger_name),
@@ -1003,22 +1003,22 @@  discard block
 block discarded – undo
1003 1003
     {
1004 1004
         $key = $slugs_only ? 'slugs' : 'all';
1005 1005
         // check if contexts has been setup yet.
1006
-        if (empty($this->_contexts[ $key ])) {
1006
+        if (empty($this->_contexts[$key])) {
1007 1007
             // So let's get all active message type objects and loop through to get all unique contexts
1008 1008
             foreach ($this->get_active_message_type_objects() as $message_type) {
1009 1009
                 if ($message_type instanceof EE_message_type) {
1010 1010
                     $message_type_contexts = $message_type->get_contexts();
1011 1011
                     if ($slugs_only) {
1012 1012
                         foreach ($message_type_contexts as $context => $context_details) {
1013
-                            $this->_contexts[ $key ][ $context ] = $context_details['label'];
1013
+                            $this->_contexts[$key][$context] = $context_details['label'];
1014 1014
                         }
1015 1015
                     } else {
1016
-                        $this->_contexts[ $key ][ $message_type->name ] = $message_type_contexts;
1016
+                        $this->_contexts[$key][$message_type->name] = $message_type_contexts;
1017 1017
                     }
1018 1018
                 }
1019 1019
             }
1020 1020
         }
1021
-        return ! empty($this->_contexts[ $key ]) ? $this->_contexts[ $key ] : array();
1021
+        return ! empty($this->_contexts[$key]) ? $this->_contexts[$key] : array();
1022 1022
     }
1023 1023
 
1024 1024
 
@@ -1038,7 +1038,7 @@  discard block
 block discarded – undo
1038 1038
         $all_message_types_valid           = true;
1039 1039
         // loop through list of active message types and verify they are installed.
1040 1040
         foreach ($list_of_active_message_type_names as $message_type_name) {
1041
-            if (! isset($installed_message_types[ $message_type_name ])) {
1041
+            if ( ! isset($installed_message_types[$message_type_name])) {
1042 1042
                 $this->remove_message_type_has_been_activated_from_all_messengers(
1043 1043
                     $message_type_name,
1044 1044
                     true
@@ -1065,8 +1065,8 @@  discard block
 block discarded – undo
1065 1065
     public function has_message_type_been_activated_for_messenger($message_type_name, $messenger_name)
1066 1066
     {
1067 1067
         $has_activated = $this->get_has_activated_messengers_option();
1068
-        return isset($has_activated[ $messenger_name ])
1069
-               && in_array($message_type_name, $has_activated[ $messenger_name ]);
1068
+        return isset($has_activated[$messenger_name])
1069
+               && in_array($message_type_name, $has_activated[$messenger_name]);
1070 1070
     }
1071 1071
 
1072 1072
 
@@ -1094,11 +1094,11 @@  discard block
 block discarded – undo
1094 1094
             return;
1095 1095
         }
1096 1096
         $has_activated = $this->get_has_activated_messengers_option();
1097
-        $key_for_message_type = isset($has_activated[ $messenger_name ])
1098
-            ? array_search($message_type_name, $has_activated[ $messenger_name ], true)
1097
+        $key_for_message_type = isset($has_activated[$messenger_name])
1098
+            ? array_search($message_type_name, $has_activated[$messenger_name], true)
1099 1099
             : false;
1100 1100
         if ($key_for_message_type !== false) {
1101
-            unset($has_activated[ $messenger_name ][ $key_for_message_type ]);
1101
+            unset($has_activated[$messenger_name][$key_for_message_type]);
1102 1102
             $this->update_has_activated_messengers_option($has_activated);
1103 1103
             // reset the internal cached property
1104 1104
             $this->get_has_activated_messengers_option(true);
Please login to merge, or discard this patch.
core/domain/DomainFactory.php 2 patches
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -23,62 +23,62 @@
 block discarded – undo
23 23
 class DomainFactory
24 24
 {
25 25
 
26
-    /**
27
-     * @param FullyQualifiedName $domain_fqcn   [required] Fully Qualified Class Name for the Domain class
28
-     * @param array $arguments                  [required] array of arguments to be passed to the Domain class
29
-     *                                          constructor. Must at least include the following two value objects:
30
-     *                                          array(
31
-     *                                              EventEspresso\core\domain\values\FilePath $plugin_file
32
-     *                                              EventEspresso\core\domain\values\Version $version
33
-     *                                          )
34
-     * @return DomainInterface
35
-     * @throws DomainException
36
-     * @throws InvalidArgumentException
37
-     * @throws InvalidDataTypeException
38
-     * @throws InvalidInterfaceException
39
-     */
40
-    public static function getShared(FullyQualifiedName $domain_fqcn, array $arguments)
41
-    {
42
-        if (! isset($arguments[0], $arguments[1])) {
43
-            throw new InvalidArgumentException(
44
-                esc_html__(
45
-                    'You need to pass at least two arguments, representing the addon plugin file and version, in order to generate a Domain class',
46
-                    'event_espresso'
47
-                )
48
-            );
49
-        }
50
-        /** @var DomainInterface $domain */
51
-        $domain = LoaderFactory::getLoader()->getShared($domain_fqcn, $arguments);
52
-        if (! $domain instanceof $domain_fqcn && ! $domain instanceof DomainBase) {
53
-            throw new DomainException(
54
-                sprintf(
55
-                    esc_html__(
56
-                        'The requested Domain class "%1$s" could not be loaded.',
57
-                        'event_espresso'
58
-                    ),
59
-                    $domain_fqcn
60
-                )
61
-            );
62
-        }
63
-        return $domain;
64
-    }
26
+	/**
27
+	 * @param FullyQualifiedName $domain_fqcn   [required] Fully Qualified Class Name for the Domain class
28
+	 * @param array $arguments                  [required] array of arguments to be passed to the Domain class
29
+	 *                                          constructor. Must at least include the following two value objects:
30
+	 *                                          array(
31
+	 *                                              EventEspresso\core\domain\values\FilePath $plugin_file
32
+	 *                                              EventEspresso\core\domain\values\Version $version
33
+	 *                                          )
34
+	 * @return DomainInterface
35
+	 * @throws DomainException
36
+	 * @throws InvalidArgumentException
37
+	 * @throws InvalidDataTypeException
38
+	 * @throws InvalidInterfaceException
39
+	 */
40
+	public static function getShared(FullyQualifiedName $domain_fqcn, array $arguments)
41
+	{
42
+		if (! isset($arguments[0], $arguments[1])) {
43
+			throw new InvalidArgumentException(
44
+				esc_html__(
45
+					'You need to pass at least two arguments, representing the addon plugin file and version, in order to generate a Domain class',
46
+					'event_espresso'
47
+				)
48
+			);
49
+		}
50
+		/** @var DomainInterface $domain */
51
+		$domain = LoaderFactory::getLoader()->getShared($domain_fqcn, $arguments);
52
+		if (! $domain instanceof $domain_fqcn && ! $domain instanceof DomainBase) {
53
+			throw new DomainException(
54
+				sprintf(
55
+					esc_html__(
56
+						'The requested Domain class "%1$s" could not be loaded.',
57
+						'event_espresso'
58
+					),
59
+					$domain_fqcn
60
+				)
61
+			);
62
+		}
63
+		return $domain;
64
+	}
65 65
 
66 66
 
67
-    /**
68
-     * @return Domain
69
-     * @throws DomainException
70
-     * @throws InvalidArgumentException
71
-     * @throws InvalidDataTypeException
72
-     * @throws InvalidFilePathException
73
-     * @throws InvalidInterfaceException
74
-     */
75
-    public static function getEventEspressoCoreDomain()
76
-    {
77
-        $domain = new Domain(
78
-            new FilePath(EVENT_ESPRESSO_MAIN_FILE),
79
-            Version::fromString(espresso_version())
80
-        );
81
-        LoaderFactory::getLoader()->share('EventEspresso\core\domain\Domain', $domain);
82
-        return $domain;
83
-    }
67
+	/**
68
+	 * @return Domain
69
+	 * @throws DomainException
70
+	 * @throws InvalidArgumentException
71
+	 * @throws InvalidDataTypeException
72
+	 * @throws InvalidFilePathException
73
+	 * @throws InvalidInterfaceException
74
+	 */
75
+	public static function getEventEspressoCoreDomain()
76
+	{
77
+		$domain = new Domain(
78
+			new FilePath(EVENT_ESPRESSO_MAIN_FILE),
79
+			Version::fromString(espresso_version())
80
+		);
81
+		LoaderFactory::getLoader()->share('EventEspresso\core\domain\Domain', $domain);
82
+		return $domain;
83
+	}
84 84
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
      */
40 40
     public static function getShared(FullyQualifiedName $domain_fqcn, array $arguments)
41 41
     {
42
-        if (! isset($arguments[0], $arguments[1])) {
42
+        if ( ! isset($arguments[0], $arguments[1])) {
43 43
             throw new InvalidArgumentException(
44 44
                 esc_html__(
45 45
                     'You need to pass at least two arguments, representing the addon plugin file and version, in order to generate a Domain class',
@@ -49,7 +49,7 @@  discard block
 block discarded – undo
49 49
         }
50 50
         /** @var DomainInterface $domain */
51 51
         $domain = LoaderFactory::getLoader()->getShared($domain_fqcn, $arguments);
52
-        if (! $domain instanceof $domain_fqcn && ! $domain instanceof DomainBase) {
52
+        if ( ! $domain instanceof $domain_fqcn && ! $domain instanceof DomainBase) {
53 53
             throw new DomainException(
54 54
                 sprintf(
55 55
                     esc_html__(
Please login to merge, or discard this patch.
core/helpers/EEH_Activation.helper.php 1 patch
Indentation   +1615 added lines, -1615 removed lines patch added patch discarded remove patch
@@ -15,233 +15,233 @@  discard block
 block discarded – undo
15 15
 class EEH_Activation implements ResettableInterface
16 16
 {
17 17
 
18
-    /**
19
-     * constant used to indicate a cron task is no longer in use
20
-     */
21
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
22
-
23
-    /**
24
-     * WP_User->ID
25
-     *
26
-     * @var int
27
-     */
28
-    private static $_default_creator_id;
29
-
30
-    /**
31
-     * indicates whether or not we've already verified core's default data during this request,
32
-     * because after migrations are done, any addons activated while in maintenance mode
33
-     * will want to setup their own default data, and they might hook into core's default data
34
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
35
-     * This prevents doing that for EVERY single addon.
36
-     *
37
-     * @var boolean
38
-     */
39
-    protected static $_initialized_db_content_already_in_this_request = false;
40
-
41
-    /**
42
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
43
-     */
44
-    private static $table_analysis;
45
-
46
-    /**
47
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
48
-     */
49
-    private static $table_manager;
50
-
51
-
52
-    /**
53
-     * @return \EventEspresso\core\services\database\TableAnalysis
54
-     */
55
-    public static function getTableAnalysis()
56
-    {
57
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
58
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
59
-        }
60
-        return self::$table_analysis;
61
-    }
62
-
63
-
64
-    /**
65
-     * @return \EventEspresso\core\services\database\TableManager
66
-     */
67
-    public static function getTableManager()
68
-    {
69
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
70
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
71
-        }
72
-        return self::$table_manager;
73
-    }
74
-
75
-
76
-    /**
77
-     *    _ensure_table_name_has_prefix
78
-     *
79
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
80
-     * @access     public
81
-     * @static
82
-     * @param $table_name
83
-     * @return string
84
-     */
85
-    public static function ensure_table_name_has_prefix($table_name)
86
-    {
87
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88
-    }
89
-
90
-
91
-    /**
92
-     *    system_initialization
93
-     *    ensures the EE configuration settings are loaded with at least default options set
94
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
95
-     *
96
-     * @access public
97
-     * @static
98
-     * @return void
99
-     */
100
-    public static function system_initialization()
101
-    {
102
-        EEH_Activation::reset_and_update_config();
103
-        // which is fired BEFORE activation of plugin anyways
104
-        EEH_Activation::verify_default_pages_exist();
105
-    }
106
-
107
-
108
-    /**
109
-     * Sets the database schema and creates folders. This should
110
-     * be called on plugin activation and reactivation
111
-     *
112
-     * @return boolean success, whether the database and folders are setup properly
113
-     * @throws \EE_Error
114
-     */
115
-    public static function initialize_db_and_folders()
116
-    {
117
-        return EEH_Activation::create_database_tables();
118
-    }
119
-
120
-
121
-    /**
122
-     * assuming we have an up-to-date database schema, this will populate it
123
-     * with default and initial data. This should be called
124
-     * upon activation of a new plugin, reactivation, and at the end
125
-     * of running migration scripts
126
-     *
127
-     * @throws \EE_Error
128
-     */
129
-    public static function initialize_db_content()
130
-    {
131
-        // let's avoid doing all this logic repeatedly, especially when addons are requesting it
132
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
133
-            return;
134
-        }
135
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
136
-
137
-        EEH_Activation::initialize_system_questions();
138
-        EEH_Activation::insert_default_status_codes();
139
-        EEH_Activation::generate_default_message_templates();
140
-        EEH_Activation::create_no_ticket_prices_array();
141
-        EEH_Activation::removeEmailConfirmFromAddressGroup();
142
-
143
-        EEH_Activation::validate_messages_system();
144
-        EEH_Activation::insert_default_payment_methods();
145
-        // in case we've
146
-        EEH_Activation::remove_cron_tasks();
147
-        EEH_Activation::create_cron_tasks();
148
-        // remove all TXN locks since that is being done via extra meta now
149
-        delete_option('ee_locked_transactions');
150
-        // also, check for CAF default db content
151
-        do_action('AHEE__EEH_Activation__initialize_db_content');
152
-        // also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
153
-        // which users really won't care about on initial activation
154
-        EE_Error::overwrite_success();
155
-    }
156
-
157
-
158
-    /**
159
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
160
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
161
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
162
-     * (null)
163
-     *
164
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
165
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
166
-     * @return array
167
-     * @throws \EE_Error
168
-     */
169
-    public static function get_cron_tasks($which_to_include)
170
-    {
171
-        $cron_tasks = apply_filters(
172
-            'FHEE__EEH_Activation__get_cron_tasks',
173
-            array(
174
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
175
-            //              'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
176
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
177
-                // there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
178
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
179
-            )
180
-        );
181
-        if ($which_to_include === 'old') {
182
-            $cron_tasks = array_filter(
183
-                $cron_tasks,
184
-                function ($value) {
185
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
186
-                }
187
-            );
188
-        } elseif ($which_to_include === 'current') {
189
-            $cron_tasks = array_filter($cron_tasks);
190
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
191
-            throw new EE_Error(
192
-                sprintf(
193
-                    __(
194
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
195
-                        'event_espresso'
196
-                    ),
197
-                    $which_to_include
198
-                )
199
-            );
200
-        }
201
-        return $cron_tasks;
202
-    }
203
-
204
-
205
-    /**
206
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
207
-     *
208
-     * @throws \EE_Error
209
-     */
210
-    public static function create_cron_tasks()
211
-    {
212
-
213
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
214
-            if (! wp_next_scheduled($hook_name)) {
215
-                /**
216
-                 * This allows client code to define the initial start timestamp for this schedule.
217
-                 */
218
-                if (is_array($frequency)
219
-                    && count($frequency) === 2
220
-                    && isset($frequency[0], $frequency[1])
221
-                ) {
222
-                    $start_timestamp = $frequency[0];
223
-                    $frequency = $frequency[1];
224
-                } else {
225
-                    $start_timestamp = time();
226
-                }
227
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
228
-            }
229
-        }
230
-    }
231
-
232
-
233
-    /**
234
-     * Remove the currently-existing and now-removed cron tasks.
235
-     *
236
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
237
-     * @throws \EE_Error
238
-     */
239
-    public static function remove_cron_tasks($remove_all = true)
240
-    {
241
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
242
-        $crons                = _get_cron_array();
243
-        $crons                = is_array($crons) ? $crons : array();
244
-        /* reminder of what $crons look like:
18
+	/**
19
+	 * constant used to indicate a cron task is no longer in use
20
+	 */
21
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
22
+
23
+	/**
24
+	 * WP_User->ID
25
+	 *
26
+	 * @var int
27
+	 */
28
+	private static $_default_creator_id;
29
+
30
+	/**
31
+	 * indicates whether or not we've already verified core's default data during this request,
32
+	 * because after migrations are done, any addons activated while in maintenance mode
33
+	 * will want to setup their own default data, and they might hook into core's default data
34
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
35
+	 * This prevents doing that for EVERY single addon.
36
+	 *
37
+	 * @var boolean
38
+	 */
39
+	protected static $_initialized_db_content_already_in_this_request = false;
40
+
41
+	/**
42
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
43
+	 */
44
+	private static $table_analysis;
45
+
46
+	/**
47
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
48
+	 */
49
+	private static $table_manager;
50
+
51
+
52
+	/**
53
+	 * @return \EventEspresso\core\services\database\TableAnalysis
54
+	 */
55
+	public static function getTableAnalysis()
56
+	{
57
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
58
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
59
+		}
60
+		return self::$table_analysis;
61
+	}
62
+
63
+
64
+	/**
65
+	 * @return \EventEspresso\core\services\database\TableManager
66
+	 */
67
+	public static function getTableManager()
68
+	{
69
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
70
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
71
+		}
72
+		return self::$table_manager;
73
+	}
74
+
75
+
76
+	/**
77
+	 *    _ensure_table_name_has_prefix
78
+	 *
79
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
80
+	 * @access     public
81
+	 * @static
82
+	 * @param $table_name
83
+	 * @return string
84
+	 */
85
+	public static function ensure_table_name_has_prefix($table_name)
86
+	{
87
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
88
+	}
89
+
90
+
91
+	/**
92
+	 *    system_initialization
93
+	 *    ensures the EE configuration settings are loaded with at least default options set
94
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
95
+	 *
96
+	 * @access public
97
+	 * @static
98
+	 * @return void
99
+	 */
100
+	public static function system_initialization()
101
+	{
102
+		EEH_Activation::reset_and_update_config();
103
+		// which is fired BEFORE activation of plugin anyways
104
+		EEH_Activation::verify_default_pages_exist();
105
+	}
106
+
107
+
108
+	/**
109
+	 * Sets the database schema and creates folders. This should
110
+	 * be called on plugin activation and reactivation
111
+	 *
112
+	 * @return boolean success, whether the database and folders are setup properly
113
+	 * @throws \EE_Error
114
+	 */
115
+	public static function initialize_db_and_folders()
116
+	{
117
+		return EEH_Activation::create_database_tables();
118
+	}
119
+
120
+
121
+	/**
122
+	 * assuming we have an up-to-date database schema, this will populate it
123
+	 * with default and initial data. This should be called
124
+	 * upon activation of a new plugin, reactivation, and at the end
125
+	 * of running migration scripts
126
+	 *
127
+	 * @throws \EE_Error
128
+	 */
129
+	public static function initialize_db_content()
130
+	{
131
+		// let's avoid doing all this logic repeatedly, especially when addons are requesting it
132
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
133
+			return;
134
+		}
135
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
136
+
137
+		EEH_Activation::initialize_system_questions();
138
+		EEH_Activation::insert_default_status_codes();
139
+		EEH_Activation::generate_default_message_templates();
140
+		EEH_Activation::create_no_ticket_prices_array();
141
+		EEH_Activation::removeEmailConfirmFromAddressGroup();
142
+
143
+		EEH_Activation::validate_messages_system();
144
+		EEH_Activation::insert_default_payment_methods();
145
+		// in case we've
146
+		EEH_Activation::remove_cron_tasks();
147
+		EEH_Activation::create_cron_tasks();
148
+		// remove all TXN locks since that is being done via extra meta now
149
+		delete_option('ee_locked_transactions');
150
+		// also, check for CAF default db content
151
+		do_action('AHEE__EEH_Activation__initialize_db_content');
152
+		// also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
153
+		// which users really won't care about on initial activation
154
+		EE_Error::overwrite_success();
155
+	}
156
+
157
+
158
+	/**
159
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
160
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
161
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
162
+	 * (null)
163
+	 *
164
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
165
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
166
+	 * @return array
167
+	 * @throws \EE_Error
168
+	 */
169
+	public static function get_cron_tasks($which_to_include)
170
+	{
171
+		$cron_tasks = apply_filters(
172
+			'FHEE__EEH_Activation__get_cron_tasks',
173
+			array(
174
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
175
+			//              'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
176
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
177
+				// there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
178
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
179
+			)
180
+		);
181
+		if ($which_to_include === 'old') {
182
+			$cron_tasks = array_filter(
183
+				$cron_tasks,
184
+				function ($value) {
185
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
186
+				}
187
+			);
188
+		} elseif ($which_to_include === 'current') {
189
+			$cron_tasks = array_filter($cron_tasks);
190
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
191
+			throw new EE_Error(
192
+				sprintf(
193
+					__(
194
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
195
+						'event_espresso'
196
+					),
197
+					$which_to_include
198
+				)
199
+			);
200
+		}
201
+		return $cron_tasks;
202
+	}
203
+
204
+
205
+	/**
206
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
207
+	 *
208
+	 * @throws \EE_Error
209
+	 */
210
+	public static function create_cron_tasks()
211
+	{
212
+
213
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
214
+			if (! wp_next_scheduled($hook_name)) {
215
+				/**
216
+				 * This allows client code to define the initial start timestamp for this schedule.
217
+				 */
218
+				if (is_array($frequency)
219
+					&& count($frequency) === 2
220
+					&& isset($frequency[0], $frequency[1])
221
+				) {
222
+					$start_timestamp = $frequency[0];
223
+					$frequency = $frequency[1];
224
+				} else {
225
+					$start_timestamp = time();
226
+				}
227
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
228
+			}
229
+		}
230
+	}
231
+
232
+
233
+	/**
234
+	 * Remove the currently-existing and now-removed cron tasks.
235
+	 *
236
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
237
+	 * @throws \EE_Error
238
+	 */
239
+	public static function remove_cron_tasks($remove_all = true)
240
+	{
241
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
242
+		$crons                = _get_cron_array();
243
+		$crons                = is_array($crons) ? $crons : array();
244
+		/* reminder of what $crons look like:
245 245
          * Top-level keys are timestamps, and their values are arrays.
246 246
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
247 247
          * and their values are arrays.
@@ -258,925 +258,925 @@  discard block
 block discarded – undo
258 258
          *                  ...
259 259
          *      ...
260 260
          */
261
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
262
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
263
-            if (is_array($hooks_to_fire_at_time)) {
264
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
265
-                    if (isset($ee_cron_tasks_to_remove[ $hook_name ])
266
-                        && is_array($ee_cron_tasks_to_remove[ $hook_name ])
267
-                    ) {
268
-                        unset($crons[ $timestamp ][ $hook_name ]);
269
-                    }
270
-                }
271
-                // also take care of any empty cron timestamps.
272
-                if (empty($hooks_to_fire_at_time)) {
273
-                    unset($crons[ $timestamp ]);
274
-                }
275
-            }
276
-        }
277
-        _set_cron_array($crons);
278
-    }
279
-
280
-
281
-    /**
282
-     *    CPT_initialization
283
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
284
-     *
285
-     * @access public
286
-     * @static
287
-     * @return void
288
-     */
289
-    public static function CPT_initialization()
290
-    {
291
-        // register Custom Post Types
292
-        EE_Registry::instance()->load_core('Register_CPTs');
293
-        flush_rewrite_rules();
294
-    }
295
-
296
-
297
-
298
-    /**
299
-     *    reset_and_update_config
300
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
301
-     * If there is old calendar config data saved, then it will get converted on activation.
302
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
303
-     *
304
-     * @access public
305
-     * @static
306
-     * @return void
307
-     */
308
-    public static function reset_and_update_config()
309
-    {
310
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
311
-        add_filter(
312
-            'FHEE__EE_Config___load_core_config__config_settings',
313
-            array('EEH_Activation', 'migrate_old_config_data'),
314
-            10,
315
-            3
316
-        );
317
-        // EE_Config::reset();
318
-        if (! EE_Config::logging_enabled()) {
319
-            delete_option(EE_Config::LOG_NAME);
320
-        }
321
-    }
322
-
323
-
324
-    /**
325
-     *    load_calendar_config
326
-     *
327
-     * @access    public
328
-     * @return    void
329
-     */
330
-    public static function load_calendar_config()
331
-    {
332
-        // grab array of all plugin folders and loop thru it
333
-        $plugins = glob(WP_PLUGIN_DIR . '/*', GLOB_ONLYDIR);
334
-        if (empty($plugins)) {
335
-            return;
336
-        }
337
-        foreach ($plugins as $plugin_path) {
338
-            // grab plugin folder name from path
339
-            $plugin = basename($plugin_path);
340
-            // drill down to Espresso plugins
341
-            // then to calendar related plugins
342
-            if (strpos($plugin, 'espresso') !== false
343
-                || strpos($plugin, 'Espresso') !== false
344
-                || strpos($plugin, 'ee4') !== false
345
-                || strpos($plugin, 'EE4') !== false
346
-                || strpos($plugin, 'calendar') !== false
347
-            ) {
348
-                // this is what we are looking for
349
-                $calendar_config = $plugin_path . '/EE_Calendar_Config.php';
350
-                // does it exist in this folder ?
351
-                if (is_readable($calendar_config)) {
352
-                    // YEAH! let's load it
353
-                    require_once($calendar_config);
354
-                }
355
-            }
356
-        }
357
-    }
358
-
359
-
360
-
361
-    /**
362
-     *    _migrate_old_config_data
363
-     *
364
-     * @access    public
365
-     * @param array|stdClass $settings
366
-     * @param string         $config
367
-     * @param \EE_Config     $EE_Config
368
-     * @return \stdClass
369
-     */
370
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
371
-    {
372
-        $convert_from_array = array('addons');
373
-        // in case old settings were saved as an array
374
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
375
-            // convert existing settings to an object
376
-            $config_array = $settings;
377
-            $settings = new stdClass();
378
-            foreach ($config_array as $key => $value) {
379
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
380
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
381
-                } else {
382
-                    $settings->{$key} = $value;
383
-                }
384
-            }
385
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
386
-        }
387
-        return $settings;
388
-    }
389
-
390
-
391
-    /**
392
-     * deactivate_event_espresso
393
-     *
394
-     * @access public
395
-     * @static
396
-     * @return void
397
-     */
398
-    public static function deactivate_event_espresso()
399
-    {
400
-        // check permissions
401
-        if (current_user_can('activate_plugins')) {
402
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
403
-        }
404
-    }
405
-
406
-
407
-
408
-    /**
409
-     * verify_default_pages_exist
410
-     *
411
-     * @access public
412
-     * @static
413
-     * @return void
414
-     * @throws InvalidDataTypeException
415
-     */
416
-    public static function verify_default_pages_exist()
417
-    {
418
-        $critical_page_problem = false;
419
-        $critical_pages = array(
420
-            array(
421
-                'id'   => 'reg_page_id',
422
-                'name' => __('Registration Checkout', 'event_espresso'),
423
-                'post' => null,
424
-                'code' => 'ESPRESSO_CHECKOUT',
425
-            ),
426
-            array(
427
-                'id'   => 'txn_page_id',
428
-                'name' => __('Transactions', 'event_espresso'),
429
-                'post' => null,
430
-                'code' => 'ESPRESSO_TXN_PAGE',
431
-            ),
432
-            array(
433
-                'id'   => 'thank_you_page_id',
434
-                'name' => __('Thank You', 'event_espresso'),
435
-                'post' => null,
436
-                'code' => 'ESPRESSO_THANK_YOU',
437
-            ),
438
-            array(
439
-                'id'   => 'cancel_page_id',
440
-                'name' => __('Registration Cancelled', 'event_espresso'),
441
-                'post' => null,
442
-                'code' => 'ESPRESSO_CANCELLED',
443
-            ),
444
-        );
445
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
446
-        foreach ($critical_pages as $critical_page) {
447
-            // is critical page ID set in config ?
448
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
449
-                // attempt to find post by ID
450
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
451
-            }
452
-            // no dice?
453
-            if ($critical_page['post'] === null) {
454
-                // attempt to find post by title
455
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
456
-                // still nothing?
457
-                if ($critical_page['post'] === null) {
458
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
459
-                    // REALLY? Still nothing ??!?!?
460
-                    if ($critical_page['post'] === null) {
461
-                        $msg = __(
462
-                            'The Event Espresso critical page configuration settings could not be updated.',
463
-                            'event_espresso'
464
-                        );
465
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
466
-                        break;
467
-                    }
468
-                }
469
-            }
470
-            // check that Post ID matches critical page ID in config
471
-            if (isset($critical_page['post']->ID)
472
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
473
-            ) {
474
-                // update Config with post ID
475
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
476
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
477
-                    $msg = __(
478
-                        'The Event Espresso critical page configuration settings could not be updated.',
479
-                        'event_espresso'
480
-                    );
481
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
482
-                }
483
-            }
484
-            $critical_page_problem =
485
-                ! isset($critical_page['post']->post_status)
486
-                || $critical_page['post']->post_status !== 'publish'
487
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
488
-                    ? true
489
-                    : $critical_page_problem;
490
-        }
491
-        if ($critical_page_problem) {
492
-            new PersistentAdminNotice(
493
-                'critical_page_problem',
494
-                sprintf(
495
-                    esc_html__(
496
-                        'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
497
-                        'event_espresso'
498
-                    ),
499
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
500
-                    . __('Event Espresso Critical Pages Settings', 'event_espresso')
501
-                    . '</a>'
502
-                )
503
-            );
504
-        }
505
-        if (EE_Error::has_notices()) {
506
-            EE_Error::get_notices(false, true, true);
507
-        }
508
-    }
509
-
510
-
511
-
512
-    /**
513
-     * Returns the first post which uses the specified shortcode
514
-     *
515
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
516
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
517
-     *                             "[ESPRESSO_THANK_YOU"
518
-     *                             (we don't search for the closing shortcode bracket because they might have added
519
-     *                             parameter to the shortcode
520
-     * @return WP_Post or NULl
521
-     */
522
-    public static function get_page_by_ee_shortcode($ee_shortcode)
523
-    {
524
-        global $wpdb;
525
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
526
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
527
-        if ($post_id) {
528
-            return get_post($post_id);
529
-        } else {
530
-            return null;
531
-        }
532
-    }
533
-
534
-
535
-    /**
536
-     *    This function generates a post for critical espresso pages
537
-     *
538
-     * @access public
539
-     * @static
540
-     * @param array $critical_page
541
-     * @return array
542
-     */
543
-    public static function create_critical_page($critical_page)
544
-    {
545
-
546
-        $post_args = array(
547
-            'post_title'     => $critical_page['name'],
548
-            'post_status'    => 'publish',
549
-            'post_type'      => 'page',
550
-            'comment_status' => 'closed',
551
-            'post_content'   => '[' . $critical_page['code'] . ']',
552
-        );
553
-
554
-        $post_id = wp_insert_post($post_args);
555
-        if (! $post_id) {
556
-            $msg = sprintf(
557
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
558
-                $critical_page['name']
559
-            );
560
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
561
-            return $critical_page;
562
-        }
563
-        // get newly created post's details
564
-        if (! $critical_page['post'] = get_post($post_id)) {
565
-            $msg = sprintf(
566
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
567
-                $critical_page['name']
568
-            );
569
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
570
-        }
571
-
572
-        return $critical_page;
573
-    }
574
-
575
-
576
-
577
-
578
-    /**
579
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
580
-     * The role being used to check is filterable.
581
-     *
582
-     * @since  4.6.0
583
-     * @global WPDB $wpdb
584
-     * @return mixed null|int WP_user ID or NULL
585
-     */
586
-    public static function get_default_creator_id()
587
-    {
588
-        global $wpdb;
589
-        if (! empty(self::$_default_creator_id)) {
590
-            return self::$_default_creator_id;
591
-        }/**/
592
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
593
-        // 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.
594
-        $pre_filtered_id = apply_filters(
595
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
596
-            false,
597
-            $role_to_check
598
-        );
599
-        if ($pre_filtered_id !== false) {
600
-            return (int) $pre_filtered_id;
601
-        }
602
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
603
-        $query = $wpdb->prepare(
604
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
605
-            '%' . $role_to_check . '%'
606
-        );
607
-        $user_id = $wpdb->get_var($query);
608
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
609
-        if ($user_id && (int) $user_id) {
610
-            self::$_default_creator_id = (int) $user_id;
611
-            return self::$_default_creator_id;
612
-        } else {
613
-            return null;
614
-        }
615
-    }
616
-
617
-
618
-
619
-    /**
620
-     * used by EE and EE addons during plugin activation to create tables.
621
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
622
-     * but includes extra logic regarding activations.
623
-     *
624
-     * @access public
625
-     * @static
626
-     * @param string  $table_name              without the $wpdb->prefix
627
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
628
-     *                                         table query)
629
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
630
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
631
-     *                                         and new once this function is done (ie, you really do want to CREATE a
632
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
633
-     *                                         you just want to verify the table exists and matches this definition
634
-     *                                         (and if it HAS data in it you want to leave it be)
635
-     * @return void
636
-     * @throws EE_Error if there are database errors
637
-     */
638
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
639
-    {
640
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
641
-            return;
642
-        }
643
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
644
-        if (! function_exists('dbDelta')) {
645
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
646
-        }
647
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
648
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
649
-        // do we need to first delete an existing version of this table ?
650
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
651
-            // ok, delete the table... but ONLY if it's empty
652
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
653
-            // table is NOT empty, are you SURE you want to delete this table ???
654
-            if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
655
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
656
-            } elseif (! $deleted_safely) {
657
-                // so we should be more cautious rather than just dropping tables so easily
658
-                error_log(
659
-                    sprintf(
660
-                        __(
661
-                            '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.',
662
-                            'event_espresso'
663
-                        ),
664
-                        $wp_table_name,
665
-                        '<br/>',
666
-                        'espresso_db_update'
667
-                    )
668
-                );
669
-            }
670
-        }
671
-        $engine = str_replace('ENGINE=', '', $engine);
672
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     *    add_column_if_it_doesn't_exist
679
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
680
-     *
681
-     * @access     public
682
-     * @static
683
-     * @deprecated instead use TableManager::addColumn()
684
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
685
-     * @param string $column_name
686
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
687
-     *                            'VARCHAR(10)'
688
-     * @return bool|int
689
-     */
690
-    public static function add_column_if_it_doesnt_exist(
691
-        $table_name,
692
-        $column_name,
693
-        $column_info = 'INT UNSIGNED NOT NULL'
694
-    ) {
695
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
696
-    }
697
-
698
-
699
-    /**
700
-     * get_fields_on_table
701
-     * Gets all the fields on the database table.
702
-     *
703
-     * @access     public
704
-     * @deprecated instead use TableManager::getTableColumns()
705
-     * @static
706
-     * @param string $table_name , without prefixed $wpdb->prefix
707
-     * @return array of database column names
708
-     */
709
-    public static function get_fields_on_table($table_name = null)
710
-    {
711
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
712
-    }
713
-
714
-
715
-    /**
716
-     * db_table_is_empty
717
-     *
718
-     * @access     public\
719
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
720
-     * @static
721
-     * @param string $table_name
722
-     * @return bool
723
-     */
724
-    public static function db_table_is_empty($table_name)
725
-    {
726
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
727
-    }
728
-
729
-
730
-    /**
731
-     * delete_db_table_if_empty
732
-     *
733
-     * @access public
734
-     * @static
735
-     * @param string $table_name
736
-     * @return bool | int
737
-     */
738
-    public static function delete_db_table_if_empty($table_name)
739
-    {
740
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
741
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
742
-        }
743
-        return false;
744
-    }
745
-
746
-
747
-    /**
748
-     * delete_unused_db_table
749
-     *
750
-     * @access     public
751
-     * @static
752
-     * @deprecated instead use TableManager::dropTable()
753
-     * @param string $table_name
754
-     * @return bool | int
755
-     */
756
-    public static function delete_unused_db_table($table_name)
757
-    {
758
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
759
-    }
760
-
761
-
762
-    /**
763
-     * drop_index
764
-     *
765
-     * @access     public
766
-     * @static
767
-     * @deprecated instead use TableManager::dropIndex()
768
-     * @param string $table_name
769
-     * @param string $index_name
770
-     * @return bool | int
771
-     */
772
-    public static function drop_index($table_name, $index_name)
773
-    {
774
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
775
-    }
776
-
777
-
778
-
779
-    /**
780
-     * create_database_tables
781
-     *
782
-     * @access public
783
-     * @static
784
-     * @throws EE_Error
785
-     * @return boolean success (whether database is setup properly or not)
786
-     */
787
-    public static function create_database_tables()
788
-    {
789
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
790
-        // find the migration script that sets the database to be compatible with the code
791
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
792
-        if ($dms_name) {
793
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
794
-            $current_data_migration_script->set_migrating(false);
795
-            $current_data_migration_script->schema_changes_before_migration();
796
-            $current_data_migration_script->schema_changes_after_migration();
797
-            if ($current_data_migration_script->get_errors()) {
798
-                if (WP_DEBUG) {
799
-                    foreach ($current_data_migration_script->get_errors() as $error) {
800
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
801
-                    }
802
-                } else {
803
-                    EE_Error::add_error(
804
-                        __(
805
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
261
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
262
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
263
+			if (is_array($hooks_to_fire_at_time)) {
264
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
265
+					if (isset($ee_cron_tasks_to_remove[ $hook_name ])
266
+						&& is_array($ee_cron_tasks_to_remove[ $hook_name ])
267
+					) {
268
+						unset($crons[ $timestamp ][ $hook_name ]);
269
+					}
270
+				}
271
+				// also take care of any empty cron timestamps.
272
+				if (empty($hooks_to_fire_at_time)) {
273
+					unset($crons[ $timestamp ]);
274
+				}
275
+			}
276
+		}
277
+		_set_cron_array($crons);
278
+	}
279
+
280
+
281
+	/**
282
+	 *    CPT_initialization
283
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
284
+	 *
285
+	 * @access public
286
+	 * @static
287
+	 * @return void
288
+	 */
289
+	public static function CPT_initialization()
290
+	{
291
+		// register Custom Post Types
292
+		EE_Registry::instance()->load_core('Register_CPTs');
293
+		flush_rewrite_rules();
294
+	}
295
+
296
+
297
+
298
+	/**
299
+	 *    reset_and_update_config
300
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
301
+	 * If there is old calendar config data saved, then it will get converted on activation.
302
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
303
+	 *
304
+	 * @access public
305
+	 * @static
306
+	 * @return void
307
+	 */
308
+	public static function reset_and_update_config()
309
+	{
310
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
311
+		add_filter(
312
+			'FHEE__EE_Config___load_core_config__config_settings',
313
+			array('EEH_Activation', 'migrate_old_config_data'),
314
+			10,
315
+			3
316
+		);
317
+		// EE_Config::reset();
318
+		if (! EE_Config::logging_enabled()) {
319
+			delete_option(EE_Config::LOG_NAME);
320
+		}
321
+	}
322
+
323
+
324
+	/**
325
+	 *    load_calendar_config
326
+	 *
327
+	 * @access    public
328
+	 * @return    void
329
+	 */
330
+	public static function load_calendar_config()
331
+	{
332
+		// grab array of all plugin folders and loop thru it
333
+		$plugins = glob(WP_PLUGIN_DIR . '/*', GLOB_ONLYDIR);
334
+		if (empty($plugins)) {
335
+			return;
336
+		}
337
+		foreach ($plugins as $plugin_path) {
338
+			// grab plugin folder name from path
339
+			$plugin = basename($plugin_path);
340
+			// drill down to Espresso plugins
341
+			// then to calendar related plugins
342
+			if (strpos($plugin, 'espresso') !== false
343
+				|| strpos($plugin, 'Espresso') !== false
344
+				|| strpos($plugin, 'ee4') !== false
345
+				|| strpos($plugin, 'EE4') !== false
346
+				|| strpos($plugin, 'calendar') !== false
347
+			) {
348
+				// this is what we are looking for
349
+				$calendar_config = $plugin_path . '/EE_Calendar_Config.php';
350
+				// does it exist in this folder ?
351
+				if (is_readable($calendar_config)) {
352
+					// YEAH! let's load it
353
+					require_once($calendar_config);
354
+				}
355
+			}
356
+		}
357
+	}
358
+
359
+
360
+
361
+	/**
362
+	 *    _migrate_old_config_data
363
+	 *
364
+	 * @access    public
365
+	 * @param array|stdClass $settings
366
+	 * @param string         $config
367
+	 * @param \EE_Config     $EE_Config
368
+	 * @return \stdClass
369
+	 */
370
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
371
+	{
372
+		$convert_from_array = array('addons');
373
+		// in case old settings were saved as an array
374
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
375
+			// convert existing settings to an object
376
+			$config_array = $settings;
377
+			$settings = new stdClass();
378
+			foreach ($config_array as $key => $value) {
379
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
380
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
381
+				} else {
382
+					$settings->{$key} = $value;
383
+				}
384
+			}
385
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
386
+		}
387
+		return $settings;
388
+	}
389
+
390
+
391
+	/**
392
+	 * deactivate_event_espresso
393
+	 *
394
+	 * @access public
395
+	 * @static
396
+	 * @return void
397
+	 */
398
+	public static function deactivate_event_espresso()
399
+	{
400
+		// check permissions
401
+		if (current_user_can('activate_plugins')) {
402
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
403
+		}
404
+	}
405
+
406
+
407
+
408
+	/**
409
+	 * verify_default_pages_exist
410
+	 *
411
+	 * @access public
412
+	 * @static
413
+	 * @return void
414
+	 * @throws InvalidDataTypeException
415
+	 */
416
+	public static function verify_default_pages_exist()
417
+	{
418
+		$critical_page_problem = false;
419
+		$critical_pages = array(
420
+			array(
421
+				'id'   => 'reg_page_id',
422
+				'name' => __('Registration Checkout', 'event_espresso'),
423
+				'post' => null,
424
+				'code' => 'ESPRESSO_CHECKOUT',
425
+			),
426
+			array(
427
+				'id'   => 'txn_page_id',
428
+				'name' => __('Transactions', 'event_espresso'),
429
+				'post' => null,
430
+				'code' => 'ESPRESSO_TXN_PAGE',
431
+			),
432
+			array(
433
+				'id'   => 'thank_you_page_id',
434
+				'name' => __('Thank You', 'event_espresso'),
435
+				'post' => null,
436
+				'code' => 'ESPRESSO_THANK_YOU',
437
+			),
438
+			array(
439
+				'id'   => 'cancel_page_id',
440
+				'name' => __('Registration Cancelled', 'event_espresso'),
441
+				'post' => null,
442
+				'code' => 'ESPRESSO_CANCELLED',
443
+			),
444
+		);
445
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
446
+		foreach ($critical_pages as $critical_page) {
447
+			// is critical page ID set in config ?
448
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
449
+				// attempt to find post by ID
450
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
451
+			}
452
+			// no dice?
453
+			if ($critical_page['post'] === null) {
454
+				// attempt to find post by title
455
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
456
+				// still nothing?
457
+				if ($critical_page['post'] === null) {
458
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
459
+					// REALLY? Still nothing ??!?!?
460
+					if ($critical_page['post'] === null) {
461
+						$msg = __(
462
+							'The Event Espresso critical page configuration settings could not be updated.',
463
+							'event_espresso'
464
+						);
465
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
466
+						break;
467
+					}
468
+				}
469
+			}
470
+			// check that Post ID matches critical page ID in config
471
+			if (isset($critical_page['post']->ID)
472
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
473
+			) {
474
+				// update Config with post ID
475
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
476
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
477
+					$msg = __(
478
+						'The Event Espresso critical page configuration settings could not be updated.',
479
+						'event_espresso'
480
+					);
481
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
482
+				}
483
+			}
484
+			$critical_page_problem =
485
+				! isset($critical_page['post']->post_status)
486
+				|| $critical_page['post']->post_status !== 'publish'
487
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
488
+					? true
489
+					: $critical_page_problem;
490
+		}
491
+		if ($critical_page_problem) {
492
+			new PersistentAdminNotice(
493
+				'critical_page_problem',
494
+				sprintf(
495
+					esc_html__(
496
+						'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
497
+						'event_espresso'
498
+					),
499
+					'<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
500
+					. __('Event Espresso Critical Pages Settings', 'event_espresso')
501
+					. '</a>'
502
+				)
503
+			);
504
+		}
505
+		if (EE_Error::has_notices()) {
506
+			EE_Error::get_notices(false, true, true);
507
+		}
508
+	}
509
+
510
+
511
+
512
+	/**
513
+	 * Returns the first post which uses the specified shortcode
514
+	 *
515
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
516
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
517
+	 *                             "[ESPRESSO_THANK_YOU"
518
+	 *                             (we don't search for the closing shortcode bracket because they might have added
519
+	 *                             parameter to the shortcode
520
+	 * @return WP_Post or NULl
521
+	 */
522
+	public static function get_page_by_ee_shortcode($ee_shortcode)
523
+	{
524
+		global $wpdb;
525
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
526
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
527
+		if ($post_id) {
528
+			return get_post($post_id);
529
+		} else {
530
+			return null;
531
+		}
532
+	}
533
+
534
+
535
+	/**
536
+	 *    This function generates a post for critical espresso pages
537
+	 *
538
+	 * @access public
539
+	 * @static
540
+	 * @param array $critical_page
541
+	 * @return array
542
+	 */
543
+	public static function create_critical_page($critical_page)
544
+	{
545
+
546
+		$post_args = array(
547
+			'post_title'     => $critical_page['name'],
548
+			'post_status'    => 'publish',
549
+			'post_type'      => 'page',
550
+			'comment_status' => 'closed',
551
+			'post_content'   => '[' . $critical_page['code'] . ']',
552
+		);
553
+
554
+		$post_id = wp_insert_post($post_args);
555
+		if (! $post_id) {
556
+			$msg = sprintf(
557
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
558
+				$critical_page['name']
559
+			);
560
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
561
+			return $critical_page;
562
+		}
563
+		// get newly created post's details
564
+		if (! $critical_page['post'] = get_post($post_id)) {
565
+			$msg = sprintf(
566
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
567
+				$critical_page['name']
568
+			);
569
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
570
+		}
571
+
572
+		return $critical_page;
573
+	}
574
+
575
+
576
+
577
+
578
+	/**
579
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
580
+	 * The role being used to check is filterable.
581
+	 *
582
+	 * @since  4.6.0
583
+	 * @global WPDB $wpdb
584
+	 * @return mixed null|int WP_user ID or NULL
585
+	 */
586
+	public static function get_default_creator_id()
587
+	{
588
+		global $wpdb;
589
+		if (! empty(self::$_default_creator_id)) {
590
+			return self::$_default_creator_id;
591
+		}/**/
592
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
593
+		// 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.
594
+		$pre_filtered_id = apply_filters(
595
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
596
+			false,
597
+			$role_to_check
598
+		);
599
+		if ($pre_filtered_id !== false) {
600
+			return (int) $pre_filtered_id;
601
+		}
602
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
603
+		$query = $wpdb->prepare(
604
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
605
+			'%' . $role_to_check . '%'
606
+		);
607
+		$user_id = $wpdb->get_var($query);
608
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
609
+		if ($user_id && (int) $user_id) {
610
+			self::$_default_creator_id = (int) $user_id;
611
+			return self::$_default_creator_id;
612
+		} else {
613
+			return null;
614
+		}
615
+	}
616
+
617
+
618
+
619
+	/**
620
+	 * used by EE and EE addons during plugin activation to create tables.
621
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
622
+	 * but includes extra logic regarding activations.
623
+	 *
624
+	 * @access public
625
+	 * @static
626
+	 * @param string  $table_name              without the $wpdb->prefix
627
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
628
+	 *                                         table query)
629
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
630
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
631
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
632
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
633
+	 *                                         you just want to verify the table exists and matches this definition
634
+	 *                                         (and if it HAS data in it you want to leave it be)
635
+	 * @return void
636
+	 * @throws EE_Error if there are database errors
637
+	 */
638
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
639
+	{
640
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
641
+			return;
642
+		}
643
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
644
+		if (! function_exists('dbDelta')) {
645
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
646
+		}
647
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
648
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
649
+		// do we need to first delete an existing version of this table ?
650
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
651
+			// ok, delete the table... but ONLY if it's empty
652
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
653
+			// table is NOT empty, are you SURE you want to delete this table ???
654
+			if (! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
655
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
656
+			} elseif (! $deleted_safely) {
657
+				// so we should be more cautious rather than just dropping tables so easily
658
+				error_log(
659
+					sprintf(
660
+						__(
661
+							'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.',
662
+							'event_espresso'
663
+						),
664
+						$wp_table_name,
665
+						'<br/>',
666
+						'espresso_db_update'
667
+					)
668
+				);
669
+			}
670
+		}
671
+		$engine = str_replace('ENGINE=', '', $engine);
672
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 *    add_column_if_it_doesn't_exist
679
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
680
+	 *
681
+	 * @access     public
682
+	 * @static
683
+	 * @deprecated instead use TableManager::addColumn()
684
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
685
+	 * @param string $column_name
686
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
687
+	 *                            'VARCHAR(10)'
688
+	 * @return bool|int
689
+	 */
690
+	public static function add_column_if_it_doesnt_exist(
691
+		$table_name,
692
+		$column_name,
693
+		$column_info = 'INT UNSIGNED NOT NULL'
694
+	) {
695
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
696
+	}
697
+
698
+
699
+	/**
700
+	 * get_fields_on_table
701
+	 * Gets all the fields on the database table.
702
+	 *
703
+	 * @access     public
704
+	 * @deprecated instead use TableManager::getTableColumns()
705
+	 * @static
706
+	 * @param string $table_name , without prefixed $wpdb->prefix
707
+	 * @return array of database column names
708
+	 */
709
+	public static function get_fields_on_table($table_name = null)
710
+	{
711
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
712
+	}
713
+
714
+
715
+	/**
716
+	 * db_table_is_empty
717
+	 *
718
+	 * @access     public\
719
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
720
+	 * @static
721
+	 * @param string $table_name
722
+	 * @return bool
723
+	 */
724
+	public static function db_table_is_empty($table_name)
725
+	{
726
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
727
+	}
728
+
729
+
730
+	/**
731
+	 * delete_db_table_if_empty
732
+	 *
733
+	 * @access public
734
+	 * @static
735
+	 * @param string $table_name
736
+	 * @return bool | int
737
+	 */
738
+	public static function delete_db_table_if_empty($table_name)
739
+	{
740
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
741
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
742
+		}
743
+		return false;
744
+	}
745
+
746
+
747
+	/**
748
+	 * delete_unused_db_table
749
+	 *
750
+	 * @access     public
751
+	 * @static
752
+	 * @deprecated instead use TableManager::dropTable()
753
+	 * @param string $table_name
754
+	 * @return bool | int
755
+	 */
756
+	public static function delete_unused_db_table($table_name)
757
+	{
758
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
759
+	}
760
+
761
+
762
+	/**
763
+	 * drop_index
764
+	 *
765
+	 * @access     public
766
+	 * @static
767
+	 * @deprecated instead use TableManager::dropIndex()
768
+	 * @param string $table_name
769
+	 * @param string $index_name
770
+	 * @return bool | int
771
+	 */
772
+	public static function drop_index($table_name, $index_name)
773
+	{
774
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
775
+	}
776
+
777
+
778
+
779
+	/**
780
+	 * create_database_tables
781
+	 *
782
+	 * @access public
783
+	 * @static
784
+	 * @throws EE_Error
785
+	 * @return boolean success (whether database is setup properly or not)
786
+	 */
787
+	public static function create_database_tables()
788
+	{
789
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
790
+		// find the migration script that sets the database to be compatible with the code
791
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
792
+		if ($dms_name) {
793
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
794
+			$current_data_migration_script->set_migrating(false);
795
+			$current_data_migration_script->schema_changes_before_migration();
796
+			$current_data_migration_script->schema_changes_after_migration();
797
+			if ($current_data_migration_script->get_errors()) {
798
+				if (WP_DEBUG) {
799
+					foreach ($current_data_migration_script->get_errors() as $error) {
800
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
801
+					}
802
+				} else {
803
+					EE_Error::add_error(
804
+						__(
805
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
806 806
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
807
-                            'event_espresso'
808
-                        )
809
-                    );
810
-                }
811
-                return false;
812
-            }
813
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
814
-        } else {
815
-            EE_Error::add_error(
816
-                __(
817
-                    'Could not determine most up-to-date data migration script from which to pull database schema
807
+							'event_espresso'
808
+						)
809
+					);
810
+				}
811
+				return false;
812
+			}
813
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
814
+		} else {
815
+			EE_Error::add_error(
816
+				__(
817
+					'Could not determine most up-to-date data migration script from which to pull database schema
818 818
                      structure. So database is probably not setup properly',
819
-                    'event_espresso'
820
-                ),
821
-                __FILE__,
822
-                __FUNCTION__,
823
-                __LINE__
824
-            );
825
-            return false;
826
-        }
827
-        return true;
828
-    }
829
-
830
-
831
-
832
-    /**
833
-     * initialize_system_questions
834
-     *
835
-     * @access public
836
-     * @static
837
-     * @return void
838
-     */
839
-    public static function initialize_system_questions()
840
-    {
841
-        // QUESTION GROUPS
842
-        global $wpdb;
843
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
844
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
845
-        // what we have
846
-        $question_groups = $wpdb->get_col($SQL);
847
-        // check the response
848
-        $question_groups = is_array($question_groups) ? $question_groups : array();
849
-        // what we should have
850
-        $QSG_systems = array(1, 2);
851
-        // loop thru what we should have and compare to what we have
852
-        foreach ($QSG_systems as $QSG_system) {
853
-            // reset values array
854
-            $QSG_values = array();
855
-            // 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)
856
-            if (! in_array("$QSG_system", $question_groups)) {
857
-                // add it
858
-                switch ($QSG_system) {
859
-                    case 1:
860
-                        $QSG_values = array(
861
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
862
-                            'QSG_identifier'      => 'personal-information-' . time(),
863
-                            'QSG_desc'            => '',
864
-                            'QSG_order'           => 1,
865
-                            'QSG_show_group_name' => 1,
866
-                            'QSG_show_group_desc' => 1,
867
-                            'QSG_system'          => EEM_Question_Group::system_personal,
868
-                            'QSG_deleted'         => 0,
869
-                        );
870
-                        break;
871
-                    case 2:
872
-                        $QSG_values = array(
873
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
874
-                            'QSG_identifier'      => 'address-information-' . time(),
875
-                            'QSG_desc'            => '',
876
-                            'QSG_order'           => 2,
877
-                            'QSG_show_group_name' => 1,
878
-                            'QSG_show_group_desc' => 1,
879
-                            'QSG_system'          => EEM_Question_Group::system_address,
880
-                            'QSG_deleted'         => 0,
881
-                        );
882
-                        break;
883
-                }
884
-                // make sure we have some values before inserting them
885
-                if (! empty($QSG_values)) {
886
-                    // insert system question
887
-                    $wpdb->insert(
888
-                        $table_name,
889
-                        $QSG_values,
890
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
891
-                    );
892
-                    $QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
893
-                }
894
-            }
895
-        }
896
-        // QUESTIONS
897
-        global $wpdb;
898
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
899
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
900
-        // what we have
901
-        $questions = $wpdb->get_col($SQL);
902
-        // all system questions
903
-        $personal_system_group_questions = ['fname', 'lname', 'email'];
904
-        $address_system_group_questions = ['address', 'address2', 'city', 'country', 'state', 'zip', 'phone'];
905
-        $system_questions_not_in_group = ['email_confirm'];
906
-        // merge all of the system questions we should have
907
-        $QST_systems = array_merge(
908
-            $personal_system_group_questions,
909
-            $address_system_group_questions,
910
-            $system_questions_not_in_group
911
-        );
912
-        $order_for_group_1 = 1;
913
-        $order_for_group_2 = 1;
914
-        // loop thru what we should have and compare to what we have
915
-        foreach ($QST_systems as $QST_system) {
916
-            // reset values array
917
-            $QST_values = array();
918
-            // if we don't have what we should have
919
-            if (! in_array($QST_system, $questions)) {
920
-                // add it
921
-                switch ($QST_system) {
922
-                    case 'fname':
923
-                        $QST_values = array(
924
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
925
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
926
-                            'QST_system'        => 'fname',
927
-                            'QST_type'          => 'TEXT',
928
-                            'QST_required'      => 1,
929
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
930
-                            'QST_order'         => 1,
931
-                            'QST_admin_only'    => 0,
932
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
933
-                            'QST_wp_user'       => self::get_default_creator_id(),
934
-                            'QST_deleted'       => 0,
935
-                        );
936
-                        break;
937
-                    case 'lname':
938
-                        $QST_values = array(
939
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
940
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
941
-                            'QST_system'        => 'lname',
942
-                            'QST_type'          => 'TEXT',
943
-                            'QST_required'      => 1,
944
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
945
-                            'QST_order'         => 2,
946
-                            'QST_admin_only'    => 0,
947
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
948
-                            'QST_wp_user'       => self::get_default_creator_id(),
949
-                            'QST_deleted'       => 0,
950
-                        );
951
-                        break;
952
-                    case 'email':
953
-                        $QST_values = array(
954
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
955
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
956
-                            'QST_system'        => 'email',
957
-                            'QST_type'          => 'EMAIL',
958
-                            'QST_required'      => 1,
959
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
960
-                            'QST_order'         => 3,
961
-                            'QST_admin_only'    => 0,
962
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
963
-                            'QST_wp_user'       => self::get_default_creator_id(),
964
-                            'QST_deleted'       => 0,
965
-                        );
966
-                        break;
967
-                    case 'email_confirm':
968
-                        $QST_values = array(
969
-                            'QST_display_text'  => __('Confirm Email Address', 'event_espresso'),
970
-                            'QST_admin_label'   => __('Confirm Email Address - System Question', 'event_espresso'),
971
-                            'QST_system'        => 'email_confirm',
972
-                            'QST_type'          => 'EMAIL_CONFIRM',
973
-                            'QST_required'      => 1,
974
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
975
-                            'QST_order'         => 4,
976
-                            'QST_admin_only'    => 0,
977
-                            'QST_max'           => EEM_Question::instance()->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 'address':
983
-                        $QST_values = array(
984
-                            'QST_display_text'  => __('Address', 'event_espresso'),
985
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
986
-                            'QST_system'        => 'address',
987
-                            'QST_type'          => 'TEXT',
988
-                            'QST_required'      => 0,
989
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
990
-                            'QST_order'         => 5,
991
-                            'QST_admin_only'    => 0,
992
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
993
-                            'QST_wp_user'       => self::get_default_creator_id(),
994
-                            'QST_deleted'       => 0,
995
-                        );
996
-                        break;
997
-                    case 'address2':
998
-                        $QST_values = array(
999
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
1000
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1001
-                            'QST_system'        => 'address2',
1002
-                            'QST_type'          => 'TEXT',
1003
-                            'QST_required'      => 0,
1004
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1005
-                            'QST_order'         => 6,
1006
-                            'QST_admin_only'    => 0,
1007
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1008
-                            'QST_wp_user'       => self::get_default_creator_id(),
1009
-                            'QST_deleted'       => 0,
1010
-                        );
1011
-                        break;
1012
-                    case 'city':
1013
-                        $QST_values = array(
1014
-                            'QST_display_text'  => __('City', 'event_espresso'),
1015
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1016
-                            'QST_system'        => 'city',
1017
-                            'QST_type'          => 'TEXT',
1018
-                            'QST_required'      => 0,
1019
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1020
-                            'QST_order'         => 7,
1021
-                            'QST_admin_only'    => 0,
1022
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1023
-                            'QST_wp_user'       => self::get_default_creator_id(),
1024
-                            'QST_deleted'       => 0,
1025
-                        );
1026
-                        break;
1027
-                    case 'country':
1028
-                        $QST_values = array(
1029
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1030
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1031
-                            'QST_system'        => 'country',
1032
-                            'QST_type'          => 'COUNTRY',
1033
-                            'QST_required'      => 0,
1034
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1035
-                            'QST_order'         => 8,
1036
-                            'QST_admin_only'    => 0,
1037
-                            'QST_wp_user'       => self::get_default_creator_id(),
1038
-                            'QST_deleted'       => 0,
1039
-                        );
1040
-                        break;
1041
-                    case 'state':
1042
-                        $QST_values = array(
1043
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1044
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1045
-                            'QST_system'        => 'state',
1046
-                            'QST_type'          => 'STATE',
1047
-                            'QST_required'      => 0,
1048
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1049
-                            'QST_order'         => 9,
1050
-                            'QST_admin_only'    => 0,
1051
-                            'QST_wp_user'       => self::get_default_creator_id(),
1052
-                            'QST_deleted'       => 0,
1053
-                        );
1054
-                        break;
1055
-                    case 'zip':
1056
-                        $QST_values = array(
1057
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1058
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1059
-                            'QST_system'        => 'zip',
1060
-                            'QST_type'          => 'TEXT',
1061
-                            'QST_required'      => 0,
1062
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1063
-                            'QST_order'         => 10,
1064
-                            'QST_admin_only'    => 0,
1065
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1066
-                            'QST_wp_user'       => self::get_default_creator_id(),
1067
-                            'QST_deleted'       => 0,
1068
-                        );
1069
-                        break;
1070
-                    case 'phone':
1071
-                        $QST_values = array(
1072
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1073
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1074
-                            'QST_system'        => 'phone',
1075
-                            'QST_type'          => 'TEXT',
1076
-                            'QST_required'      => 0,
1077
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1078
-                            'QST_order'         => 11,
1079
-                            'QST_admin_only'    => 0,
1080
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1081
-                            'QST_wp_user'       => self::get_default_creator_id(),
1082
-                            'QST_deleted'       => 0,
1083
-                        );
1084
-                        break;
1085
-                }
1086
-                if (! empty($QST_values)) {
1087
-                    // insert system question
1088
-                    $wpdb->insert(
1089
-                        $table_name,
1090
-                        $QST_values,
1091
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1092
-                    );
1093
-                    $QST_ID = $wpdb->insert_id;
1094
-
1095
-                    // QUESTION GROUP QUESTIONS
1096
-                    if (in_array($QST_system, $personal_system_group_questions)) {
1097
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1098
-                    } elseif (in_array($QST_system, $address_system_group_questions)) {
1099
-                        $system_question_we_want = EEM_Question_Group::system_address;
1100
-                    } else {
1101
-                        // QST_system should not be assigned to any group
1102
-                        continue;
1103
-                    }
1104
-                    if (isset($QSG_IDs[ $system_question_we_want ])) {
1105
-                        $QSG_ID = $QSG_IDs[ $system_question_we_want ];
1106
-                    } else {
1107
-                        $id_col = EEM_Question_Group::instance()
1108
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1109
-                        if (is_array($id_col)) {
1110
-                            $QSG_ID = reset($id_col);
1111
-                        } else {
1112
-                            // 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
1113
-                            EE_Log::instance()->log(
1114
-                                __FILE__,
1115
-                                __FUNCTION__,
1116
-                                sprintf(
1117
-                                    __(
1118
-                                        'Could not associate question %1$s to a question group because no system question
819
+					'event_espresso'
820
+				),
821
+				__FILE__,
822
+				__FUNCTION__,
823
+				__LINE__
824
+			);
825
+			return false;
826
+		}
827
+		return true;
828
+	}
829
+
830
+
831
+
832
+	/**
833
+	 * initialize_system_questions
834
+	 *
835
+	 * @access public
836
+	 * @static
837
+	 * @return void
838
+	 */
839
+	public static function initialize_system_questions()
840
+	{
841
+		// QUESTION GROUPS
842
+		global $wpdb;
843
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
844
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
845
+		// what we have
846
+		$question_groups = $wpdb->get_col($SQL);
847
+		// check the response
848
+		$question_groups = is_array($question_groups) ? $question_groups : array();
849
+		// what we should have
850
+		$QSG_systems = array(1, 2);
851
+		// loop thru what we should have and compare to what we have
852
+		foreach ($QSG_systems as $QSG_system) {
853
+			// reset values array
854
+			$QSG_values = array();
855
+			// 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)
856
+			if (! in_array("$QSG_system", $question_groups)) {
857
+				// add it
858
+				switch ($QSG_system) {
859
+					case 1:
860
+						$QSG_values = array(
861
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
862
+							'QSG_identifier'      => 'personal-information-' . time(),
863
+							'QSG_desc'            => '',
864
+							'QSG_order'           => 1,
865
+							'QSG_show_group_name' => 1,
866
+							'QSG_show_group_desc' => 1,
867
+							'QSG_system'          => EEM_Question_Group::system_personal,
868
+							'QSG_deleted'         => 0,
869
+						);
870
+						break;
871
+					case 2:
872
+						$QSG_values = array(
873
+							'QSG_name'            => __('Address Information', 'event_espresso'),
874
+							'QSG_identifier'      => 'address-information-' . time(),
875
+							'QSG_desc'            => '',
876
+							'QSG_order'           => 2,
877
+							'QSG_show_group_name' => 1,
878
+							'QSG_show_group_desc' => 1,
879
+							'QSG_system'          => EEM_Question_Group::system_address,
880
+							'QSG_deleted'         => 0,
881
+						);
882
+						break;
883
+				}
884
+				// make sure we have some values before inserting them
885
+				if (! empty($QSG_values)) {
886
+					// insert system question
887
+					$wpdb->insert(
888
+						$table_name,
889
+						$QSG_values,
890
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
891
+					);
892
+					$QSG_IDs[ $QSG_system ] = $wpdb->insert_id;
893
+				}
894
+			}
895
+		}
896
+		// QUESTIONS
897
+		global $wpdb;
898
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
899
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
900
+		// what we have
901
+		$questions = $wpdb->get_col($SQL);
902
+		// all system questions
903
+		$personal_system_group_questions = ['fname', 'lname', 'email'];
904
+		$address_system_group_questions = ['address', 'address2', 'city', 'country', 'state', 'zip', 'phone'];
905
+		$system_questions_not_in_group = ['email_confirm'];
906
+		// merge all of the system questions we should have
907
+		$QST_systems = array_merge(
908
+			$personal_system_group_questions,
909
+			$address_system_group_questions,
910
+			$system_questions_not_in_group
911
+		);
912
+		$order_for_group_1 = 1;
913
+		$order_for_group_2 = 1;
914
+		// loop thru what we should have and compare to what we have
915
+		foreach ($QST_systems as $QST_system) {
916
+			// reset values array
917
+			$QST_values = array();
918
+			// if we don't have what we should have
919
+			if (! in_array($QST_system, $questions)) {
920
+				// add it
921
+				switch ($QST_system) {
922
+					case 'fname':
923
+						$QST_values = array(
924
+							'QST_display_text'  => __('First Name', 'event_espresso'),
925
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
926
+							'QST_system'        => 'fname',
927
+							'QST_type'          => 'TEXT',
928
+							'QST_required'      => 1,
929
+							'QST_required_text' => __('This field is required', 'event_espresso'),
930
+							'QST_order'         => 1,
931
+							'QST_admin_only'    => 0,
932
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
933
+							'QST_wp_user'       => self::get_default_creator_id(),
934
+							'QST_deleted'       => 0,
935
+						);
936
+						break;
937
+					case 'lname':
938
+						$QST_values = array(
939
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
940
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
941
+							'QST_system'        => 'lname',
942
+							'QST_type'          => 'TEXT',
943
+							'QST_required'      => 1,
944
+							'QST_required_text' => __('This field is required', 'event_espresso'),
945
+							'QST_order'         => 2,
946
+							'QST_admin_only'    => 0,
947
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
948
+							'QST_wp_user'       => self::get_default_creator_id(),
949
+							'QST_deleted'       => 0,
950
+						);
951
+						break;
952
+					case 'email':
953
+						$QST_values = array(
954
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
955
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
956
+							'QST_system'        => 'email',
957
+							'QST_type'          => 'EMAIL',
958
+							'QST_required'      => 1,
959
+							'QST_required_text' => __('This field is required', 'event_espresso'),
960
+							'QST_order'         => 3,
961
+							'QST_admin_only'    => 0,
962
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
963
+							'QST_wp_user'       => self::get_default_creator_id(),
964
+							'QST_deleted'       => 0,
965
+						);
966
+						break;
967
+					case 'email_confirm':
968
+						$QST_values = array(
969
+							'QST_display_text'  => __('Confirm Email Address', 'event_espresso'),
970
+							'QST_admin_label'   => __('Confirm Email Address - System Question', 'event_espresso'),
971
+							'QST_system'        => 'email_confirm',
972
+							'QST_type'          => 'EMAIL_CONFIRM',
973
+							'QST_required'      => 1,
974
+							'QST_required_text' => __('This field is required', 'event_espresso'),
975
+							'QST_order'         => 4,
976
+							'QST_admin_only'    => 0,
977
+							'QST_max'           => EEM_Question::instance()->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 'address':
983
+						$QST_values = array(
984
+							'QST_display_text'  => __('Address', 'event_espresso'),
985
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
986
+							'QST_system'        => 'address',
987
+							'QST_type'          => 'TEXT',
988
+							'QST_required'      => 0,
989
+							'QST_required_text' => __('This field is required', 'event_espresso'),
990
+							'QST_order'         => 5,
991
+							'QST_admin_only'    => 0,
992
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
993
+							'QST_wp_user'       => self::get_default_creator_id(),
994
+							'QST_deleted'       => 0,
995
+						);
996
+						break;
997
+					case 'address2':
998
+						$QST_values = array(
999
+							'QST_display_text'  => __('Address2', 'event_espresso'),
1000
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1001
+							'QST_system'        => 'address2',
1002
+							'QST_type'          => 'TEXT',
1003
+							'QST_required'      => 0,
1004
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1005
+							'QST_order'         => 6,
1006
+							'QST_admin_only'    => 0,
1007
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1008
+							'QST_wp_user'       => self::get_default_creator_id(),
1009
+							'QST_deleted'       => 0,
1010
+						);
1011
+						break;
1012
+					case 'city':
1013
+						$QST_values = array(
1014
+							'QST_display_text'  => __('City', 'event_espresso'),
1015
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1016
+							'QST_system'        => 'city',
1017
+							'QST_type'          => 'TEXT',
1018
+							'QST_required'      => 0,
1019
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1020
+							'QST_order'         => 7,
1021
+							'QST_admin_only'    => 0,
1022
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1023
+							'QST_wp_user'       => self::get_default_creator_id(),
1024
+							'QST_deleted'       => 0,
1025
+						);
1026
+						break;
1027
+					case 'country':
1028
+						$QST_values = array(
1029
+							'QST_display_text'  => __('Country', 'event_espresso'),
1030
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1031
+							'QST_system'        => 'country',
1032
+							'QST_type'          => 'COUNTRY',
1033
+							'QST_required'      => 0,
1034
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1035
+							'QST_order'         => 8,
1036
+							'QST_admin_only'    => 0,
1037
+							'QST_wp_user'       => self::get_default_creator_id(),
1038
+							'QST_deleted'       => 0,
1039
+						);
1040
+						break;
1041
+					case 'state':
1042
+						$QST_values = array(
1043
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1044
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1045
+							'QST_system'        => 'state',
1046
+							'QST_type'          => 'STATE',
1047
+							'QST_required'      => 0,
1048
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1049
+							'QST_order'         => 9,
1050
+							'QST_admin_only'    => 0,
1051
+							'QST_wp_user'       => self::get_default_creator_id(),
1052
+							'QST_deleted'       => 0,
1053
+						);
1054
+						break;
1055
+					case 'zip':
1056
+						$QST_values = array(
1057
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1058
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1059
+							'QST_system'        => 'zip',
1060
+							'QST_type'          => 'TEXT',
1061
+							'QST_required'      => 0,
1062
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1063
+							'QST_order'         => 10,
1064
+							'QST_admin_only'    => 0,
1065
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1066
+							'QST_wp_user'       => self::get_default_creator_id(),
1067
+							'QST_deleted'       => 0,
1068
+						);
1069
+						break;
1070
+					case 'phone':
1071
+						$QST_values = array(
1072
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1073
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1074
+							'QST_system'        => 'phone',
1075
+							'QST_type'          => 'TEXT',
1076
+							'QST_required'      => 0,
1077
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1078
+							'QST_order'         => 11,
1079
+							'QST_admin_only'    => 0,
1080
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1081
+							'QST_wp_user'       => self::get_default_creator_id(),
1082
+							'QST_deleted'       => 0,
1083
+						);
1084
+						break;
1085
+				}
1086
+				if (! empty($QST_values)) {
1087
+					// insert system question
1088
+					$wpdb->insert(
1089
+						$table_name,
1090
+						$QST_values,
1091
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1092
+					);
1093
+					$QST_ID = $wpdb->insert_id;
1094
+
1095
+					// QUESTION GROUP QUESTIONS
1096
+					if (in_array($QST_system, $personal_system_group_questions)) {
1097
+						$system_question_we_want = EEM_Question_Group::system_personal;
1098
+					} elseif (in_array($QST_system, $address_system_group_questions)) {
1099
+						$system_question_we_want = EEM_Question_Group::system_address;
1100
+					} else {
1101
+						// QST_system should not be assigned to any group
1102
+						continue;
1103
+					}
1104
+					if (isset($QSG_IDs[ $system_question_we_want ])) {
1105
+						$QSG_ID = $QSG_IDs[ $system_question_we_want ];
1106
+					} else {
1107
+						$id_col = EEM_Question_Group::instance()
1108
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1109
+						if (is_array($id_col)) {
1110
+							$QSG_ID = reset($id_col);
1111
+						} else {
1112
+							// 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
1113
+							EE_Log::instance()->log(
1114
+								__FILE__,
1115
+								__FUNCTION__,
1116
+								sprintf(
1117
+									__(
1118
+										'Could not associate question %1$s to a question group because no system question
1119 1119
                                          group existed',
1120
-                                        'event_espresso'
1121
-                                    ),
1122
-                                    $QST_ID
1123
-                                ),
1124
-                                'error'
1125
-                            );
1126
-                            continue;
1127
-                        }
1128
-                    }
1129
-                    // add system questions to groups
1130
-                    $wpdb->insert(
1131
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1132
-                        array(
1133
-                            'QSG_ID'    => $QSG_ID,
1134
-                            'QST_ID'    => $QST_ID,
1135
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1136
-                        ),
1137
-                        array('%d', '%d', '%d')
1138
-                    );
1139
-                }
1140
-            }
1141
-        }
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * Makes sure the default payment method (Invoice) is active.
1147
-     * This used to be done automatically as part of constructing the old gateways config
1148
-     *
1149
-     * @throws \EE_Error
1150
-     */
1151
-    public static function insert_default_payment_methods()
1152
-    {
1153
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1154
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1155
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1156
-        } else {
1157
-            EEM_Payment_Method::instance()->verify_button_urls();
1158
-        }
1159
-    }
1160
-
1161
-    /**
1162
-     * insert_default_status_codes
1163
-     *
1164
-     * @access public
1165
-     * @static
1166
-     * @return void
1167
-     */
1168
-    public static function insert_default_status_codes()
1169
-    {
1170
-
1171
-        global $wpdb;
1172
-
1173
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1174
-            $table_name = EEM_Status::instance()->table();
1175
-
1176
-            $SQL = "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' );";
1177
-            $wpdb->query($SQL);
1178
-
1179
-            $SQL = "INSERT INTO $table_name
1120
+										'event_espresso'
1121
+									),
1122
+									$QST_ID
1123
+								),
1124
+								'error'
1125
+							);
1126
+							continue;
1127
+						}
1128
+					}
1129
+					// add system questions to groups
1130
+					$wpdb->insert(
1131
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1132
+						array(
1133
+							'QSG_ID'    => $QSG_ID,
1134
+							'QST_ID'    => $QST_ID,
1135
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1136
+						),
1137
+						array('%d', '%d', '%d')
1138
+					);
1139
+				}
1140
+			}
1141
+		}
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * Makes sure the default payment method (Invoice) is active.
1147
+	 * This used to be done automatically as part of constructing the old gateways config
1148
+	 *
1149
+	 * @throws \EE_Error
1150
+	 */
1151
+	public static function insert_default_payment_methods()
1152
+	{
1153
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1154
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1155
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1156
+		} else {
1157
+			EEM_Payment_Method::instance()->verify_button_urls();
1158
+		}
1159
+	}
1160
+
1161
+	/**
1162
+	 * insert_default_status_codes
1163
+	 *
1164
+	 * @access public
1165
+	 * @static
1166
+	 * @return void
1167
+	 */
1168
+	public static function insert_default_status_codes()
1169
+	{
1170
+
1171
+		global $wpdb;
1172
+
1173
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1174
+			$table_name = EEM_Status::instance()->table();
1175
+
1176
+			$SQL = "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' );";
1177
+			$wpdb->query($SQL);
1178
+
1179
+			$SQL = "INSERT INTO $table_name
1180 1180
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1181 1181
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1182 1182
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1216,479 +1216,479 @@  discard block
 block discarded – undo
1216 1216
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1217 1217
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1218 1218
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1219
-            $wpdb->query($SQL);
1220
-        }
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * generate_default_message_templates
1226
-     *
1227
-     * @static
1228
-     * @throws EE_Error
1229
-     * @return bool     true means new templates were created.
1230
-     *                  false means no templates were created.
1231
-     *                  This is NOT an error flag. To check for errors you will want
1232
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1233
-     */
1234
-    public static function generate_default_message_templates()
1235
-    {
1236
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1237
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1238
-        /*
1219
+			$wpdb->query($SQL);
1220
+		}
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * generate_default_message_templates
1226
+	 *
1227
+	 * @static
1228
+	 * @throws EE_Error
1229
+	 * @return bool     true means new templates were created.
1230
+	 *                  false means no templates were created.
1231
+	 *                  This is NOT an error flag. To check for errors you will want
1232
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1233
+	 */
1234
+	public static function generate_default_message_templates()
1235
+	{
1236
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1237
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1238
+		/*
1239 1239
          * This first method is taking care of ensuring any default messengers
1240 1240
          * that should be made active and have templates generated are done.
1241 1241
          */
1242
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1243
-            $message_resource_manager
1244
-        );
1245
-        /**
1246
-         * This method is verifying there are no NEW default message types
1247
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1248
-         */
1249
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1250
-            $message_resource_manager
1251
-        );
1252
-        // after all is done, let's persist these changes to the db.
1253
-        $message_resource_manager->update_has_activated_messengers_option();
1254
-        $message_resource_manager->update_active_messengers_option();
1255
-        // will return true if either of these are true.  Otherwise will return false.
1256
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1257
-    }
1258
-
1259
-
1260
-
1261
-    /**
1262
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1263
-     * @return array|bool
1264
-     * @throws \EE_Error
1265
-     */
1266
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1267
-        EE_Message_Resource_Manager $message_resource_manager
1268
-    ) {
1269
-        /** @type EE_messenger[] $active_messengers */
1270
-        $active_messengers = $message_resource_manager->active_messengers();
1271
-        $installed_message_types = $message_resource_manager->installed_message_types();
1272
-        $templates_created = false;
1273
-        foreach ($active_messengers as $active_messenger) {
1274
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1275
-            $default_message_type_names_to_activate = array();
1276
-            // looping through each default message type reported by the messenger
1277
-            // and setup the actual message types to activate.
1278
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1279
-                // if already active or has already been activated before we skip
1280
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1281
-                // we also skip if the message type is not installed.
1282
-                if ($message_resource_manager->has_message_type_been_activated_for_messenger(
1283
-                    $default_message_type_name_for_messenger,
1284
-                    $active_messenger->name
1285
-                )
1286
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1287
-                        $active_messenger->name,
1288
-                        $default_message_type_name_for_messenger
1289
-                    )
1290
-                    || ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1291
-                ) {
1292
-                    continue;
1293
-                }
1294
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1295
-            }
1296
-            // let's activate!
1297
-            $message_resource_manager->ensure_message_types_are_active(
1298
-                $default_message_type_names_to_activate,
1299
-                $active_messenger->name,
1300
-                false
1301
-            );
1302
-            // activate the templates for these message types
1303
-            if (! empty($default_message_type_names_to_activate)) {
1304
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1305
-                    $active_messenger->name,
1306
-                    $default_message_type_names_for_messenger,
1307
-                    '',
1308
-                    true
1309
-                );
1310
-            }
1311
-        }
1312
-        return $templates_created;
1313
-    }
1314
-
1315
-
1316
-
1317
-    /**
1318
-     * This will activate and generate default messengers and default message types for those messengers.
1319
-     *
1320
-     * @param EE_message_Resource_Manager $message_resource_manager
1321
-     * @return array|bool  True means there were default messengers and message type templates generated.
1322
-     *                     False means that there were no templates generated
1323
-     *                     (which could simply mean there are no default message types for a messenger).
1324
-     * @throws EE_Error
1325
-     */
1326
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1327
-        EE_Message_Resource_Manager $message_resource_manager
1328
-    ) {
1329
-        /** @type EE_messenger[] $messengers_to_generate */
1330
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1331
-        $installed_message_types = $message_resource_manager->installed_message_types();
1332
-        $templates_generated = false;
1333
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1334
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1335
-            // verify the default message types match an installed message type.
1336
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1337
-                if (! isset($installed_message_types[ $name ])
1338
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1339
-                        $name,
1340
-                        $messenger_to_generate->name
1341
-                    )
1342
-                ) {
1343
-                    unset($default_message_type_names_for_messenger[ $key ]);
1344
-                }
1345
-            }
1346
-            // in previous iterations, the active_messengers option in the db
1347
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1348
-            // This comment is left here just in case we discover that we _do_ need to update before
1349
-            // passing off to create templates (after the refactor is done).
1350
-            // @todo remove this comment when determined not necessary.
1351
-            $message_resource_manager->activate_messenger(
1352
-                $messenger_to_generate,
1353
-                $default_message_type_names_for_messenger,
1354
-                false
1355
-            );
1356
-            // create any templates needing created (or will reactivate templates already generated as necessary).
1357
-            if (! empty($default_message_type_names_for_messenger)) {
1358
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1359
-                    $messenger_to_generate->name,
1360
-                    $default_message_type_names_for_messenger,
1361
-                    '',
1362
-                    true
1363
-                );
1364
-            }
1365
-        }
1366
-        return $templates_generated;
1367
-    }
1368
-
1369
-
1370
-    /**
1371
-     * This returns the default messengers to generate templates for on activation of EE.
1372
-     * It considers:
1373
-     * - whether a messenger is already active in the db.
1374
-     * - whether a messenger has been made active at any time in the past.
1375
-     *
1376
-     * @static
1377
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1378
-     * @return EE_messenger[]
1379
-     */
1380
-    protected static function _get_default_messengers_to_generate_on_activation(
1381
-        EE_Message_Resource_Manager $message_resource_manager
1382
-    ) {
1383
-        $active_messengers    = $message_resource_manager->active_messengers();
1384
-        $installed_messengers = $message_resource_manager->installed_messengers();
1385
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1386
-
1387
-        $messengers_to_generate = array();
1388
-        foreach ($installed_messengers as $installed_messenger) {
1389
-            // if installed messenger is a messenger that should be activated on install
1390
-            // and is not already active
1391
-            // and has never been activated
1392
-            if (! $installed_messenger->activate_on_install
1393
-                || isset($active_messengers[ $installed_messenger->name ])
1394
-                || isset($has_activated[ $installed_messenger->name ])
1395
-            ) {
1396
-                continue;
1397
-            }
1398
-            $messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1399
-        }
1400
-        return $messengers_to_generate;
1401
-    }
1402
-
1403
-
1404
-    /**
1405
-     * This simply validates active message types to ensure they actually match installed
1406
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1407
-     * rows are set inactive.
1408
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1409
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1410
-     * are still handled in here.
1411
-     *
1412
-     * @since 4.3.1
1413
-     * @return void
1414
-     */
1415
-    public static function validate_messages_system()
1416
-    {
1417
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1418
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1419
-        $message_resource_manager->validate_active_message_types_are_installed();
1420
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1421
-    }
1422
-
1423
-
1424
-    /**
1425
-     * create_no_ticket_prices_array
1426
-     *
1427
-     * @access public
1428
-     * @static
1429
-     * @return void
1430
-     */
1431
-    public static function create_no_ticket_prices_array()
1432
-    {
1433
-        // this creates an array for tracking events that have no active ticket prices created
1434
-        // this allows us to warn admins of the situation so that it can be corrected
1435
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1436
-        if (! $espresso_no_ticket_prices) {
1437
-            add_option('ee_no_ticket_prices', array(), '', false);
1438
-        }
1439
-    }
1440
-
1441
-
1442
-    /**
1443
-     * plugin_deactivation
1444
-     *
1445
-     * @access public
1446
-     * @static
1447
-     * @return void
1448
-     */
1449
-    public static function plugin_deactivation()
1450
-    {
1451
-    }
1452
-
1453
-
1454
-    /**
1455
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1456
-     * (like post meta or term relations)
1457
-     *
1458
-     * @global wpdb $wpdb
1459
-     * @throws \EE_Error
1460
-     */
1461
-    public static function delete_all_espresso_cpt_data()
1462
-    {
1463
-        global $wpdb;
1464
-        // get all the CPT post_types
1465
-        $ee_post_types = array();
1466
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1467
-            if (method_exists($model_name, 'instance')) {
1468
-                $model_obj = call_user_func(array($model_name, 'instance'));
1469
-                if ($model_obj instanceof EEM_CPT_Base) {
1470
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1471
-                }
1472
-            }
1473
-        }
1474
-        // get all our CPTs
1475
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1476
-        $cpt_ids = $wpdb->get_col($query);
1477
-        // delete each post meta and term relations too
1478
-        foreach ($cpt_ids as $post_id) {
1479
-            wp_delete_post($post_id, true);
1480
-        }
1481
-    }
1482
-
1483
-    /**
1484
-     * Deletes all EE custom tables
1485
-     *
1486
-     * @return array
1487
-     */
1488
-    public static function drop_espresso_tables()
1489
-    {
1490
-        $tables = array();
1491
-        // load registry
1492
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1493
-            if (method_exists($model_name, 'instance')) {
1494
-                $model_obj = call_user_func(array($model_name, 'instance'));
1495
-                if ($model_obj instanceof EEM_Base) {
1496
-                    foreach ($model_obj->get_tables() as $table) {
1497
-                        if (strpos($table->get_table_name(), 'esp_')
1498
-                            &&
1499
-                            (
1500
-                                is_main_site()// main site? nuke them all
1501
-                                || ! $table->is_global()// not main site,but not global either. nuke it
1502
-                            )
1503
-                        ) {
1504
-                            $tables[ $table->get_table_name() ] = $table->get_table_name();
1505
-                        }
1506
-                    }
1507
-                }
1508
-            }
1509
-        }
1510
-
1511
-        // there are some tables whose models were removed.
1512
-        // they should be removed when removing all EE core's data
1513
-        $tables_without_models = array(
1514
-            'esp_promotion',
1515
-            'esp_promotion_applied',
1516
-            'esp_promotion_object',
1517
-            'esp_promotion_rule',
1518
-            'esp_rule',
1519
-        );
1520
-        foreach ($tables_without_models as $table) {
1521
-            $tables[ $table ] = $table;
1522
-        }
1523
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1524
-    }
1525
-
1526
-
1527
-
1528
-    /**
1529
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1530
-     * each table name provided has a wpdb prefix attached, and that it exists.
1531
-     * Returns the list actually deleted
1532
-     *
1533
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1534
-     * @global WPDB $wpdb
1535
-     * @param array $table_names
1536
-     * @return array of table names which we deleted
1537
-     */
1538
-    public static function drop_tables($table_names)
1539
-    {
1540
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1541
-    }
1542
-
1543
-
1544
-
1545
-    /**
1546
-     * plugin_uninstall
1547
-     *
1548
-     * @access public
1549
-     * @static
1550
-     * @param bool $remove_all
1551
-     * @return void
1552
-     */
1553
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1554
-    {
1555
-        global $wpdb;
1556
-        self::drop_espresso_tables();
1557
-        $wp_options_to_delete = array(
1558
-            'ee_no_ticket_prices'                => true,
1559
-            'ee_active_messengers'               => true,
1560
-            'ee_has_activated_messenger'         => true,
1561
-            RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1562
-            'ee_config'                          => false,
1563
-            'ee_data_migration_current_db_state' => true,
1564
-            'ee_data_migration_mapping_'         => false,
1565
-            'ee_data_migration_script_'          => false,
1566
-            'ee_data_migrations'                 => true,
1567
-            'ee_dms_map'                         => false,
1568
-            'ee_notices'                         => true,
1569
-            'lang_file_check_'                   => false,
1570
-            'ee_maintenance_mode'                => true,
1571
-            'ee_ueip_optin'                      => true,
1572
-            'ee_ueip_has_notified'               => true,
1573
-            'ee_plugin_activation_errors'        => true,
1574
-            'ee_id_mapping_from'                 => false,
1575
-            'espresso_persistent_admin_notices'  => true,
1576
-            'ee_encryption_key'                  => true,
1577
-            'pue_force_upgrade_'                 => false,
1578
-            'pue_json_error_'                    => false,
1579
-            'pue_install_key_'                   => false,
1580
-            'pue_verification_error_'            => false,
1581
-            'pu_dismissed_upgrade_'              => false,
1582
-            'external_updates-'                  => false,
1583
-            'ee_extra_data'                      => true,
1584
-            'ee_ssn_'                            => false,
1585
-            'ee_rss_'                            => false,
1586
-            'ee_rte_n_tx_'                       => false,
1587
-            'ee_pers_admin_notices'              => true,
1588
-            'ee_job_parameters_'                 => false,
1589
-            'ee_upload_directories_incomplete'   => true,
1590
-            'ee_verified_db_collations'          => true,
1591
-        );
1592
-        if (is_main_site()) {
1593
-            $wp_options_to_delete['ee_network_config'] = true;
1594
-        }
1595
-        $undeleted_options = array();
1596
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1597
-            if ($no_wildcard) {
1598
-                if (! delete_option($option_name)) {
1599
-                    $undeleted_options[] = $option_name;
1600
-                }
1601
-            } else {
1602
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1603
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1604
-                    if (! delete_option($option_name_from_wildcard)) {
1605
-                        $undeleted_options[] = $option_name_from_wildcard;
1606
-                    }
1607
-                }
1608
-            }
1609
-        }
1610
-        // also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1611
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1612
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1613
-            $db_update_sans_ee4 = array();
1614
-            foreach ($espresso_db_update as $version => $times_activated) {
1615
-                if ((string) $version[0] === '3') {// if its NON EE4
1616
-                    $db_update_sans_ee4[ $version ] = $times_activated;
1617
-                }
1618
-            }
1619
-            update_option('espresso_db_update', $db_update_sans_ee4);
1620
-        }
1621
-        $errors = '';
1622
-        if (! empty($undeleted_options)) {
1623
-            $errors .= sprintf(
1624
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1625
-                '<br/>',
1626
-                implode(',<br/>', $undeleted_options)
1627
-            );
1628
-        }
1629
-        if (! empty($errors)) {
1630
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1631
-        }
1632
-    }
1633
-
1634
-    /**
1635
-     * Gets the mysql error code from the last used query by wpdb
1636
-     *
1637
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1638
-     */
1639
-    public static function last_wpdb_error_code()
1640
-    {
1641
-        // phpcs:disable PHPCompatibility.PHP.RemovedExtensions.mysql_DeprecatedRemoved
1642
-        global $wpdb;
1643
-        if ($wpdb->use_mysqli) {
1644
-            return mysqli_errno($wpdb->dbh);
1645
-        } else {
1646
-            return mysql_errno($wpdb->dbh);
1647
-        }
1648
-        // phpcs:enable
1649
-    }
1650
-
1651
-    /**
1652
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1653
-     *
1654
-     * @global wpdb  $wpdb
1655
-     * @deprecated instead use TableAnalysis::tableExists()
1656
-     * @param string $table_name with or without $wpdb->prefix
1657
-     * @return boolean
1658
-     */
1659
-    public static function table_exists($table_name)
1660
-    {
1661
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1662
-    }
1663
-
1664
-    /**
1665
-     * Resets the cache on EEH_Activation
1666
-     */
1667
-    public static function reset()
1668
-    {
1669
-        self::$_default_creator_id                             = null;
1670
-        self::$_initialized_db_content_already_in_this_request = false;
1671
-    }
1672
-
1673
-    /**
1674
-     * Removes 'email_confirm' from the Address info question group on activation
1675
-     * @return void
1676
-     */
1677
-    public static function removeEmailConfirmFromAddressGroup()
1678
-    {
1679
-
1680
-        // Pull the email_confirm question ID.
1681
-        $email_confirm_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(
1682
-            EEM_Attendee::system_question_email_confirm
1683
-        );
1684
-        // Remove the email_confirm question group from the address group questions.
1685
-        EEM_Question_Group_Question::instance()->delete(
1686
-            array(
1687
-                array(
1688
-                    'QST_ID' => $email_confirm_question_id,
1689
-                    'Question_Group.QSG_system' => EEM_Question_Group::system_address,
1690
-                ),
1691
-            )
1692
-        );
1693
-    }
1242
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1243
+			$message_resource_manager
1244
+		);
1245
+		/**
1246
+		 * This method is verifying there are no NEW default message types
1247
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1248
+		 */
1249
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1250
+			$message_resource_manager
1251
+		);
1252
+		// after all is done, let's persist these changes to the db.
1253
+		$message_resource_manager->update_has_activated_messengers_option();
1254
+		$message_resource_manager->update_active_messengers_option();
1255
+		// will return true if either of these are true.  Otherwise will return false.
1256
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1257
+	}
1258
+
1259
+
1260
+
1261
+	/**
1262
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1263
+	 * @return array|bool
1264
+	 * @throws \EE_Error
1265
+	 */
1266
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1267
+		EE_Message_Resource_Manager $message_resource_manager
1268
+	) {
1269
+		/** @type EE_messenger[] $active_messengers */
1270
+		$active_messengers = $message_resource_manager->active_messengers();
1271
+		$installed_message_types = $message_resource_manager->installed_message_types();
1272
+		$templates_created = false;
1273
+		foreach ($active_messengers as $active_messenger) {
1274
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1275
+			$default_message_type_names_to_activate = array();
1276
+			// looping through each default message type reported by the messenger
1277
+			// and setup the actual message types to activate.
1278
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1279
+				// if already active or has already been activated before we skip
1280
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1281
+				// we also skip if the message type is not installed.
1282
+				if ($message_resource_manager->has_message_type_been_activated_for_messenger(
1283
+					$default_message_type_name_for_messenger,
1284
+					$active_messenger->name
1285
+				)
1286
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1287
+						$active_messenger->name,
1288
+						$default_message_type_name_for_messenger
1289
+					)
1290
+					|| ! isset($installed_message_types[ $default_message_type_name_for_messenger ])
1291
+				) {
1292
+					continue;
1293
+				}
1294
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1295
+			}
1296
+			// let's activate!
1297
+			$message_resource_manager->ensure_message_types_are_active(
1298
+				$default_message_type_names_to_activate,
1299
+				$active_messenger->name,
1300
+				false
1301
+			);
1302
+			// activate the templates for these message types
1303
+			if (! empty($default_message_type_names_to_activate)) {
1304
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1305
+					$active_messenger->name,
1306
+					$default_message_type_names_for_messenger,
1307
+					'',
1308
+					true
1309
+				);
1310
+			}
1311
+		}
1312
+		return $templates_created;
1313
+	}
1314
+
1315
+
1316
+
1317
+	/**
1318
+	 * This will activate and generate default messengers and default message types for those messengers.
1319
+	 *
1320
+	 * @param EE_message_Resource_Manager $message_resource_manager
1321
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1322
+	 *                     False means that there were no templates generated
1323
+	 *                     (which could simply mean there are no default message types for a messenger).
1324
+	 * @throws EE_Error
1325
+	 */
1326
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1327
+		EE_Message_Resource_Manager $message_resource_manager
1328
+	) {
1329
+		/** @type EE_messenger[] $messengers_to_generate */
1330
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1331
+		$installed_message_types = $message_resource_manager->installed_message_types();
1332
+		$templates_generated = false;
1333
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1334
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1335
+			// verify the default message types match an installed message type.
1336
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1337
+				if (! isset($installed_message_types[ $name ])
1338
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1339
+						$name,
1340
+						$messenger_to_generate->name
1341
+					)
1342
+				) {
1343
+					unset($default_message_type_names_for_messenger[ $key ]);
1344
+				}
1345
+			}
1346
+			// in previous iterations, the active_messengers option in the db
1347
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1348
+			// This comment is left here just in case we discover that we _do_ need to update before
1349
+			// passing off to create templates (after the refactor is done).
1350
+			// @todo remove this comment when determined not necessary.
1351
+			$message_resource_manager->activate_messenger(
1352
+				$messenger_to_generate,
1353
+				$default_message_type_names_for_messenger,
1354
+				false
1355
+			);
1356
+			// create any templates needing created (or will reactivate templates already generated as necessary).
1357
+			if (! empty($default_message_type_names_for_messenger)) {
1358
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1359
+					$messenger_to_generate->name,
1360
+					$default_message_type_names_for_messenger,
1361
+					'',
1362
+					true
1363
+				);
1364
+			}
1365
+		}
1366
+		return $templates_generated;
1367
+	}
1368
+
1369
+
1370
+	/**
1371
+	 * This returns the default messengers to generate templates for on activation of EE.
1372
+	 * It considers:
1373
+	 * - whether a messenger is already active in the db.
1374
+	 * - whether a messenger has been made active at any time in the past.
1375
+	 *
1376
+	 * @static
1377
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1378
+	 * @return EE_messenger[]
1379
+	 */
1380
+	protected static function _get_default_messengers_to_generate_on_activation(
1381
+		EE_Message_Resource_Manager $message_resource_manager
1382
+	) {
1383
+		$active_messengers    = $message_resource_manager->active_messengers();
1384
+		$installed_messengers = $message_resource_manager->installed_messengers();
1385
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1386
+
1387
+		$messengers_to_generate = array();
1388
+		foreach ($installed_messengers as $installed_messenger) {
1389
+			// if installed messenger is a messenger that should be activated on install
1390
+			// and is not already active
1391
+			// and has never been activated
1392
+			if (! $installed_messenger->activate_on_install
1393
+				|| isset($active_messengers[ $installed_messenger->name ])
1394
+				|| isset($has_activated[ $installed_messenger->name ])
1395
+			) {
1396
+				continue;
1397
+			}
1398
+			$messengers_to_generate[ $installed_messenger->name ] = $installed_messenger;
1399
+		}
1400
+		return $messengers_to_generate;
1401
+	}
1402
+
1403
+
1404
+	/**
1405
+	 * This simply validates active message types to ensure they actually match installed
1406
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1407
+	 * rows are set inactive.
1408
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1409
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1410
+	 * are still handled in here.
1411
+	 *
1412
+	 * @since 4.3.1
1413
+	 * @return void
1414
+	 */
1415
+	public static function validate_messages_system()
1416
+	{
1417
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1418
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1419
+		$message_resource_manager->validate_active_message_types_are_installed();
1420
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1421
+	}
1422
+
1423
+
1424
+	/**
1425
+	 * create_no_ticket_prices_array
1426
+	 *
1427
+	 * @access public
1428
+	 * @static
1429
+	 * @return void
1430
+	 */
1431
+	public static function create_no_ticket_prices_array()
1432
+	{
1433
+		// this creates an array for tracking events that have no active ticket prices created
1434
+		// this allows us to warn admins of the situation so that it can be corrected
1435
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1436
+		if (! $espresso_no_ticket_prices) {
1437
+			add_option('ee_no_ticket_prices', array(), '', false);
1438
+		}
1439
+	}
1440
+
1441
+
1442
+	/**
1443
+	 * plugin_deactivation
1444
+	 *
1445
+	 * @access public
1446
+	 * @static
1447
+	 * @return void
1448
+	 */
1449
+	public static function plugin_deactivation()
1450
+	{
1451
+	}
1452
+
1453
+
1454
+	/**
1455
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1456
+	 * (like post meta or term relations)
1457
+	 *
1458
+	 * @global wpdb $wpdb
1459
+	 * @throws \EE_Error
1460
+	 */
1461
+	public static function delete_all_espresso_cpt_data()
1462
+	{
1463
+		global $wpdb;
1464
+		// get all the CPT post_types
1465
+		$ee_post_types = array();
1466
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1467
+			if (method_exists($model_name, 'instance')) {
1468
+				$model_obj = call_user_func(array($model_name, 'instance'));
1469
+				if ($model_obj instanceof EEM_CPT_Base) {
1470
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1471
+				}
1472
+			}
1473
+		}
1474
+		// get all our CPTs
1475
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1476
+		$cpt_ids = $wpdb->get_col($query);
1477
+		// delete each post meta and term relations too
1478
+		foreach ($cpt_ids as $post_id) {
1479
+			wp_delete_post($post_id, true);
1480
+		}
1481
+	}
1482
+
1483
+	/**
1484
+	 * Deletes all EE custom tables
1485
+	 *
1486
+	 * @return array
1487
+	 */
1488
+	public static function drop_espresso_tables()
1489
+	{
1490
+		$tables = array();
1491
+		// load registry
1492
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1493
+			if (method_exists($model_name, 'instance')) {
1494
+				$model_obj = call_user_func(array($model_name, 'instance'));
1495
+				if ($model_obj instanceof EEM_Base) {
1496
+					foreach ($model_obj->get_tables() as $table) {
1497
+						if (strpos($table->get_table_name(), 'esp_')
1498
+							&&
1499
+							(
1500
+								is_main_site()// main site? nuke them all
1501
+								|| ! $table->is_global()// not main site,but not global either. nuke it
1502
+							)
1503
+						) {
1504
+							$tables[ $table->get_table_name() ] = $table->get_table_name();
1505
+						}
1506
+					}
1507
+				}
1508
+			}
1509
+		}
1510
+
1511
+		// there are some tables whose models were removed.
1512
+		// they should be removed when removing all EE core's data
1513
+		$tables_without_models = array(
1514
+			'esp_promotion',
1515
+			'esp_promotion_applied',
1516
+			'esp_promotion_object',
1517
+			'esp_promotion_rule',
1518
+			'esp_rule',
1519
+		);
1520
+		foreach ($tables_without_models as $table) {
1521
+			$tables[ $table ] = $table;
1522
+		}
1523
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1524
+	}
1525
+
1526
+
1527
+
1528
+	/**
1529
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1530
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1531
+	 * Returns the list actually deleted
1532
+	 *
1533
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1534
+	 * @global WPDB $wpdb
1535
+	 * @param array $table_names
1536
+	 * @return array of table names which we deleted
1537
+	 */
1538
+	public static function drop_tables($table_names)
1539
+	{
1540
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1541
+	}
1542
+
1543
+
1544
+
1545
+	/**
1546
+	 * plugin_uninstall
1547
+	 *
1548
+	 * @access public
1549
+	 * @static
1550
+	 * @param bool $remove_all
1551
+	 * @return void
1552
+	 */
1553
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1554
+	{
1555
+		global $wpdb;
1556
+		self::drop_espresso_tables();
1557
+		$wp_options_to_delete = array(
1558
+			'ee_no_ticket_prices'                => true,
1559
+			'ee_active_messengers'               => true,
1560
+			'ee_has_activated_messenger'         => true,
1561
+			RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1562
+			'ee_config'                          => false,
1563
+			'ee_data_migration_current_db_state' => true,
1564
+			'ee_data_migration_mapping_'         => false,
1565
+			'ee_data_migration_script_'          => false,
1566
+			'ee_data_migrations'                 => true,
1567
+			'ee_dms_map'                         => false,
1568
+			'ee_notices'                         => true,
1569
+			'lang_file_check_'                   => false,
1570
+			'ee_maintenance_mode'                => true,
1571
+			'ee_ueip_optin'                      => true,
1572
+			'ee_ueip_has_notified'               => true,
1573
+			'ee_plugin_activation_errors'        => true,
1574
+			'ee_id_mapping_from'                 => false,
1575
+			'espresso_persistent_admin_notices'  => true,
1576
+			'ee_encryption_key'                  => true,
1577
+			'pue_force_upgrade_'                 => false,
1578
+			'pue_json_error_'                    => false,
1579
+			'pue_install_key_'                   => false,
1580
+			'pue_verification_error_'            => false,
1581
+			'pu_dismissed_upgrade_'              => false,
1582
+			'external_updates-'                  => false,
1583
+			'ee_extra_data'                      => true,
1584
+			'ee_ssn_'                            => false,
1585
+			'ee_rss_'                            => false,
1586
+			'ee_rte_n_tx_'                       => false,
1587
+			'ee_pers_admin_notices'              => true,
1588
+			'ee_job_parameters_'                 => false,
1589
+			'ee_upload_directories_incomplete'   => true,
1590
+			'ee_verified_db_collations'          => true,
1591
+		);
1592
+		if (is_main_site()) {
1593
+			$wp_options_to_delete['ee_network_config'] = true;
1594
+		}
1595
+		$undeleted_options = array();
1596
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1597
+			if ($no_wildcard) {
1598
+				if (! delete_option($option_name)) {
1599
+					$undeleted_options[] = $option_name;
1600
+				}
1601
+			} else {
1602
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1603
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1604
+					if (! delete_option($option_name_from_wildcard)) {
1605
+						$undeleted_options[] = $option_name_from_wildcard;
1606
+					}
1607
+				}
1608
+			}
1609
+		}
1610
+		// also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1611
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1612
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1613
+			$db_update_sans_ee4 = array();
1614
+			foreach ($espresso_db_update as $version => $times_activated) {
1615
+				if ((string) $version[0] === '3') {// if its NON EE4
1616
+					$db_update_sans_ee4[ $version ] = $times_activated;
1617
+				}
1618
+			}
1619
+			update_option('espresso_db_update', $db_update_sans_ee4);
1620
+		}
1621
+		$errors = '';
1622
+		if (! empty($undeleted_options)) {
1623
+			$errors .= sprintf(
1624
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1625
+				'<br/>',
1626
+				implode(',<br/>', $undeleted_options)
1627
+			);
1628
+		}
1629
+		if (! empty($errors)) {
1630
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1631
+		}
1632
+	}
1633
+
1634
+	/**
1635
+	 * Gets the mysql error code from the last used query by wpdb
1636
+	 *
1637
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1638
+	 */
1639
+	public static function last_wpdb_error_code()
1640
+	{
1641
+		// phpcs:disable PHPCompatibility.PHP.RemovedExtensions.mysql_DeprecatedRemoved
1642
+		global $wpdb;
1643
+		if ($wpdb->use_mysqli) {
1644
+			return mysqli_errno($wpdb->dbh);
1645
+		} else {
1646
+			return mysql_errno($wpdb->dbh);
1647
+		}
1648
+		// phpcs:enable
1649
+	}
1650
+
1651
+	/**
1652
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1653
+	 *
1654
+	 * @global wpdb  $wpdb
1655
+	 * @deprecated instead use TableAnalysis::tableExists()
1656
+	 * @param string $table_name with or without $wpdb->prefix
1657
+	 * @return boolean
1658
+	 */
1659
+	public static function table_exists($table_name)
1660
+	{
1661
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1662
+	}
1663
+
1664
+	/**
1665
+	 * Resets the cache on EEH_Activation
1666
+	 */
1667
+	public static function reset()
1668
+	{
1669
+		self::$_default_creator_id                             = null;
1670
+		self::$_initialized_db_content_already_in_this_request = false;
1671
+	}
1672
+
1673
+	/**
1674
+	 * Removes 'email_confirm' from the Address info question group on activation
1675
+	 * @return void
1676
+	 */
1677
+	public static function removeEmailConfirmFromAddressGroup()
1678
+	{
1679
+
1680
+		// Pull the email_confirm question ID.
1681
+		$email_confirm_question_id = EEM_Question::instance()->get_Question_ID_from_system_string(
1682
+			EEM_Attendee::system_question_email_confirm
1683
+		);
1684
+		// Remove the email_confirm question group from the address group questions.
1685
+		EEM_Question_Group_Question::instance()->delete(
1686
+			array(
1687
+				array(
1688
+					'QST_ID' => $email_confirm_question_id,
1689
+					'Question_Group.QSG_system' => EEM_Question_Group::system_address,
1690
+				),
1691
+			)
1692
+		);
1693
+	}
1694 1694
 }
Please login to merge, or discard this patch.
core/EE_Addon.core.php 2 patches
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
     public function set_plugins_page_row($plugins_page_row = array())
299 299
     {
300 300
         // sigh.... check for example content that I stupidly merged to master and remove it if found
301
-        if (! is_array($plugins_page_row)
301
+        if ( ! is_array($plugins_page_row)
302 302
             && strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
303 303
         ) {
304 304
             $plugins_page_row = array();
@@ -575,7 +575,7 @@  discard block
 block discarded – undo
575 575
      */
576 576
     public function get_activation_indicator_option_name()
577 577
     {
578
-        return 'ee_activation_' . $this->name();
578
+        return 'ee_activation_'.$this->name();
579 579
     }
580 580
 
581 581
 
@@ -662,13 +662,13 @@  discard block
 block discarded – undo
662 662
      */
663 663
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
664 664
     {
665
-        if (! $version_history) {
665
+        if ( ! $version_history) {
666 666
             $version_history = $this->get_activation_history();
667 667
         }
668 668
         if ($current_version_to_add === null) {
669 669
             $current_version_to_add = $this->version();
670 670
         }
671
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
671
+        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
672 672
         // resave
673 673
         return update_option($this->get_activation_history_option_name(), $version_history);
674 674
     }
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
      */
682 682
     public function get_activation_history_option_name()
683 683
     {
684
-        return self::ee_addon_version_history_option_prefix . $this->name();
684
+        return self::ee_addon_version_history_option_prefix.$this->name();
685 685
     }
686 686
 
687 687
 
@@ -756,7 +756,7 @@  discard block
 block discarded – undo
756 756
         // is admin and not in M-Mode ?
757 757
         if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
758 758
             add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
759
-            add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
759
+            add_filter('after_plugin_row_'.$this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
760 760
         }
761 761
     }
762 762
 
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
             // before other links
776 776
             array_unshift(
777 777
                 $links,
778
-                '<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
778
+                '<a href="admin.php?page='.$this->plugin_action_slug().'">'
779 779
                 . esc_html__('Settings', 'event_espresso')
780 780
                 . '</a>'
781 781
             );
@@ -798,15 +798,15 @@  discard block
 block discarded – undo
798 798
     {
799 799
         $after_plugin_row = '';
800 800
         $plugins_page_row = $this->get_plugins_page_row();
801
-        if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
801
+        if ( ! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
802 802
             $class = $status ? 'active' : 'inactive';
803 803
             $link_text = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
804 804
             $link_url = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
805 805
             $description = isset($plugins_page_row['description'])
806 806
                 ? $plugins_page_row['description']
807 807
                 : '';
808
-            if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
809
-                $after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
808
+            if ( ! empty($link_text) && ! empty($link_url) && ! empty($description)) {
809
+                $after_plugin_row .= '<tr id="'.sanitize_title($plugin_file).'-ee-addon" class="'.$class.'">';
810 810
                 $after_plugin_row .= '<th class="check-column" scope="row"></th>';
811 811
                 $after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
812 812
                 $after_plugin_row .= '<style>
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 </style>';
849 849
                 $after_plugin_row .= '
850 850
 <p class="ee-addon-upsell-info-dv">
851
-	<a class="ee-button" href="' . $link_url . '">'
851
+	<a class="ee-button" href="' . $link_url.'">'
852 852
                                      . $link_text
853 853
                                      . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
854 854
                                      . '</a>
Please login to merge, or discard this patch.
Indentation   +843 added lines, -843 removed lines patch added patch discarded remove patch
@@ -19,797 +19,797 @@  discard block
 block discarded – undo
19 19
 {
20 20
 
21 21
 
22
-    /**
23
-     * prefix to be added onto an addon's plugin slug to make a wp option name
24
-     * which will be used to store the plugin's activation history
25
-     */
26
-    const ee_addon_version_history_option_prefix = 'ee_version_history_';
27
-
28
-    /**
29
-     * @var $_version
30
-     * @type string
31
-     */
32
-    protected $_version = '';
33
-
34
-    /**
35
-     * @var $_min_core_version
36
-     * @type string
37
-     */
38
-    protected $_min_core_version = '';
39
-
40
-    /**
41
-     * derived from plugin 'main_file_path using plugin_basename()
42
-     *
43
-     * @type string $_plugin_basename
44
-     */
45
-    protected $_plugin_basename = '';
46
-
47
-    /**
48
-     * A non-internationalized name to identify this addon for use in URLs, etc
49
-     *
50
-     * @type string $_plugin_slug
51
-     */
52
-    protected $_plugin_slug = '';
53
-
54
-    /**
55
-     * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
56
-     *
57
-     * @type string _addon_name
58
-     */
59
-    protected $_addon_name = '';
60
-
61
-    /**
62
-     * one of the EE_System::req_type_* constants
63
-     *
64
-     * @type int $_req_type
65
-     */
66
-    protected $_req_type;
67
-
68
-    /**
69
-     * page slug to be used when generating the "Settings" link on the WP plugin page
70
-     *
71
-     * @type string $_plugin_action_slug
72
-     */
73
-    protected $_plugin_action_slug = '';
74
-
75
-    /**
76
-     * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
77
-     * that can be used for adding upgrading/marketing info
78
-     *
79
-     * @type array $_plugins_page_row
80
-     */
81
-    protected $_plugins_page_row = array();
82
-
83
-
84
-    /**
85
-     *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
86
-     *
87
-     * @type string
88
-     */
89
-    protected $_main_plugin_file;
90
-
91
-    /**
92
-     *    This is the slug used to identify this add-on within the plugin update engine.
93
-     *
94
-     * @type string
95
-     */
96
-    protected $pue_slug;
97
-
98
-
99
-    /**
100
-     * @var EE_Dependency_Map $dependency_map
101
-     */
102
-    private $dependency_map;
103
-
104
-
105
-    /**
106
-     * @var DomainInterface $domain
107
-     */
108
-    private $domain;
109
-
110
-
111
-    /**
112
-     * @param EE_Dependency_Map $dependency_map [optional]
113
-     * @param DomainInterface   $domain         [optional]
114
-     */
115
-    public function __construct(EE_Dependency_Map $dependency_map = null, DomainInterface $domain = null)
116
-    {
117
-        if ($dependency_map instanceof EE_Dependency_Map) {
118
-            $this->setDependencyMap($dependency_map);
119
-        }
120
-        if ($domain instanceof DomainInterface) {
121
-            $this->setDomain($domain);
122
-        }
123
-        add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
124
-    }
125
-
126
-
127
-    /**
128
-     * @param EE_Dependency_Map $dependency_map
129
-     */
130
-    public function setDependencyMap($dependency_map)
131
-    {
132
-        $this->dependency_map = $dependency_map;
133
-    }
134
-
135
-
136
-    /**
137
-     * @return EE_Dependency_Map
138
-     */
139
-    public function dependencyMap()
140
-    {
141
-        return $this->dependency_map;
142
-    }
143
-
144
-
145
-    /**
146
-     * @param DomainInterface $domain
147
-     */
148
-    public function setDomain(DomainInterface $domain)
149
-    {
150
-        $this->domain = $domain;
151
-    }
152
-
153
-    /**
154
-     * @return DomainInterface
155
-     */
156
-    public function domain()
157
-    {
158
-        return $this->domain;
159
-    }
160
-
161
-
162
-    /**
163
-     * @param mixed $version
164
-     */
165
-    public function set_version($version = null)
166
-    {
167
-        $this->_version = $version;
168
-    }
169
-
170
-
171
-    /**
172
-     * get__version
173
-     *
174
-     * @return string
175
-     */
176
-    public function version()
177
-    {
178
-        return $this->_version;
179
-    }
180
-
181
-
182
-    /**
183
-     * @param mixed $min_core_version
184
-     */
185
-    public function set_min_core_version($min_core_version = null)
186
-    {
187
-        $this->_min_core_version = $min_core_version;
188
-    }
189
-
190
-
191
-    /**
192
-     * get__min_core_version
193
-     *
194
-     * @return string
195
-     */
196
-    public function min_core_version()
197
-    {
198
-        return $this->_min_core_version;
199
-    }
200
-
201
-
202
-    /**
203
-     * Sets addon_name
204
-     *
205
-     * @param string $addon_name
206
-     * @return boolean
207
-     */
208
-    public function set_name($addon_name)
209
-    {
210
-        return $this->_addon_name = $addon_name;
211
-    }
212
-
213
-
214
-    /**
215
-     * Gets addon_name
216
-     *
217
-     * @return string
218
-     */
219
-    public function name()
220
-    {
221
-        return $this->_addon_name;
222
-    }
223
-
224
-
225
-    /**
226
-     * @return string
227
-     */
228
-    public function plugin_basename()
229
-    {
230
-
231
-        return $this->_plugin_basename;
232
-    }
233
-
234
-
235
-    /**
236
-     * @param string $plugin_basename
237
-     */
238
-    public function set_plugin_basename($plugin_basename)
239
-    {
240
-
241
-        $this->_plugin_basename = $plugin_basename;
242
-    }
243
-
244
-
245
-    /**
246
-     * @return string
247
-     */
248
-    public function plugin_slug()
249
-    {
250
-
251
-        return $this->_plugin_slug;
252
-    }
253
-
254
-
255
-    /**
256
-     * @param string $plugin_slug
257
-     */
258
-    public function set_plugin_slug($plugin_slug)
259
-    {
260
-
261
-        $this->_plugin_slug = $plugin_slug;
262
-    }
263
-
264
-
265
-    /**
266
-     * @return string
267
-     */
268
-    public function plugin_action_slug()
269
-    {
270
-
271
-        return $this->_plugin_action_slug;
272
-    }
273
-
274
-
275
-    /**
276
-     * @param string $plugin_action_slug
277
-     */
278
-    public function set_plugin_action_slug($plugin_action_slug)
279
-    {
280
-
281
-        $this->_plugin_action_slug = $plugin_action_slug;
282
-    }
283
-
284
-
285
-    /**
286
-     * @return array
287
-     */
288
-    public function get_plugins_page_row()
289
-    {
290
-
291
-        return $this->_plugins_page_row;
292
-    }
293
-
294
-
295
-    /**
296
-     * @param array $plugins_page_row
297
-     */
298
-    public function set_plugins_page_row($plugins_page_row = array())
299
-    {
300
-        // sigh.... check for example content that I stupidly merged to master and remove it if found
301
-        if (! is_array($plugins_page_row)
302
-            && strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
303
-        ) {
304
-            $plugins_page_row = array();
305
-        }
306
-        $this->_plugins_page_row = (array) $plugins_page_row;
307
-    }
308
-
309
-
310
-    /**
311
-     * Called when EE core detects this addon has been activated for the first time.
312
-     * If the site isn't in maintenance mode, should setup the addon's database
313
-     *
314
-     * @return void
315
-     */
316
-    public function new_install()
317
-    {
318
-        $classname = get_class($this);
319
-        do_action("AHEE__{$classname}__new_install");
320
-        do_action('AHEE__EE_Addon__new_install', $this);
321
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
322
-        add_action(
323
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
324
-            array($this, 'initialize_db_if_no_migrations_required')
325
-        );
326
-    }
327
-
328
-
329
-    /**
330
-     * Called when EE core detects this addon has been reactivated. When this happens,
331
-     * it's good to just check that your data is still intact
332
-     *
333
-     * @return void
334
-     */
335
-    public function reactivation()
336
-    {
337
-        $classname = get_class($this);
338
-        do_action("AHEE__{$classname}__reactivation");
339
-        do_action('AHEE__EE_Addon__reactivation', $this);
340
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
341
-        add_action(
342
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
343
-            array($this, 'initialize_db_if_no_migrations_required')
344
-        );
345
-    }
346
-
347
-
348
-    /**
349
-     * Called when the registered deactivation hook for this addon fires.
350
-     *
351
-     * @throws EE_Error
352
-     */
353
-    public function deactivation()
354
-    {
355
-        $classname = get_class($this);
356
-        do_action("AHEE__{$classname}__deactivation");
357
-        do_action('AHEE__EE_Addon__deactivation', $this);
358
-        // check if the site no longer needs to be in maintenance mode
359
-        EE_Register_Addon::deregister($this->name());
360
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
361
-    }
362
-
363
-
364
-    /**
365
-     * Takes care of double-checking that we're not in maintenance mode, and then
366
-     * initializing this addon's necessary initial data. This is called by default on new activations
367
-     * and reactivations.
368
-     *
369
-     * @param boolean $verify_schema whether to verify the database's schema for this addon, or just its data.
370
-     *                               This is a resource-intensive job so we prefer to only do it when necessary
371
-     * @return void
372
-     * @throws \EE_Error
373
-     * @throws InvalidInterfaceException
374
-     * @throws InvalidDataTypeException
375
-     * @throws InvalidArgumentException
376
-     */
377
-    public function initialize_db_if_no_migrations_required($verify_schema = true)
378
-    {
379
-        if ($verify_schema === '') {
380
-            // wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
381
-            // (ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
382
-            // calls them with an argument of an empty string (ie ""), which evaluates to false
383
-            // so we need to treat the empty string as if nothing had been passed, and should instead use the default
384
-            $verify_schema = true;
385
-        }
386
-        if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
387
-            if ($verify_schema) {
388
-                $this->initialize_db();
389
-            }
390
-            $this->initialize_default_data();
391
-            // @todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
392
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to(
393
-                array(
394
-                    'slug'    => $this->name(),
395
-                    'version' => $this->version(),
396
-                )
397
-            );
398
-            /* make sure core's data is a-ok
22
+	/**
23
+	 * prefix to be added onto an addon's plugin slug to make a wp option name
24
+	 * which will be used to store the plugin's activation history
25
+	 */
26
+	const ee_addon_version_history_option_prefix = 'ee_version_history_';
27
+
28
+	/**
29
+	 * @var $_version
30
+	 * @type string
31
+	 */
32
+	protected $_version = '';
33
+
34
+	/**
35
+	 * @var $_min_core_version
36
+	 * @type string
37
+	 */
38
+	protected $_min_core_version = '';
39
+
40
+	/**
41
+	 * derived from plugin 'main_file_path using plugin_basename()
42
+	 *
43
+	 * @type string $_plugin_basename
44
+	 */
45
+	protected $_plugin_basename = '';
46
+
47
+	/**
48
+	 * A non-internationalized name to identify this addon for use in URLs, etc
49
+	 *
50
+	 * @type string $_plugin_slug
51
+	 */
52
+	protected $_plugin_slug = '';
53
+
54
+	/**
55
+	 * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
56
+	 *
57
+	 * @type string _addon_name
58
+	 */
59
+	protected $_addon_name = '';
60
+
61
+	/**
62
+	 * one of the EE_System::req_type_* constants
63
+	 *
64
+	 * @type int $_req_type
65
+	 */
66
+	protected $_req_type;
67
+
68
+	/**
69
+	 * page slug to be used when generating the "Settings" link on the WP plugin page
70
+	 *
71
+	 * @type string $_plugin_action_slug
72
+	 */
73
+	protected $_plugin_action_slug = '';
74
+
75
+	/**
76
+	 * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
77
+	 * that can be used for adding upgrading/marketing info
78
+	 *
79
+	 * @type array $_plugins_page_row
80
+	 */
81
+	protected $_plugins_page_row = array();
82
+
83
+
84
+	/**
85
+	 *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
86
+	 *
87
+	 * @type string
88
+	 */
89
+	protected $_main_plugin_file;
90
+
91
+	/**
92
+	 *    This is the slug used to identify this add-on within the plugin update engine.
93
+	 *
94
+	 * @type string
95
+	 */
96
+	protected $pue_slug;
97
+
98
+
99
+	/**
100
+	 * @var EE_Dependency_Map $dependency_map
101
+	 */
102
+	private $dependency_map;
103
+
104
+
105
+	/**
106
+	 * @var DomainInterface $domain
107
+	 */
108
+	private $domain;
109
+
110
+
111
+	/**
112
+	 * @param EE_Dependency_Map $dependency_map [optional]
113
+	 * @param DomainInterface   $domain         [optional]
114
+	 */
115
+	public function __construct(EE_Dependency_Map $dependency_map = null, DomainInterface $domain = null)
116
+	{
117
+		if ($dependency_map instanceof EE_Dependency_Map) {
118
+			$this->setDependencyMap($dependency_map);
119
+		}
120
+		if ($domain instanceof DomainInterface) {
121
+			$this->setDomain($domain);
122
+		}
123
+		add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
124
+	}
125
+
126
+
127
+	/**
128
+	 * @param EE_Dependency_Map $dependency_map
129
+	 */
130
+	public function setDependencyMap($dependency_map)
131
+	{
132
+		$this->dependency_map = $dependency_map;
133
+	}
134
+
135
+
136
+	/**
137
+	 * @return EE_Dependency_Map
138
+	 */
139
+	public function dependencyMap()
140
+	{
141
+		return $this->dependency_map;
142
+	}
143
+
144
+
145
+	/**
146
+	 * @param DomainInterface $domain
147
+	 */
148
+	public function setDomain(DomainInterface $domain)
149
+	{
150
+		$this->domain = $domain;
151
+	}
152
+
153
+	/**
154
+	 * @return DomainInterface
155
+	 */
156
+	public function domain()
157
+	{
158
+		return $this->domain;
159
+	}
160
+
161
+
162
+	/**
163
+	 * @param mixed $version
164
+	 */
165
+	public function set_version($version = null)
166
+	{
167
+		$this->_version = $version;
168
+	}
169
+
170
+
171
+	/**
172
+	 * get__version
173
+	 *
174
+	 * @return string
175
+	 */
176
+	public function version()
177
+	{
178
+		return $this->_version;
179
+	}
180
+
181
+
182
+	/**
183
+	 * @param mixed $min_core_version
184
+	 */
185
+	public function set_min_core_version($min_core_version = null)
186
+	{
187
+		$this->_min_core_version = $min_core_version;
188
+	}
189
+
190
+
191
+	/**
192
+	 * get__min_core_version
193
+	 *
194
+	 * @return string
195
+	 */
196
+	public function min_core_version()
197
+	{
198
+		return $this->_min_core_version;
199
+	}
200
+
201
+
202
+	/**
203
+	 * Sets addon_name
204
+	 *
205
+	 * @param string $addon_name
206
+	 * @return boolean
207
+	 */
208
+	public function set_name($addon_name)
209
+	{
210
+		return $this->_addon_name = $addon_name;
211
+	}
212
+
213
+
214
+	/**
215
+	 * Gets addon_name
216
+	 *
217
+	 * @return string
218
+	 */
219
+	public function name()
220
+	{
221
+		return $this->_addon_name;
222
+	}
223
+
224
+
225
+	/**
226
+	 * @return string
227
+	 */
228
+	public function plugin_basename()
229
+	{
230
+
231
+		return $this->_plugin_basename;
232
+	}
233
+
234
+
235
+	/**
236
+	 * @param string $plugin_basename
237
+	 */
238
+	public function set_plugin_basename($plugin_basename)
239
+	{
240
+
241
+		$this->_plugin_basename = $plugin_basename;
242
+	}
243
+
244
+
245
+	/**
246
+	 * @return string
247
+	 */
248
+	public function plugin_slug()
249
+	{
250
+
251
+		return $this->_plugin_slug;
252
+	}
253
+
254
+
255
+	/**
256
+	 * @param string $plugin_slug
257
+	 */
258
+	public function set_plugin_slug($plugin_slug)
259
+	{
260
+
261
+		$this->_plugin_slug = $plugin_slug;
262
+	}
263
+
264
+
265
+	/**
266
+	 * @return string
267
+	 */
268
+	public function plugin_action_slug()
269
+	{
270
+
271
+		return $this->_plugin_action_slug;
272
+	}
273
+
274
+
275
+	/**
276
+	 * @param string $plugin_action_slug
277
+	 */
278
+	public function set_plugin_action_slug($plugin_action_slug)
279
+	{
280
+
281
+		$this->_plugin_action_slug = $plugin_action_slug;
282
+	}
283
+
284
+
285
+	/**
286
+	 * @return array
287
+	 */
288
+	public function get_plugins_page_row()
289
+	{
290
+
291
+		return $this->_plugins_page_row;
292
+	}
293
+
294
+
295
+	/**
296
+	 * @param array $plugins_page_row
297
+	 */
298
+	public function set_plugins_page_row($plugins_page_row = array())
299
+	{
300
+		// sigh.... check for example content that I stupidly merged to master and remove it if found
301
+		if (! is_array($plugins_page_row)
302
+			&& strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
303
+		) {
304
+			$plugins_page_row = array();
305
+		}
306
+		$this->_plugins_page_row = (array) $plugins_page_row;
307
+	}
308
+
309
+
310
+	/**
311
+	 * Called when EE core detects this addon has been activated for the first time.
312
+	 * If the site isn't in maintenance mode, should setup the addon's database
313
+	 *
314
+	 * @return void
315
+	 */
316
+	public function new_install()
317
+	{
318
+		$classname = get_class($this);
319
+		do_action("AHEE__{$classname}__new_install");
320
+		do_action('AHEE__EE_Addon__new_install', $this);
321
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
322
+		add_action(
323
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
324
+			array($this, 'initialize_db_if_no_migrations_required')
325
+		);
326
+	}
327
+
328
+
329
+	/**
330
+	 * Called when EE core detects this addon has been reactivated. When this happens,
331
+	 * it's good to just check that your data is still intact
332
+	 *
333
+	 * @return void
334
+	 */
335
+	public function reactivation()
336
+	{
337
+		$classname = get_class($this);
338
+		do_action("AHEE__{$classname}__reactivation");
339
+		do_action('AHEE__EE_Addon__reactivation', $this);
340
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
341
+		add_action(
342
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
343
+			array($this, 'initialize_db_if_no_migrations_required')
344
+		);
345
+	}
346
+
347
+
348
+	/**
349
+	 * Called when the registered deactivation hook for this addon fires.
350
+	 *
351
+	 * @throws EE_Error
352
+	 */
353
+	public function deactivation()
354
+	{
355
+		$classname = get_class($this);
356
+		do_action("AHEE__{$classname}__deactivation");
357
+		do_action('AHEE__EE_Addon__deactivation', $this);
358
+		// check if the site no longer needs to be in maintenance mode
359
+		EE_Register_Addon::deregister($this->name());
360
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
361
+	}
362
+
363
+
364
+	/**
365
+	 * Takes care of double-checking that we're not in maintenance mode, and then
366
+	 * initializing this addon's necessary initial data. This is called by default on new activations
367
+	 * and reactivations.
368
+	 *
369
+	 * @param boolean $verify_schema whether to verify the database's schema for this addon, or just its data.
370
+	 *                               This is a resource-intensive job so we prefer to only do it when necessary
371
+	 * @return void
372
+	 * @throws \EE_Error
373
+	 * @throws InvalidInterfaceException
374
+	 * @throws InvalidDataTypeException
375
+	 * @throws InvalidArgumentException
376
+	 */
377
+	public function initialize_db_if_no_migrations_required($verify_schema = true)
378
+	{
379
+		if ($verify_schema === '') {
380
+			// wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
381
+			// (ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
382
+			// calls them with an argument of an empty string (ie ""), which evaluates to false
383
+			// so we need to treat the empty string as if nothing had been passed, and should instead use the default
384
+			$verify_schema = true;
385
+		}
386
+		if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
387
+			if ($verify_schema) {
388
+				$this->initialize_db();
389
+			}
390
+			$this->initialize_default_data();
391
+			// @todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
392
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to(
393
+				array(
394
+					'slug'    => $this->name(),
395
+					'version' => $this->version(),
396
+				)
397
+			);
398
+			/* make sure core's data is a-ok
399 399
              * (at the time of writing, we especially want to verify all the caps are present
400 400
              * because payment method type capabilities are added dynamically, and it's
401 401
              * possible this addon added a payment method. But it's also possible
402 402
              * other data needs to be verified)
403 403
              */
404
-            EEH_Activation::initialize_db_content();
405
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
406
-            $rewrite_rules = LoaderFactory::getLoader()->getShared(
407
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
408
-            );
409
-            $rewrite_rules->flushRewriteRules();
410
-            // in case there are lots of addons being activated at once, let's force garbage collection
411
-            // to help avoid memory limit errors
412
-            // EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
413
-            gc_collect_cycles();
414
-        } else {
415
-            // ask the data migration manager to init this addon's data
416
-            // when migrations are finished because we can't do it now
417
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
418
-        }
419
-    }
420
-
421
-
422
-    /**
423
-     * Used to setup this addon's database tables, but not necessarily any default
424
-     * data in them. The default is to actually use the most up-to-date data migration script
425
-     * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
426
-     * methods to setup the db.
427
-     */
428
-    public function initialize_db()
429
-    {
430
-        // find the migration script that sets the database to be compatible with the code
431
-        $current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
432
-        if ($current_dms_name) {
433
-            $current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
434
-            $current_data_migration_script->set_migrating(false);
435
-            $current_data_migration_script->schema_changes_before_migration();
436
-            $current_data_migration_script->schema_changes_after_migration();
437
-            if ($current_data_migration_script->get_errors()) {
438
-                foreach ($current_data_migration_script->get_errors() as $error) {
439
-                    EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
440
-                }
441
-            }
442
-        }
443
-        // if not DMS was found that should be ok. This addon just doesn't require any database changes
444
-        EE_Data_Migration_Manager::instance()->update_current_database_state_to(
445
-            array(
446
-                'slug'    => $this->name(),
447
-                'version' => $this->version(),
448
-            )
449
-        );
450
-    }
451
-
452
-
453
-    /**
454
-     * If you want to setup default data for the addon, override this method, and call
455
-     * parent::initialize_default_data() from within it. This is normally called
456
-     * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
457
-     * and should verify default data is present (but this is also called
458
-     * on reactivations and just after migrations, so please verify you actually want
459
-     * to ADD default data, because it may already be present).
460
-     * However, please call this parent (currently it just fires a hook which other
461
-     * addons may be depending on)
462
-     */
463
-    public function initialize_default_data()
464
-    {
465
-        /**
466
-         * Called when an addon is ensuring its default data is set (possibly called
467
-         * on a reactivation, so first check for the absence of other data before setting
468
-         * default data)
469
-         *
470
-         * @param EE_Addon $addon the addon that called this
471
-         */
472
-        do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
473
-        // override to insert default data. It is safe to use the models here
474
-        // because the site should not be in maintenance mode
475
-    }
476
-
477
-
478
-    /**
479
-     * EE Core detected that this addon has been upgraded. We should check if there
480
-     * are any new migration scripts, and if so put the site into maintenance mode until
481
-     * they're ran
482
-     *
483
-     * @return void
484
-     */
485
-    public function upgrade()
486
-    {
487
-        $classname = get_class($this);
488
-        do_action("AHEE__{$classname}__upgrade");
489
-        do_action('AHEE__EE_Addon__upgrade', $this);
490
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
491
-        // also it's possible there is new default data that needs to be added
492
-        add_action(
493
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
494
-            array($this, 'initialize_db_if_no_migrations_required')
495
-        );
496
-    }
497
-
498
-
499
-    /**
500
-     * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
501
-     */
502
-    public function downgrade()
503
-    {
504
-        $classname = get_class($this);
505
-        do_action("AHEE__{$classname}__downgrade");
506
-        do_action('AHEE__EE_Addon__downgrade', $this);
507
-        // it's possible there's old default data that needs to be double-checked
508
-        add_action(
509
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
510
-            array($this, 'initialize_db_if_no_migrations_required')
511
-        );
512
-    }
513
-
514
-
515
-    /**
516
-     * set_db_update_option_name
517
-     * Until we do something better, we'll just check for migration scripts upon
518
-     * plugin activation only. In the future, we'll want to do it on plugin updates too
519
-     *
520
-     * @return bool
521
-     */
522
-    public function set_db_update_option_name()
523
-    {
524
-        EE_Error::doing_it_wrong(
525
-            __FUNCTION__,
526
-            esc_html__(
527
-                'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
528
-                'event_espresso'
529
-            ),
530
-            '4.3.0.alpha.016'
531
-        );
532
-        // let's just handle this on the next request, ok? right now we're just not really ready
533
-        return $this->set_activation_indicator_option();
534
-    }
535
-
536
-
537
-    /**
538
-     * Returns the name of the activation indicator option
539
-     * (an option which is set temporarily to indicate that this addon was just activated)
540
-     *
541
-     * @deprecated since version 4.3.0.alpha.016
542
-     * @return string
543
-     */
544
-    public function get_db_update_option_name()
545
-    {
546
-        EE_Error::doing_it_wrong(
547
-            __FUNCTION__,
548
-            esc_html__(
549
-                'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
550
-                'event_espresso'
551
-            ),
552
-            '4.3.0.alpha.016'
553
-        );
554
-        return $this->get_activation_indicator_option_name();
555
-    }
556
-
557
-
558
-    /**
559
-     * When the addon is activated, this should be called to set a wordpress option that
560
-     * indicates it was activated. This is especially useful for detecting reactivations.
561
-     *
562
-     * @return bool
563
-     */
564
-    public function set_activation_indicator_option()
565
-    {
566
-        // let's just handle this on the next request, ok? right now we're just not really ready
567
-        return update_option($this->get_activation_indicator_option_name(), true);
568
-    }
569
-
570
-
571
-    /**
572
-     * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
573
-     *
574
-     * @return string
575
-     */
576
-    public function get_activation_indicator_option_name()
577
-    {
578
-        return 'ee_activation_' . $this->name();
579
-    }
580
-
581
-
582
-    /**
583
-     * Used by EE_System to set the request type of this addon. Should not be used by addon developers
584
-     *
585
-     * @param int $req_type
586
-     */
587
-    public function set_req_type($req_type)
588
-    {
589
-        $this->_req_type = $req_type;
590
-    }
591
-
592
-
593
-    /**
594
-     * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
595
-     * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
596
-     * EE_System when it is checking for new install or upgrades of addons
597
-     */
598
-    public function detect_req_type($redetect = false)
599
-    {
600
-        if ($this->_req_type === null || $redetect) {
601
-            $this->detect_activation_or_upgrade();
602
-        }
603
-        return $this->_req_type;
604
-    }
605
-
606
-
607
-    /**
608
-     * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
609
-     * Should only be called once per request
610
-     *
611
-     * @return void
612
-     */
613
-    public function detect_activation_or_upgrade()
614
-    {
615
-        $activation_history_for_addon = $this->get_activation_history();
616
-        $request_type = EE_System::detect_req_type_given_activation_history(
617
-            $activation_history_for_addon,
618
-            $this->get_activation_indicator_option_name(),
619
-            $this->version()
620
-        );
621
-        $this->set_req_type($request_type);
622
-        $classname = get_class($this);
623
-        switch ($request_type) {
624
-            case EE_System::req_type_new_activation:
625
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
626
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
627
-                $this->new_install();
628
-                $this->update_list_of_installed_versions($activation_history_for_addon);
629
-                break;
630
-            case EE_System::req_type_reactivation:
631
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
632
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
633
-                $this->reactivation();
634
-                $this->update_list_of_installed_versions($activation_history_for_addon);
635
-                break;
636
-            case EE_System::req_type_upgrade:
637
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
638
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
639
-                $this->upgrade();
640
-                $this->update_list_of_installed_versions($activation_history_for_addon);
641
-                break;
642
-            case EE_System::req_type_downgrade:
643
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
644
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
645
-                $this->downgrade();
646
-                $this->update_list_of_installed_versions($activation_history_for_addon);
647
-                break;
648
-            case EE_System::req_type_normal:
649
-            default:
650
-                break;
651
-        }
652
-
653
-        do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
654
-    }
655
-
656
-    /**
657
-     * Updates the version history for this addon
658
-     *
659
-     * @param array  $version_history
660
-     * @param string $current_version_to_add
661
-     * @return boolean success
662
-     */
663
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
664
-    {
665
-        if (! $version_history) {
666
-            $version_history = $this->get_activation_history();
667
-        }
668
-        if ($current_version_to_add === null) {
669
-            $current_version_to_add = $this->version();
670
-        }
671
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
672
-        // resave
673
-        return update_option($this->get_activation_history_option_name(), $version_history);
674
-    }
675
-
676
-    /**
677
-     * Gets the name of the wp option that stores the activation history
678
-     * of this addon
679
-     *
680
-     * @return string
681
-     */
682
-    public function get_activation_history_option_name()
683
-    {
684
-        return self::ee_addon_version_history_option_prefix . $this->name();
685
-    }
686
-
687
-
688
-    /**
689
-     * Gets the wp option which stores the activation history for this addon
690
-     *
691
-     * @return array
692
-     */
693
-    public function get_activation_history()
694
-    {
695
-        return get_option($this->get_activation_history_option_name(), null);
696
-    }
697
-
698
-
699
-    /**
700
-     * @param string $config_section
701
-     */
702
-    public function set_config_section($config_section = '')
703
-    {
704
-        $this->_config_section = ! empty($config_section) ? $config_section : 'addons';
705
-    }
706
-
707
-    /**
708
-     * Sets the filepath to the main plugin file
709
-     *
710
-     * @param string $filepath
711
-     */
712
-    public function set_main_plugin_file($filepath)
713
-    {
714
-        $this->_main_plugin_file = $filepath;
715
-    }
716
-
717
-    /**
718
-     * gets the filepath to teh main file
719
-     *
720
-     * @return string
721
-     */
722
-    public function get_main_plugin_file()
723
-    {
724
-        return $this->_main_plugin_file;
725
-    }
726
-
727
-    /**
728
-     * Gets the filename (no path) of the main file (the main file loaded
729
-     * by WP)
730
-     *
731
-     * @return string
732
-     */
733
-    public function get_main_plugin_file_basename()
734
-    {
735
-        return plugin_basename($this->get_main_plugin_file());
736
-    }
737
-
738
-    /**
739
-     * Gets the folder name which contains the main plugin file
740
-     *
741
-     * @return string
742
-     */
743
-    public function get_main_plugin_file_dirname()
744
-    {
745
-        return dirname($this->get_main_plugin_file());
746
-    }
747
-
748
-
749
-    /**
750
-     * sets hooks used in the admin
751
-     *
752
-     * @return void
753
-     */
754
-    public function admin_init()
755
-    {
756
-        // is admin and not in M-Mode ?
757
-        if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
758
-            add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
759
-            add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
760
-        }
761
-    }
762
-
763
-
764
-    /**
765
-     * plugin_actions
766
-     * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
767
-     *
768
-     * @param $links
769
-     * @param $file
770
-     * @return array
771
-     */
772
-    public function plugin_action_links($links, $file)
773
-    {
774
-        if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
775
-            // before other links
776
-            array_unshift(
777
-                $links,
778
-                '<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
779
-                . esc_html__('Settings', 'event_espresso')
780
-                . '</a>'
781
-            );
782
-        }
783
-        return $links;
784
-    }
785
-
786
-
787
-    /**
788
-     * after_plugin_row
789
-     * Add additional content to the plugins page plugin row
790
-     * Inserts another row
791
-     *
792
-     * @param $plugin_file
793
-     * @param $plugin_data
794
-     * @param $status
795
-     * @return void
796
-     */
797
-    public function after_plugin_row($plugin_file, $plugin_data, $status)
798
-    {
799
-        $after_plugin_row = '';
800
-        $plugins_page_row = $this->get_plugins_page_row();
801
-        if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
802
-            $class = $status ? 'active' : 'inactive';
803
-            $link_text = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
804
-            $link_url = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
805
-            $description = isset($plugins_page_row['description'])
806
-                ? $plugins_page_row['description']
807
-                : '';
808
-            if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
809
-                $after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
810
-                $after_plugin_row .= '<th class="check-column" scope="row"></th>';
811
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
812
-                $after_plugin_row .= '<style>
404
+			EEH_Activation::initialize_db_content();
405
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
406
+			$rewrite_rules = LoaderFactory::getLoader()->getShared(
407
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
408
+			);
409
+			$rewrite_rules->flushRewriteRules();
410
+			// in case there are lots of addons being activated at once, let's force garbage collection
411
+			// to help avoid memory limit errors
412
+			// EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
413
+			gc_collect_cycles();
414
+		} else {
415
+			// ask the data migration manager to init this addon's data
416
+			// when migrations are finished because we can't do it now
417
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
418
+		}
419
+	}
420
+
421
+
422
+	/**
423
+	 * Used to setup this addon's database tables, but not necessarily any default
424
+	 * data in them. The default is to actually use the most up-to-date data migration script
425
+	 * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
426
+	 * methods to setup the db.
427
+	 */
428
+	public function initialize_db()
429
+	{
430
+		// find the migration script that sets the database to be compatible with the code
431
+		$current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
432
+		if ($current_dms_name) {
433
+			$current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
434
+			$current_data_migration_script->set_migrating(false);
435
+			$current_data_migration_script->schema_changes_before_migration();
436
+			$current_data_migration_script->schema_changes_after_migration();
437
+			if ($current_data_migration_script->get_errors()) {
438
+				foreach ($current_data_migration_script->get_errors() as $error) {
439
+					EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
440
+				}
441
+			}
442
+		}
443
+		// if not DMS was found that should be ok. This addon just doesn't require any database changes
444
+		EE_Data_Migration_Manager::instance()->update_current_database_state_to(
445
+			array(
446
+				'slug'    => $this->name(),
447
+				'version' => $this->version(),
448
+			)
449
+		);
450
+	}
451
+
452
+
453
+	/**
454
+	 * If you want to setup default data for the addon, override this method, and call
455
+	 * parent::initialize_default_data() from within it. This is normally called
456
+	 * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
457
+	 * and should verify default data is present (but this is also called
458
+	 * on reactivations and just after migrations, so please verify you actually want
459
+	 * to ADD default data, because it may already be present).
460
+	 * However, please call this parent (currently it just fires a hook which other
461
+	 * addons may be depending on)
462
+	 */
463
+	public function initialize_default_data()
464
+	{
465
+		/**
466
+		 * Called when an addon is ensuring its default data is set (possibly called
467
+		 * on a reactivation, so first check for the absence of other data before setting
468
+		 * default data)
469
+		 *
470
+		 * @param EE_Addon $addon the addon that called this
471
+		 */
472
+		do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
473
+		// override to insert default data. It is safe to use the models here
474
+		// because the site should not be in maintenance mode
475
+	}
476
+
477
+
478
+	/**
479
+	 * EE Core detected that this addon has been upgraded. We should check if there
480
+	 * are any new migration scripts, and if so put the site into maintenance mode until
481
+	 * they're ran
482
+	 *
483
+	 * @return void
484
+	 */
485
+	public function upgrade()
486
+	{
487
+		$classname = get_class($this);
488
+		do_action("AHEE__{$classname}__upgrade");
489
+		do_action('AHEE__EE_Addon__upgrade', $this);
490
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
491
+		// also it's possible there is new default data that needs to be added
492
+		add_action(
493
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
494
+			array($this, 'initialize_db_if_no_migrations_required')
495
+		);
496
+	}
497
+
498
+
499
+	/**
500
+	 * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
501
+	 */
502
+	public function downgrade()
503
+	{
504
+		$classname = get_class($this);
505
+		do_action("AHEE__{$classname}__downgrade");
506
+		do_action('AHEE__EE_Addon__downgrade', $this);
507
+		// it's possible there's old default data that needs to be double-checked
508
+		add_action(
509
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
510
+			array($this, 'initialize_db_if_no_migrations_required')
511
+		);
512
+	}
513
+
514
+
515
+	/**
516
+	 * set_db_update_option_name
517
+	 * Until we do something better, we'll just check for migration scripts upon
518
+	 * plugin activation only. In the future, we'll want to do it on plugin updates too
519
+	 *
520
+	 * @return bool
521
+	 */
522
+	public function set_db_update_option_name()
523
+	{
524
+		EE_Error::doing_it_wrong(
525
+			__FUNCTION__,
526
+			esc_html__(
527
+				'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
528
+				'event_espresso'
529
+			),
530
+			'4.3.0.alpha.016'
531
+		);
532
+		// let's just handle this on the next request, ok? right now we're just not really ready
533
+		return $this->set_activation_indicator_option();
534
+	}
535
+
536
+
537
+	/**
538
+	 * Returns the name of the activation indicator option
539
+	 * (an option which is set temporarily to indicate that this addon was just activated)
540
+	 *
541
+	 * @deprecated since version 4.3.0.alpha.016
542
+	 * @return string
543
+	 */
544
+	public function get_db_update_option_name()
545
+	{
546
+		EE_Error::doing_it_wrong(
547
+			__FUNCTION__,
548
+			esc_html__(
549
+				'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
550
+				'event_espresso'
551
+			),
552
+			'4.3.0.alpha.016'
553
+		);
554
+		return $this->get_activation_indicator_option_name();
555
+	}
556
+
557
+
558
+	/**
559
+	 * When the addon is activated, this should be called to set a wordpress option that
560
+	 * indicates it was activated. This is especially useful for detecting reactivations.
561
+	 *
562
+	 * @return bool
563
+	 */
564
+	public function set_activation_indicator_option()
565
+	{
566
+		// let's just handle this on the next request, ok? right now we're just not really ready
567
+		return update_option($this->get_activation_indicator_option_name(), true);
568
+	}
569
+
570
+
571
+	/**
572
+	 * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
573
+	 *
574
+	 * @return string
575
+	 */
576
+	public function get_activation_indicator_option_name()
577
+	{
578
+		return 'ee_activation_' . $this->name();
579
+	}
580
+
581
+
582
+	/**
583
+	 * Used by EE_System to set the request type of this addon. Should not be used by addon developers
584
+	 *
585
+	 * @param int $req_type
586
+	 */
587
+	public function set_req_type($req_type)
588
+	{
589
+		$this->_req_type = $req_type;
590
+	}
591
+
592
+
593
+	/**
594
+	 * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
595
+	 * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
596
+	 * EE_System when it is checking for new install or upgrades of addons
597
+	 */
598
+	public function detect_req_type($redetect = false)
599
+	{
600
+		if ($this->_req_type === null || $redetect) {
601
+			$this->detect_activation_or_upgrade();
602
+		}
603
+		return $this->_req_type;
604
+	}
605
+
606
+
607
+	/**
608
+	 * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
609
+	 * Should only be called once per request
610
+	 *
611
+	 * @return void
612
+	 */
613
+	public function detect_activation_or_upgrade()
614
+	{
615
+		$activation_history_for_addon = $this->get_activation_history();
616
+		$request_type = EE_System::detect_req_type_given_activation_history(
617
+			$activation_history_for_addon,
618
+			$this->get_activation_indicator_option_name(),
619
+			$this->version()
620
+		);
621
+		$this->set_req_type($request_type);
622
+		$classname = get_class($this);
623
+		switch ($request_type) {
624
+			case EE_System::req_type_new_activation:
625
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
626
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
627
+				$this->new_install();
628
+				$this->update_list_of_installed_versions($activation_history_for_addon);
629
+				break;
630
+			case EE_System::req_type_reactivation:
631
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
632
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
633
+				$this->reactivation();
634
+				$this->update_list_of_installed_versions($activation_history_for_addon);
635
+				break;
636
+			case EE_System::req_type_upgrade:
637
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
638
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
639
+				$this->upgrade();
640
+				$this->update_list_of_installed_versions($activation_history_for_addon);
641
+				break;
642
+			case EE_System::req_type_downgrade:
643
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
644
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
645
+				$this->downgrade();
646
+				$this->update_list_of_installed_versions($activation_history_for_addon);
647
+				break;
648
+			case EE_System::req_type_normal:
649
+			default:
650
+				break;
651
+		}
652
+
653
+		do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
654
+	}
655
+
656
+	/**
657
+	 * Updates the version history for this addon
658
+	 *
659
+	 * @param array  $version_history
660
+	 * @param string $current_version_to_add
661
+	 * @return boolean success
662
+	 */
663
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
664
+	{
665
+		if (! $version_history) {
666
+			$version_history = $this->get_activation_history();
667
+		}
668
+		if ($current_version_to_add === null) {
669
+			$current_version_to_add = $this->version();
670
+		}
671
+		$version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
672
+		// resave
673
+		return update_option($this->get_activation_history_option_name(), $version_history);
674
+	}
675
+
676
+	/**
677
+	 * Gets the name of the wp option that stores the activation history
678
+	 * of this addon
679
+	 *
680
+	 * @return string
681
+	 */
682
+	public function get_activation_history_option_name()
683
+	{
684
+		return self::ee_addon_version_history_option_prefix . $this->name();
685
+	}
686
+
687
+
688
+	/**
689
+	 * Gets the wp option which stores the activation history for this addon
690
+	 *
691
+	 * @return array
692
+	 */
693
+	public function get_activation_history()
694
+	{
695
+		return get_option($this->get_activation_history_option_name(), null);
696
+	}
697
+
698
+
699
+	/**
700
+	 * @param string $config_section
701
+	 */
702
+	public function set_config_section($config_section = '')
703
+	{
704
+		$this->_config_section = ! empty($config_section) ? $config_section : 'addons';
705
+	}
706
+
707
+	/**
708
+	 * Sets the filepath to the main plugin file
709
+	 *
710
+	 * @param string $filepath
711
+	 */
712
+	public function set_main_plugin_file($filepath)
713
+	{
714
+		$this->_main_plugin_file = $filepath;
715
+	}
716
+
717
+	/**
718
+	 * gets the filepath to teh main file
719
+	 *
720
+	 * @return string
721
+	 */
722
+	public function get_main_plugin_file()
723
+	{
724
+		return $this->_main_plugin_file;
725
+	}
726
+
727
+	/**
728
+	 * Gets the filename (no path) of the main file (the main file loaded
729
+	 * by WP)
730
+	 *
731
+	 * @return string
732
+	 */
733
+	public function get_main_plugin_file_basename()
734
+	{
735
+		return plugin_basename($this->get_main_plugin_file());
736
+	}
737
+
738
+	/**
739
+	 * Gets the folder name which contains the main plugin file
740
+	 *
741
+	 * @return string
742
+	 */
743
+	public function get_main_plugin_file_dirname()
744
+	{
745
+		return dirname($this->get_main_plugin_file());
746
+	}
747
+
748
+
749
+	/**
750
+	 * sets hooks used in the admin
751
+	 *
752
+	 * @return void
753
+	 */
754
+	public function admin_init()
755
+	{
756
+		// is admin and not in M-Mode ?
757
+		if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
758
+			add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
759
+			add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
760
+		}
761
+	}
762
+
763
+
764
+	/**
765
+	 * plugin_actions
766
+	 * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
767
+	 *
768
+	 * @param $links
769
+	 * @param $file
770
+	 * @return array
771
+	 */
772
+	public function plugin_action_links($links, $file)
773
+	{
774
+		if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
775
+			// before other links
776
+			array_unshift(
777
+				$links,
778
+				'<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
779
+				. esc_html__('Settings', 'event_espresso')
780
+				. '</a>'
781
+			);
782
+		}
783
+		return $links;
784
+	}
785
+
786
+
787
+	/**
788
+	 * after_plugin_row
789
+	 * Add additional content to the plugins page plugin row
790
+	 * Inserts another row
791
+	 *
792
+	 * @param $plugin_file
793
+	 * @param $plugin_data
794
+	 * @param $status
795
+	 * @return void
796
+	 */
797
+	public function after_plugin_row($plugin_file, $plugin_data, $status)
798
+	{
799
+		$after_plugin_row = '';
800
+		$plugins_page_row = $this->get_plugins_page_row();
801
+		if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
802
+			$class = $status ? 'active' : 'inactive';
803
+			$link_text = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
804
+			$link_url = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
805
+			$description = isset($plugins_page_row['description'])
806
+				? $plugins_page_row['description']
807
+				: '';
808
+			if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
809
+				$after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
810
+				$after_plugin_row .= '<th class="check-column" scope="row"></th>';
811
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
812
+				$after_plugin_row .= '<style>
813 813
 .ee-button,
814 814
 .ee-button:active,
815 815
 .ee-button:visited {
@@ -846,64 +846,64 @@  discard block
 block discarded – undo
846 846
 }
847 847
 .ee-button:active { top:0; }
848 848
 </style>';
849
-                $after_plugin_row .= '
849
+				$after_plugin_row .= '
850 850
 <p class="ee-addon-upsell-info-dv">
851 851
 	<a class="ee-button" href="' . $link_url . '">'
852
-                                     . $link_text
853
-                                     . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
854
-                                     . '</a>
852
+									 . $link_text
853
+									 . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
854
+									 . '</a>
855 855
 </p>';
856
-                $after_plugin_row .= '</td>';
857
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
858
-                $after_plugin_row .= $description;
859
-                $after_plugin_row .= '</td>';
860
-                $after_plugin_row .= '</tr>';
861
-            } else {
862
-                $after_plugin_row .= $description;
863
-            }
864
-        }
865
-
866
-        echo $after_plugin_row;
867
-    }
868
-
869
-
870
-    /**
871
-     * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
872
-     * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
873
-     * for back compat reasons.
874
-     *
875
-     * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
876
-     *
877
-     * It is recommended, if client code is `de-registering` an add-on, then do it on the
878
-     * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
879
-     * callback does not get run/set in that request.
880
-     *
881
-     * Also, keep in mind that if a registered add-on happens to be deactivated via
882
-     * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
883
-     * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
884
-     * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
885
-     * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
886
-     * to call `parent::deactivation`.
887
-     *
888
-     * @since 4.9.26
889
-     */
890
-    public function after_registration()
891
-    {
892
-        // cricket chirp... cricket chirp...
893
-    }
894
-
895
-    /**
896
-     * @return string
897
-     */
898
-    public function getPueSlug()
899
-    {
900
-        return $this->pue_slug;
901
-    }
902
-    /**
903
-     * @param string $pue_slug
904
-     */
905
-    public function setPueSlug($pue_slug)
906
-    {
907
-        $this->pue_slug = $pue_slug;
908
-    }
856
+				$after_plugin_row .= '</td>';
857
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
858
+				$after_plugin_row .= $description;
859
+				$after_plugin_row .= '</td>';
860
+				$after_plugin_row .= '</tr>';
861
+			} else {
862
+				$after_plugin_row .= $description;
863
+			}
864
+		}
865
+
866
+		echo $after_plugin_row;
867
+	}
868
+
869
+
870
+	/**
871
+	 * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
872
+	 * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
873
+	 * for back compat reasons.
874
+	 *
875
+	 * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
876
+	 *
877
+	 * It is recommended, if client code is `de-registering` an add-on, then do it on the
878
+	 * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
879
+	 * callback does not get run/set in that request.
880
+	 *
881
+	 * Also, keep in mind that if a registered add-on happens to be deactivated via
882
+	 * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
883
+	 * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
884
+	 * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
885
+	 * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
886
+	 * to call `parent::deactivation`.
887
+	 *
888
+	 * @since 4.9.26
889
+	 */
890
+	public function after_registration()
891
+	{
892
+		// cricket chirp... cricket chirp...
893
+	}
894
+
895
+	/**
896
+	 * @return string
897
+	 */
898
+	public function getPueSlug()
899
+	{
900
+		return $this->pue_slug;
901
+	}
902
+	/**
903
+	 * @param string $pue_slug
904
+	 */
905
+	public function setPueSlug($pue_slug)
906
+	{
907
+		$this->pue_slug = $pue_slug;
908
+	}
909 909
 }
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Personal_Data_Exporter.lib.php 2 patches
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -13,55 +13,55 @@
 block discarded – undo
13 13
 class EE_Register_Personal_Data_Exporter implements EEI_Plugin_API
14 14
 {
15 15
 
16
-    /**
17
-     * FQCN for all privacy policy generators
18
-     *
19
-     * @var array keys are plugin_ids, and values are an array of FQCNs or FQCNs
20
-     */
21
-    protected static $exporters = [];
16
+	/**
17
+	 * FQCN for all privacy policy generators
18
+	 *
19
+	 * @var array keys are plugin_ids, and values are an array of FQCNs or FQCNs
20
+	 */
21
+	protected static $exporters = [];
22 22
 
23 23
 
24
-    /**
25
-     * @param string $identifier
26
-     * @param array  $setup_args can be the fully qualified namespaces each containing only privacy policies,
27
-     *                           OR fully qualified class names of privacy policies
28
-     */
29
-    public static function register($identifier = '', array $setup_args = [])
30
-    {
31
-        self::$exporters[ $identifier ] = $setup_args;
32
-        // add to list of modules to be registered
33
-        add_filter(
34
-            'FHEE__EventEspresso_core_services_privacy_export_PersonalDataExporterManager__exporters',
35
-            ['EE_Register_Personal_Data_Exporter', 'addExporters']
36
-        );
37
-    }
24
+	/**
25
+	 * @param string $identifier
26
+	 * @param array  $setup_args can be the fully qualified namespaces each containing only privacy policies,
27
+	 *                           OR fully qualified class names of privacy policies
28
+	 */
29
+	public static function register($identifier = '', array $setup_args = [])
30
+	{
31
+		self::$exporters[ $identifier ] = $setup_args;
32
+		// add to list of modules to be registered
33
+		add_filter(
34
+			'FHEE__EventEspresso_core_services_privacy_export_PersonalDataExporterManager__exporters',
35
+			['EE_Register_Personal_Data_Exporter', 'addExporters']
36
+		);
37
+	}
38 38
 
39 39
 
40
-    /**
41
-     * @param string $identifier
42
-     */
43
-    public static function deregister($identifier = '')
44
-    {
45
-        unset(self::$exporters[ $identifier ]);
46
-    }
40
+	/**
41
+	 * @param string $identifier
42
+	 */
43
+	public static function deregister($identifier = '')
44
+	{
45
+		unset(self::$exporters[ $identifier ]);
46
+	}
47 47
 
48 48
 
49
-    /**
50
-     * Adds our personal data exporters registered by add-ons
51
-     *
52
-     * @param string[] $exporters
53
-     * @return string[]
54
-     */
55
-    public static function addExporters(array $exporters)
56
-    {
57
-        foreach (self::$exporters as $exporters_per_addon) {
58
-            $exporters = array_merge(
59
-                $exporters,
60
-                $exporters_per_addon
61
-            );
62
-        }
63
-        return $exporters;
64
-    }
49
+	/**
50
+	 * Adds our personal data exporters registered by add-ons
51
+	 *
52
+	 * @param string[] $exporters
53
+	 * @return string[]
54
+	 */
55
+	public static function addExporters(array $exporters)
56
+	{
57
+		foreach (self::$exporters as $exporters_per_addon) {
58
+			$exporters = array_merge(
59
+				$exporters,
60
+				$exporters_per_addon
61
+			);
62
+		}
63
+		return $exporters;
64
+	}
65 65
 }
66 66
 // End of file EE_Register_Personal_Data_Exporter.lib.php
67 67
 // Location: ${NAMESPACE}/EE_Register_Personal_Data_Exporter.lib.php
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
      */
29 29
     public static function register($identifier = '', array $setup_args = [])
30 30
     {
31
-        self::$exporters[ $identifier ] = $setup_args;
31
+        self::$exporters[$identifier] = $setup_args;
32 32
         // add to list of modules to be registered
33 33
         add_filter(
34 34
             'FHEE__EventEspresso_core_services_privacy_export_PersonalDataExporterManager__exporters',
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
      */
43 43
     public static function deregister($identifier = '')
44 44
     {
45
-        unset(self::$exporters[ $identifier ]);
45
+        unset(self::$exporters[$identifier]);
46 46
     }
47 47
 
48 48
 
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Personal_Data_Eraser.lib.php 2 patches
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -13,55 +13,55 @@
 block discarded – undo
13 13
 class EE_Register_Personal_Data_Eraser implements EEI_Plugin_API
14 14
 {
15 15
 
16
-    /**
17
-     * FQCN for all privacy policy generators
18
-     *
19
-     * @var array keys are plugin_ids, and values are an array of FQCNs or FQCNs
20
-     */
21
-    protected static $erasers = [];
16
+	/**
17
+	 * FQCN for all privacy policy generators
18
+	 *
19
+	 * @var array keys are plugin_ids, and values are an array of FQCNs or FQCNs
20
+	 */
21
+	protected static $erasers = [];
22 22
 
23 23
 
24
-    /**
25
-     * @param string $identifier
26
-     * @param array  $setup_args can be the fully qualified namespaces each containing only privacy policies,
27
-     *                           OR fully qualified class names of privacy policies
28
-     */
29
-    public static function register($identifier = '', array $setup_args = [])
30
-    {
31
-        self::$erasers[ $identifier ] = $setup_args;
32
-        // add to list of modules to be registered
33
-        add_filter(
34
-            'FHEE__EventEspresso_core_services_privacy_erasure_PersonalDataEraserManager__erasers',
35
-            ['EE_Register_Personal_Data_Eraser', 'addErasers']
36
-        );
37
-    }
24
+	/**
25
+	 * @param string $identifier
26
+	 * @param array  $setup_args can be the fully qualified namespaces each containing only privacy policies,
27
+	 *                           OR fully qualified class names of privacy policies
28
+	 */
29
+	public static function register($identifier = '', array $setup_args = [])
30
+	{
31
+		self::$erasers[ $identifier ] = $setup_args;
32
+		// add to list of modules to be registered
33
+		add_filter(
34
+			'FHEE__EventEspresso_core_services_privacy_erasure_PersonalDataEraserManager__erasers',
35
+			['EE_Register_Personal_Data_Eraser', 'addErasers']
36
+		);
37
+	}
38 38
 
39 39
 
40
-    /**
41
-     * @param string $identifier
42
-     */
43
-    public static function deregister($identifier = '')
44
-    {
45
-        unset(self::$erasers[ $identifier ]);
46
-    }
40
+	/**
41
+	 * @param string $identifier
42
+	 */
43
+	public static function deregister($identifier = '')
44
+	{
45
+		unset(self::$erasers[ $identifier ]);
46
+	}
47 47
 
48 48
 
49
-    /**
50
-     * Adds our personal data erasers registered by add-ons
51
-     *
52
-     * @param string[] $erasers
53
-     * @return string[]
54
-     */
55
-    public static function addErasers(array $erasers)
56
-    {
57
-        foreach (self::$erasers as $erasers_per_addon) {
58
-            $erasers = array_merge(
59
-                $erasers,
60
-                $erasers_per_addon
61
-            );
62
-        }
63
-        return $erasers;
64
-    }
49
+	/**
50
+	 * Adds our personal data erasers registered by add-ons
51
+	 *
52
+	 * @param string[] $erasers
53
+	 * @return string[]
54
+	 */
55
+	public static function addErasers(array $erasers)
56
+	{
57
+		foreach (self::$erasers as $erasers_per_addon) {
58
+			$erasers = array_merge(
59
+				$erasers,
60
+				$erasers_per_addon
61
+			);
62
+		}
63
+		return $erasers;
64
+	}
65 65
 }
66 66
 // End of file EE_Register_Personal_Data_Eraser.lib.php
67 67
 // Location: ${NAMESPACE}/EE_Register_Personal_Data_Eraser.lib.php
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
      */
29 29
     public static function register($identifier = '', array $setup_args = [])
30 30
     {
31
-        self::$erasers[ $identifier ] = $setup_args;
31
+        self::$erasers[$identifier] = $setup_args;
32 32
         // add to list of modules to be registered
33 33
         add_filter(
34 34
             'FHEE__EventEspresso_core_services_privacy_erasure_PersonalDataEraserManager__erasers',
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
      */
43 43
     public static function deregister($identifier = '')
44 44
     {
45
-        unset(self::$erasers[ $identifier ]);
45
+        unset(self::$erasers[$identifier]);
46 46
     }
47 47
 
48 48
 
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Widget.lib.php 2 patches
Indentation   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -15,97 +15,97 @@
 block discarded – undo
15 15
 class EE_Register_Widget implements EEI_Plugin_API
16 16
 {
17 17
 
18
-    /**
19
-     * Holds values for registered widgets
20
-     *
21
-     * @var array
22
-     */
23
-    protected static $_settings = [];
18
+	/**
19
+	 * Holds values for registered widgets
20
+	 *
21
+	 * @var array
22
+	 */
23
+	protected static $_settings = [];
24 24
 
25 25
 
26
-    /**
27
-     *    Method for registering new EED_Widgets
28
-     *
29
-     * @param string $identifier a unique identifier for this set of widgets
30
-     * @param array  $setup_args an array of arguments provided for registering widgets
31
-     * @type array widget_paths        an array of full server paths to folders containing any EED_Widgets, or to the
32
-     *                           EED_Widget files themselves
33
-     * @return void
34
-     * @throws EE_Error
35
-     * @since    4.3.0
36
-     */
37
-    public static function register($identifier = '', array $setup_args = [])
38
-    {
26
+	/**
27
+	 *    Method for registering new EED_Widgets
28
+	 *
29
+	 * @param string $identifier a unique identifier for this set of widgets
30
+	 * @param array  $setup_args an array of arguments provided for registering widgets
31
+	 * @type array widget_paths        an array of full server paths to folders containing any EED_Widgets, or to the
32
+	 *                           EED_Widget files themselves
33
+	 * @return void
34
+	 * @throws EE_Error
35
+	 * @since    4.3.0
36
+	 */
37
+	public static function register($identifier = '', array $setup_args = [])
38
+	{
39 39
 
40
-        // required fields MUST be present, so let's make sure they are.
41
-        if (empty($identifier) || ! is_array($setup_args) || empty($setup_args['widget_paths'])) {
42
-            throw new EE_Error(
43
-                __(
44
-                    'In order to register Widgets with EE_Register_Widget::register(), you must include a "widget_id" (a unique identifier for this set of widgets), and an array containing the following keys: "widget_paths" (an array of full server paths to folders that contain widgets, or to the widget files themselves)',
45
-                    'event_espresso'
46
-                )
47
-            );
48
-        }
40
+		// required fields MUST be present, so let's make sure they are.
41
+		if (empty($identifier) || ! is_array($setup_args) || empty($setup_args['widget_paths'])) {
42
+			throw new EE_Error(
43
+				__(
44
+					'In order to register Widgets with EE_Register_Widget::register(), you must include a "widget_id" (a unique identifier for this set of widgets), and an array containing the following keys: "widget_paths" (an array of full server paths to folders that contain widgets, or to the widget files themselves)',
45
+					'event_espresso'
46
+				)
47
+			);
48
+		}
49 49
 
50
-        // make sure we don't register twice
51
-        if (isset(self::$_settings[ $identifier ])) {
52
-            return;
53
-        }
50
+		// make sure we don't register twice
51
+		if (isset(self::$_settings[ $identifier ])) {
52
+			return;
53
+		}
54 54
 
55 55
 
56
-        // make sure this was called in the right place!
57
-        if (! did_action('AHEE__EE_System__load_espresso_addons')
58
-            || did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')
59
-        ) {
60
-            EE_Error::doing_it_wrong(
61
-                __METHOD__,
62
-                __(
63
-                    'An attempt to register widgets has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__register_shortcodes_modules_and_widgets" hook to register widgets.',
64
-                    'event_espresso'
65
-                ),
66
-                '4.3.0'
67
-            );
68
-        }
69
-        // setup $_settings array from incoming values.
70
-        self::$_settings[ $identifier ] = [
71
-            // array of full server paths to any EED_Widgets used by the widget
72
-            'widget_paths' => isset($setup_args['widget_paths']) ? (array) $setup_args['widget_paths'] : [],
73
-        ];
74
-        // add to list of widgets to be registered
75
-        add_filter(
76
-            'FHEE__EE_Config__register_widgets__widgets_to_register',
77
-            ['EE_Register_Widget', 'add_widgets']
78
-        );
79
-    }
56
+		// make sure this was called in the right place!
57
+		if (! did_action('AHEE__EE_System__load_espresso_addons')
58
+			|| did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')
59
+		) {
60
+			EE_Error::doing_it_wrong(
61
+				__METHOD__,
62
+				__(
63
+					'An attempt to register widgets has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__register_shortcodes_modules_and_widgets" hook to register widgets.',
64
+					'event_espresso'
65
+				),
66
+				'4.3.0'
67
+			);
68
+		}
69
+		// setup $_settings array from incoming values.
70
+		self::$_settings[ $identifier ] = [
71
+			// array of full server paths to any EED_Widgets used by the widget
72
+			'widget_paths' => isset($setup_args['widget_paths']) ? (array) $setup_args['widget_paths'] : [],
73
+		];
74
+		// add to list of widgets to be registered
75
+		add_filter(
76
+			'FHEE__EE_Config__register_widgets__widgets_to_register',
77
+			['EE_Register_Widget', 'add_widgets']
78
+		);
79
+	}
80 80
 
81 81
 
82
-    /**
83
-     * Filters the list of widgets to add ours.
84
-     * and they're just full filepaths to FOLDERS containing a shortcode class file. Eg.
85
-     * array('espresso_monkey'=>'/public_html/wonder-site/wp-content/plugins/ee4/widgets/espresso_monkey'...)
86
-     *
87
-     * @param array $widgets_to_register array of paths to all widgets that require registering
88
-     * @return array
89
-     */
90
-    public static function add_widgets(array $widgets_to_register = [])
91
-    {
92
-        foreach (self::$_settings as $settings) {
93
-            $widgets_to_register = array_merge($widgets_to_register, $settings['widget_paths']);
94
-        }
95
-        return $widgets_to_register;
96
-    }
82
+	/**
83
+	 * Filters the list of widgets to add ours.
84
+	 * and they're just full filepaths to FOLDERS containing a shortcode class file. Eg.
85
+	 * array('espresso_monkey'=>'/public_html/wonder-site/wp-content/plugins/ee4/widgets/espresso_monkey'...)
86
+	 *
87
+	 * @param array $widgets_to_register array of paths to all widgets that require registering
88
+	 * @return array
89
+	 */
90
+	public static function add_widgets(array $widgets_to_register = [])
91
+	{
92
+		foreach (self::$_settings as $settings) {
93
+			$widgets_to_register = array_merge($widgets_to_register, $settings['widget_paths']);
94
+		}
95
+		return $widgets_to_register;
96
+	}
97 97
 
98 98
 
99
-    /**
100
-     * This deregisters a widget that was previously registered with a specific $identifier.
101
-     *
102
-     * @param string $identifier the name for the widget that was previously registered
103
-     * @return void
104
-     * @since    4.3.0
105
-     *
106
-     */
107
-    public static function deregister($identifier = '')
108
-    {
109
-        unset(self::$_settings[ $identifier ]);
110
-    }
99
+	/**
100
+	 * This deregisters a widget that was previously registered with a specific $identifier.
101
+	 *
102
+	 * @param string $identifier the name for the widget that was previously registered
103
+	 * @return void
104
+	 * @since    4.3.0
105
+	 *
106
+	 */
107
+	public static function deregister($identifier = '')
108
+	{
109
+		unset(self::$_settings[ $identifier ]);
110
+	}
111 111
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -48,13 +48,13 @@  discard block
 block discarded – undo
48 48
         }
49 49
 
50 50
         // make sure we don't register twice
51
-        if (isset(self::$_settings[ $identifier ])) {
51
+        if (isset(self::$_settings[$identifier])) {
52 52
             return;
53 53
         }
54 54
 
55 55
 
56 56
         // make sure this was called in the right place!
57
-        if (! did_action('AHEE__EE_System__load_espresso_addons')
57
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')
58 58
             || did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')
59 59
         ) {
60 60
             EE_Error::doing_it_wrong(
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
             );
68 68
         }
69 69
         // setup $_settings array from incoming values.
70
-        self::$_settings[ $identifier ] = [
70
+        self::$_settings[$identifier] = [
71 71
             // array of full server paths to any EED_Widgets used by the widget
72 72
             'widget_paths' => isset($setup_args['widget_paths']) ? (array) $setup_args['widget_paths'] : [],
73 73
         ];
@@ -106,6 +106,6 @@  discard block
 block discarded – undo
106 106
      */
107 107
     public static function deregister($identifier = '')
108 108
     {
109
-        unset(self::$_settings[ $identifier ]);
109
+        unset(self::$_settings[$identifier]);
110 110
     }
111 111
 }
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Messages_Shortcode_Library.lib.php 2 patches
Indentation   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -12,182 +12,182 @@
 block discarded – undo
12 12
 {
13 13
 
14 14
 
15
-    /**
16
-     * holds values for registered messages shortcode libraries
17
-     *
18
-     * @var array
19
-     */
20
-    protected static $_ee_messages_shortcode_registry = [];
21
-
22
-
23
-    /**
24
-     * Helper method for registering a new shortcodes library class for the messages system.
25
-     *
26
-     * Note this is not used for adding shortcodes to existing libraries.  It's for registering anything
27
-     * related to registering a new EE_{shortcode_library_name}_Shortcodes.lib.php class.
28
-     *
29
-     * @param string $identifier                                                    What is the name of this shortcode
30
-     *                                                                              library
31
-     *                                                                              (e.g. 'question_list');
32
-     * @param array  $setup_args                                                    {
33
-     *                                                                              An array of arguments provided for
34
-     *                                                                              registering the new messages
35
-     *                                                                              shortcode library.
36
-     *
37
-     * @type array   $autoloadpaths                                                 An array of paths to add to the
38
-     *       messages autoloader for the new shortcode library class file.
39
-     * @type string  $msgr_validator_callback                                       Callback for a method that will
40
-     *       register the library with the messenger
41
-     *                                                                              _validator_config. Optional.
42
-     * @type string  $msgr_template_fields_callback                                 Callback for changing adding the
43
-     *                                                                              _template_fields property for
44
-     *                                                                              messenger. For example, the
45
-     *                                                                              shortcode library may add a new
46
-     *                                                                              field to the message templates.
47
-     *                                                                              Optional.
48
-     * @type string  $valid_shortcodes_callback                                     Callback for message types
49
-     *                                                                              _valid_shortcodes array setup.
50
-     *                                                                              Optional.
51
-     * @type array   $list_type_shortcodes                                          If there are any specific
52
-     *       shortcodes with this message shortcode library that should be considered "list type" then include them in
53
-     *       an array.  List Type shortcodes are shortcodes that have a corresponding field that indicates how they are
54
-     *       parsed. Optional.
55
-     * }
56
-     * @return void
57
-     * @throws EE_Error
58
-     * @throws EE_Error
59
-     * @since    4.3.0
60
-     *
61
-     */
62
-    public static function register($identifier = '', array $setup_args = [])
63
-    {
64
-
65
-        // required fields MUST be present, so let's make sure they are.
66
-        if (empty($identifier) || ! is_array($setup_args) || empty($setup_args['autoloadpaths'])) {
67
-            throw new EE_Error(
68
-                __(
69
-                    'In order to register a messages shortcode library with EE_Register_Messages_Shortcode_Library::register, you must include a "name" (a unique identifier for this set of message shortcodes), and an array containing the following keys: : "autoload_paths"',
70
-                    'event_espresso'
71
-                )
72
-            );
73
-        }
74
-
75
-        // make sure we don't register twice
76
-        if (isset(self::$_ee_messages_shortcode_registry[ $identifier ])) {
77
-            return;
78
-        }
79
-
80
-        // make sure this was called in the right place!
81
-        if (! did_action('EE_Brewing_Regular___messages_caf')
82
-            || did_action('AHEE__EE_System__perform_activations_upgrades_and_migrations')
83
-        ) {
84
-            EE_Error::doing_it_wrong(
85
-                __METHOD__,
86
-                sprintf(
87
-                    __(
88
-                        'Should be only called on the "EE_Brewing_Regular___messages_caf" hook (Trying to register a library named %s).',
89
-                        'event_espresso'
90
-                    ),
91
-                    $identifier
92
-                ),
93
-                '4.3.0'
94
-            );
95
-        }
96
-
97
-        self::$_ee_messages_shortcode_registry[ $identifier ] = [
98
-            'autoloadpaths'        => (array) $setup_args['autoloadpaths'],
99
-            'list_type_shortcodes' => ! empty($setup_args['list_type_shortcodes'])
100
-                ? (array) $setup_args['list_type_shortcodes'] : [],
101
-        ];
102
-
103
-        // add filters
104
-        add_filter(
105
-            'FHEE__EED_Messages___set_messages_paths___MSG_PATHS',
106
-            ['EE_Register_Messages_Shortcode_Library', 'register_msgs_autoload_paths'],
107
-            10
108
-        );
109
-
110
-        // add below filters if the required callback is provided.
111
-        if (! empty($setup_args['msgr_validator_callback'])) {
112
-            add_filter('FHEE__EE_messenger__get_validator_config', $setup_args['msgr_validator_callback'], 10, 2);
113
-        }
114
-
115
-        if (! empty($setup_args['msgr_template_fields_callback'])) {
116
-            add_filter('FHEE__EE_messenger__get_template_fields', $setup_args['msgr_template_fields_callback'], 10, 2);
117
-        }
118
-
119
-        if (! empty($setup_args['valid_shortcodes_callback'])) {
120
-            add_filter('FHEE__EE_Messages_Base__get_valid_shortcodes', $setup_args['valid_shortcodes_callback'], 10, 2);
121
-        }
122
-
123
-        if (! empty($setup_args['list_type_shortcodes'])) {
124
-            add_filter(
125
-                'FHEE__EEH_Parse_Shortcodes___parse_message_template__list_type_shortcodes',
126
-                ['EE_Register_Messages_Shortcode_Library', 'register_list_type_shortcodes'],
127
-                10
128
-            );
129
-        }
130
-    }
131
-
132
-
133
-    /**
134
-     * This deregisters any messages shortcode library previously registered with the given name.
135
-     *
136
-     * @param string $identifier name used to register the shortcode library.
137
-     * @return  void
138
-     * @since    4.3.0
139
-     */
140
-    public static function deregister($identifier = '')
141
-    {
142
-        unset(self::$_ee_messages_shortcode_registry[ $identifier ]);
143
-    }
144
-
145
-
146
-    /**
147
-     * callback for FHEE__EED_Messages___set_messages_paths___MSG_PATHS filter.
148
-     *
149
-     * @param array $paths array of paths to be checked by EE_messages autoloader.
150
-     * @return array
151
-     * @since    4.3.0
152
-     *
153
-     */
154
-    public static function register_msgs_autoload_paths(array $paths)
155
-    {
156
-
157
-        if (! empty(self::$_ee_messages_shortcode_registry)) {
158
-            foreach (self::$_ee_messages_shortcode_registry as $st_reg) {
159
-                if (empty($st_reg['autoloadpaths'])) {
160
-                    continue;
161
-                }
162
-                $paths = array_merge($paths, $st_reg['autoloadpaths']);
163
-            }
164
-        }
165
-
166
-        return $paths;
167
-    }
168
-
169
-
170
-    /**
171
-     * This is the callback for the FHEE__EEH_Parse_Shortcodes___parse_message_template__list_type_shortcodes
172
-     * filter which is used to add additional list type shortcodes.
173
-     *
174
-     * @param array $original_shortcodes
175
-     * @return  array                                   Modifications to original shortcodes.
176
-     * @since 4.3.0
177
-     *
178
-     */
179
-    public static function register_list_type_shortcodes(array $original_shortcodes)
180
-    {
181
-        if (empty(self::$_ee_messages_shortcode_registry)) {
182
-            return $original_shortcodes;
183
-        }
184
-
185
-        foreach (self::$_ee_messages_shortcode_registry as $sc_reg) {
186
-            if (! empty($sc_reg['list_type_shortcodes'])) {
187
-                $original_shortcodes = array_merge($original_shortcodes, $sc_reg['list_type_shortcodes']);
188
-            }
189
-        }
190
-
191
-        return $original_shortcodes;
192
-    }
15
+	/**
16
+	 * holds values for registered messages shortcode libraries
17
+	 *
18
+	 * @var array
19
+	 */
20
+	protected static $_ee_messages_shortcode_registry = [];
21
+
22
+
23
+	/**
24
+	 * Helper method for registering a new shortcodes library class for the messages system.
25
+	 *
26
+	 * Note this is not used for adding shortcodes to existing libraries.  It's for registering anything
27
+	 * related to registering a new EE_{shortcode_library_name}_Shortcodes.lib.php class.
28
+	 *
29
+	 * @param string $identifier                                                    What is the name of this shortcode
30
+	 *                                                                              library
31
+	 *                                                                              (e.g. 'question_list');
32
+	 * @param array  $setup_args                                                    {
33
+	 *                                                                              An array of arguments provided for
34
+	 *                                                                              registering the new messages
35
+	 *                                                                              shortcode library.
36
+	 *
37
+	 * @type array   $autoloadpaths                                                 An array of paths to add to the
38
+	 *       messages autoloader for the new shortcode library class file.
39
+	 * @type string  $msgr_validator_callback                                       Callback for a method that will
40
+	 *       register the library with the messenger
41
+	 *                                                                              _validator_config. Optional.
42
+	 * @type string  $msgr_template_fields_callback                                 Callback for changing adding the
43
+	 *                                                                              _template_fields property for
44
+	 *                                                                              messenger. For example, the
45
+	 *                                                                              shortcode library may add a new
46
+	 *                                                                              field to the message templates.
47
+	 *                                                                              Optional.
48
+	 * @type string  $valid_shortcodes_callback                                     Callback for message types
49
+	 *                                                                              _valid_shortcodes array setup.
50
+	 *                                                                              Optional.
51
+	 * @type array   $list_type_shortcodes                                          If there are any specific
52
+	 *       shortcodes with this message shortcode library that should be considered "list type" then include them in
53
+	 *       an array.  List Type shortcodes are shortcodes that have a corresponding field that indicates how they are
54
+	 *       parsed. Optional.
55
+	 * }
56
+	 * @return void
57
+	 * @throws EE_Error
58
+	 * @throws EE_Error
59
+	 * @since    4.3.0
60
+	 *
61
+	 */
62
+	public static function register($identifier = '', array $setup_args = [])
63
+	{
64
+
65
+		// required fields MUST be present, so let's make sure they are.
66
+		if (empty($identifier) || ! is_array($setup_args) || empty($setup_args['autoloadpaths'])) {
67
+			throw new EE_Error(
68
+				__(
69
+					'In order to register a messages shortcode library with EE_Register_Messages_Shortcode_Library::register, you must include a "name" (a unique identifier for this set of message shortcodes), and an array containing the following keys: : "autoload_paths"',
70
+					'event_espresso'
71
+				)
72
+			);
73
+		}
74
+
75
+		// make sure we don't register twice
76
+		if (isset(self::$_ee_messages_shortcode_registry[ $identifier ])) {
77
+			return;
78
+		}
79
+
80
+		// make sure this was called in the right place!
81
+		if (! did_action('EE_Brewing_Regular___messages_caf')
82
+			|| did_action('AHEE__EE_System__perform_activations_upgrades_and_migrations')
83
+		) {
84
+			EE_Error::doing_it_wrong(
85
+				__METHOD__,
86
+				sprintf(
87
+					__(
88
+						'Should be only called on the "EE_Brewing_Regular___messages_caf" hook (Trying to register a library named %s).',
89
+						'event_espresso'
90
+					),
91
+					$identifier
92
+				),
93
+				'4.3.0'
94
+			);
95
+		}
96
+
97
+		self::$_ee_messages_shortcode_registry[ $identifier ] = [
98
+			'autoloadpaths'        => (array) $setup_args['autoloadpaths'],
99
+			'list_type_shortcodes' => ! empty($setup_args['list_type_shortcodes'])
100
+				? (array) $setup_args['list_type_shortcodes'] : [],
101
+		];
102
+
103
+		// add filters
104
+		add_filter(
105
+			'FHEE__EED_Messages___set_messages_paths___MSG_PATHS',
106
+			['EE_Register_Messages_Shortcode_Library', 'register_msgs_autoload_paths'],
107
+			10
108
+		);
109
+
110
+		// add below filters if the required callback is provided.
111
+		if (! empty($setup_args['msgr_validator_callback'])) {
112
+			add_filter('FHEE__EE_messenger__get_validator_config', $setup_args['msgr_validator_callback'], 10, 2);
113
+		}
114
+
115
+		if (! empty($setup_args['msgr_template_fields_callback'])) {
116
+			add_filter('FHEE__EE_messenger__get_template_fields', $setup_args['msgr_template_fields_callback'], 10, 2);
117
+		}
118
+
119
+		if (! empty($setup_args['valid_shortcodes_callback'])) {
120
+			add_filter('FHEE__EE_Messages_Base__get_valid_shortcodes', $setup_args['valid_shortcodes_callback'], 10, 2);
121
+		}
122
+
123
+		if (! empty($setup_args['list_type_shortcodes'])) {
124
+			add_filter(
125
+				'FHEE__EEH_Parse_Shortcodes___parse_message_template__list_type_shortcodes',
126
+				['EE_Register_Messages_Shortcode_Library', 'register_list_type_shortcodes'],
127
+				10
128
+			);
129
+		}
130
+	}
131
+
132
+
133
+	/**
134
+	 * This deregisters any messages shortcode library previously registered with the given name.
135
+	 *
136
+	 * @param string $identifier name used to register the shortcode library.
137
+	 * @return  void
138
+	 * @since    4.3.0
139
+	 */
140
+	public static function deregister($identifier = '')
141
+	{
142
+		unset(self::$_ee_messages_shortcode_registry[ $identifier ]);
143
+	}
144
+
145
+
146
+	/**
147
+	 * callback for FHEE__EED_Messages___set_messages_paths___MSG_PATHS filter.
148
+	 *
149
+	 * @param array $paths array of paths to be checked by EE_messages autoloader.
150
+	 * @return array
151
+	 * @since    4.3.0
152
+	 *
153
+	 */
154
+	public static function register_msgs_autoload_paths(array $paths)
155
+	{
156
+
157
+		if (! empty(self::$_ee_messages_shortcode_registry)) {
158
+			foreach (self::$_ee_messages_shortcode_registry as $st_reg) {
159
+				if (empty($st_reg['autoloadpaths'])) {
160
+					continue;
161
+				}
162
+				$paths = array_merge($paths, $st_reg['autoloadpaths']);
163
+			}
164
+		}
165
+
166
+		return $paths;
167
+	}
168
+
169
+
170
+	/**
171
+	 * This is the callback for the FHEE__EEH_Parse_Shortcodes___parse_message_template__list_type_shortcodes
172
+	 * filter which is used to add additional list type shortcodes.
173
+	 *
174
+	 * @param array $original_shortcodes
175
+	 * @return  array                                   Modifications to original shortcodes.
176
+	 * @since 4.3.0
177
+	 *
178
+	 */
179
+	public static function register_list_type_shortcodes(array $original_shortcodes)
180
+	{
181
+		if (empty(self::$_ee_messages_shortcode_registry)) {
182
+			return $original_shortcodes;
183
+		}
184
+
185
+		foreach (self::$_ee_messages_shortcode_registry as $sc_reg) {
186
+			if (! empty($sc_reg['list_type_shortcodes'])) {
187
+				$original_shortcodes = array_merge($original_shortcodes, $sc_reg['list_type_shortcodes']);
188
+			}
189
+		}
190
+
191
+		return $original_shortcodes;
192
+	}
193 193
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -73,12 +73,12 @@  discard block
 block discarded – undo
73 73
         }
74 74
 
75 75
         // make sure we don't register twice
76
-        if (isset(self::$_ee_messages_shortcode_registry[ $identifier ])) {
76
+        if (isset(self::$_ee_messages_shortcode_registry[$identifier])) {
77 77
             return;
78 78
         }
79 79
 
80 80
         // make sure this was called in the right place!
81
-        if (! did_action('EE_Brewing_Regular___messages_caf')
81
+        if ( ! did_action('EE_Brewing_Regular___messages_caf')
82 82
             || did_action('AHEE__EE_System__perform_activations_upgrades_and_migrations')
83 83
         ) {
84 84
             EE_Error::doing_it_wrong(
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
             );
95 95
         }
96 96
 
97
-        self::$_ee_messages_shortcode_registry[ $identifier ] = [
97
+        self::$_ee_messages_shortcode_registry[$identifier] = [
98 98
             'autoloadpaths'        => (array) $setup_args['autoloadpaths'],
99 99
             'list_type_shortcodes' => ! empty($setup_args['list_type_shortcodes'])
100 100
                 ? (array) $setup_args['list_type_shortcodes'] : [],
@@ -108,19 +108,19 @@  discard block
 block discarded – undo
108 108
         );
109 109
 
110 110
         // add below filters if the required callback is provided.
111
-        if (! empty($setup_args['msgr_validator_callback'])) {
111
+        if ( ! empty($setup_args['msgr_validator_callback'])) {
112 112
             add_filter('FHEE__EE_messenger__get_validator_config', $setup_args['msgr_validator_callback'], 10, 2);
113 113
         }
114 114
 
115
-        if (! empty($setup_args['msgr_template_fields_callback'])) {
115
+        if ( ! empty($setup_args['msgr_template_fields_callback'])) {
116 116
             add_filter('FHEE__EE_messenger__get_template_fields', $setup_args['msgr_template_fields_callback'], 10, 2);
117 117
         }
118 118
 
119
-        if (! empty($setup_args['valid_shortcodes_callback'])) {
119
+        if ( ! empty($setup_args['valid_shortcodes_callback'])) {
120 120
             add_filter('FHEE__EE_Messages_Base__get_valid_shortcodes', $setup_args['valid_shortcodes_callback'], 10, 2);
121 121
         }
122 122
 
123
-        if (! empty($setup_args['list_type_shortcodes'])) {
123
+        if ( ! empty($setup_args['list_type_shortcodes'])) {
124 124
             add_filter(
125 125
                 'FHEE__EEH_Parse_Shortcodes___parse_message_template__list_type_shortcodes',
126 126
                 ['EE_Register_Messages_Shortcode_Library', 'register_list_type_shortcodes'],
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
      */
140 140
     public static function deregister($identifier = '')
141 141
     {
142
-        unset(self::$_ee_messages_shortcode_registry[ $identifier ]);
142
+        unset(self::$_ee_messages_shortcode_registry[$identifier]);
143 143
     }
144 144
 
145 145
 
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
     public static function register_msgs_autoload_paths(array $paths)
155 155
     {
156 156
 
157
-        if (! empty(self::$_ee_messages_shortcode_registry)) {
157
+        if ( ! empty(self::$_ee_messages_shortcode_registry)) {
158 158
             foreach (self::$_ee_messages_shortcode_registry as $st_reg) {
159 159
                 if (empty($st_reg['autoloadpaths'])) {
160 160
                     continue;
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
         }
184 184
 
185 185
         foreach (self::$_ee_messages_shortcode_registry as $sc_reg) {
186
-            if (! empty($sc_reg['list_type_shortcodes'])) {
186
+            if ( ! empty($sc_reg['list_type_shortcodes'])) {
187 187
                 $original_shortcodes = array_merge($original_shortcodes, $sc_reg['list_type_shortcodes']);
188 188
             }
189 189
         }
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Admin_Page.lib.php 2 patches
Indentation   +135 added lines, -135 removed lines patch added patch discarded remove patch
@@ -12,139 +12,139 @@
 block discarded – undo
12 12
 {
13 13
 
14 14
 
15
-    /**
16
-     * Holds registered EE_Admin_Pages
17
-     *
18
-     * @var array
19
-     */
20
-    protected static $_ee_admin_page_registry = [];
21
-
22
-
23
-    /**
24
-     * The purpose of this method is to provide an easy way for addons to register their admin pages (using the EE
25
-     * Admin Page loader system).
26
-     *
27
-     * @param string $identifier                                      This string represents the basename of the Admin
28
-     *                                                                Page init. The init file must use this basename
29
-     *                                                                in its name and class (i.e.
30
-     *                                                                {page_basename}_Admin_Page_Init.core.php).
31
-     * @param array  $setup_args                                      {              An array of configuration options
32
-     *                                                                that will be used in different circumstances
33
-     *
34
-     * @type  string $page_path                                       This is the path where the registered admin pages
35
-     *        reside ( used to setup autoloaders).
36
-     *
37
-     *    }
38
-     * @return void
39
-     * @throws EE_Error
40
-     * @since 4.3.0
41
-     *
42
-     */
43
-    public static function register($identifier = '', array $setup_args = [])
44
-    {
45
-
46
-        // check that an admin_page has not already been registered with that name
47
-        if (isset(self::$_ee_admin_page_registry[ $identifier ])) {
48
-            throw new EE_Error(
49
-                sprintf(
50
-                    __(
51
-                        'An Admin Page with the name "%s" has already been registered and each Admin Page requires a unique name.',
52
-                        'event_espresso'
53
-                    ),
54
-                    $identifier
55
-                )
56
-            );
57
-        }
58
-
59
-        // required fields MUST be present, so let's make sure they are.
60
-        if (empty($identifier) || ! is_array($setup_args) || empty($setup_args['page_path'])) {
61
-            throw new EE_Error(
62
-                __(
63
-                    'In order to register an Admin Page with EE_Register_Admin_Page::register(), you must include the "page_basename" (the class name of the page), and an array containing the following keys: "page_path" (the path where the registered admin pages reside)',
64
-                    'event_espresso'
65
-                )
66
-            );
67
-        }
68
-
69
-        // make sure we don't register twice
70
-        if (isset(self::$_ee_admin_page_registry[ $identifier ])) {
71
-            return;
72
-        }
73
-
74
-        if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_Admin__loaded')) {
75
-            EE_Error::doing_it_wrong(
76
-                __METHOD__,
77
-                sprintf(
78
-                    __(
79
-                        'An attempt was made to register "%s" as an EE Admin page has failed because it was not registered at the correct time.  Please use the "AHEE__EE_Admin__loaded" hook to register Admin pages.',
80
-                        'event_espresso'
81
-                    ),
82
-                    $identifier
83
-                ),
84
-                '4.3'
85
-            );
86
-        }
87
-
88
-        // add incoming stuff to our registry property
89
-        self::$_ee_admin_page_registry[ $identifier ] = [
90
-            'page_path' => $setup_args['page_path'],
91
-            'config'    => $setup_args,
92
-        ];
93
-
94
-        // add filters
95
-
96
-        add_filter(
97
-            'FHEE__EE_Admin_Page_Loader___get_installed_pages__installed_refs',
98
-            ['EE_Register_Admin_Page', 'set_page_basename'],
99
-            10
100
-        );
101
-        add_filter('FHEE__EEH_Autoloader__load_admin_core', ['EE_Register_Admin_Page', 'set_page_path'], 10);
102
-    }
103
-
104
-
105
-    /**
106
-     * This deregisters a EE_Admin page that is already registered.  Note, this MUST be loaded after the
107
-     * page being deregistered is loaded.
108
-     *
109
-     * @param string $identifier Use whatever string was used to register the admin page.
110
-     * @return  void
111
-     * @since    4.3.0
112
-     *
113
-     */
114
-    public static function deregister($identifier = '')
115
-    {
116
-        unset(self::$_ee_admin_page_registry[ $identifier ]);
117
-    }
118
-
119
-
120
-    /**
121
-     * set_page_basename
122
-     *
123
-     * @param $installed_refs
124
-     * @return mixed
125
-     */
126
-    public static function set_page_basename($installed_refs)
127
-    {
128
-        if (! empty(self::$_ee_admin_page_registry)) {
129
-            foreach (self::$_ee_admin_page_registry as $basename => $args) {
130
-                $installed_refs[ $basename ] = $args['page_path'];
131
-            }
132
-        }
133
-        return $installed_refs;
134
-    }
135
-
136
-
137
-    /**
138
-     * set_page_path
139
-     *
140
-     * @param $paths
141
-     * @return mixed
142
-     */
143
-    public static function set_page_path($paths)
144
-    {
145
-        foreach (self::$_ee_admin_page_registry as $basename => $args) {
146
-            $paths[ $basename ] = $args['page_path'];
147
-        }
148
-        return $paths;
149
-    }
15
+	/**
16
+	 * Holds registered EE_Admin_Pages
17
+	 *
18
+	 * @var array
19
+	 */
20
+	protected static $_ee_admin_page_registry = [];
21
+
22
+
23
+	/**
24
+	 * The purpose of this method is to provide an easy way for addons to register their admin pages (using the EE
25
+	 * Admin Page loader system).
26
+	 *
27
+	 * @param string $identifier                                      This string represents the basename of the Admin
28
+	 *                                                                Page init. The init file must use this basename
29
+	 *                                                                in its name and class (i.e.
30
+	 *                                                                {page_basename}_Admin_Page_Init.core.php).
31
+	 * @param array  $setup_args                                      {              An array of configuration options
32
+	 *                                                                that will be used in different circumstances
33
+	 *
34
+	 * @type  string $page_path                                       This is the path where the registered admin pages
35
+	 *        reside ( used to setup autoloaders).
36
+	 *
37
+	 *    }
38
+	 * @return void
39
+	 * @throws EE_Error
40
+	 * @since 4.3.0
41
+	 *
42
+	 */
43
+	public static function register($identifier = '', array $setup_args = [])
44
+	{
45
+
46
+		// check that an admin_page has not already been registered with that name
47
+		if (isset(self::$_ee_admin_page_registry[ $identifier ])) {
48
+			throw new EE_Error(
49
+				sprintf(
50
+					__(
51
+						'An Admin Page with the name "%s" has already been registered and each Admin Page requires a unique name.',
52
+						'event_espresso'
53
+					),
54
+					$identifier
55
+				)
56
+			);
57
+		}
58
+
59
+		// required fields MUST be present, so let's make sure they are.
60
+		if (empty($identifier) || ! is_array($setup_args) || empty($setup_args['page_path'])) {
61
+			throw new EE_Error(
62
+				__(
63
+					'In order to register an Admin Page with EE_Register_Admin_Page::register(), you must include the "page_basename" (the class name of the page), and an array containing the following keys: "page_path" (the path where the registered admin pages reside)',
64
+					'event_espresso'
65
+				)
66
+			);
67
+		}
68
+
69
+		// make sure we don't register twice
70
+		if (isset(self::$_ee_admin_page_registry[ $identifier ])) {
71
+			return;
72
+		}
73
+
74
+		if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_Admin__loaded')) {
75
+			EE_Error::doing_it_wrong(
76
+				__METHOD__,
77
+				sprintf(
78
+					__(
79
+						'An attempt was made to register "%s" as an EE Admin page has failed because it was not registered at the correct time.  Please use the "AHEE__EE_Admin__loaded" hook to register Admin pages.',
80
+						'event_espresso'
81
+					),
82
+					$identifier
83
+				),
84
+				'4.3'
85
+			);
86
+		}
87
+
88
+		// add incoming stuff to our registry property
89
+		self::$_ee_admin_page_registry[ $identifier ] = [
90
+			'page_path' => $setup_args['page_path'],
91
+			'config'    => $setup_args,
92
+		];
93
+
94
+		// add filters
95
+
96
+		add_filter(
97
+			'FHEE__EE_Admin_Page_Loader___get_installed_pages__installed_refs',
98
+			['EE_Register_Admin_Page', 'set_page_basename'],
99
+			10
100
+		);
101
+		add_filter('FHEE__EEH_Autoloader__load_admin_core', ['EE_Register_Admin_Page', 'set_page_path'], 10);
102
+	}
103
+
104
+
105
+	/**
106
+	 * This deregisters a EE_Admin page that is already registered.  Note, this MUST be loaded after the
107
+	 * page being deregistered is loaded.
108
+	 *
109
+	 * @param string $identifier Use whatever string was used to register the admin page.
110
+	 * @return  void
111
+	 * @since    4.3.0
112
+	 *
113
+	 */
114
+	public static function deregister($identifier = '')
115
+	{
116
+		unset(self::$_ee_admin_page_registry[ $identifier ]);
117
+	}
118
+
119
+
120
+	/**
121
+	 * set_page_basename
122
+	 *
123
+	 * @param $installed_refs
124
+	 * @return mixed
125
+	 */
126
+	public static function set_page_basename($installed_refs)
127
+	{
128
+		if (! empty(self::$_ee_admin_page_registry)) {
129
+			foreach (self::$_ee_admin_page_registry as $basename => $args) {
130
+				$installed_refs[ $basename ] = $args['page_path'];
131
+			}
132
+		}
133
+		return $installed_refs;
134
+	}
135
+
136
+
137
+	/**
138
+	 * set_page_path
139
+	 *
140
+	 * @param $paths
141
+	 * @return mixed
142
+	 */
143
+	public static function set_page_path($paths)
144
+	{
145
+		foreach (self::$_ee_admin_page_registry as $basename => $args) {
146
+			$paths[ $basename ] = $args['page_path'];
147
+		}
148
+		return $paths;
149
+	}
150 150
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
     {
45 45
 
46 46
         // check that an admin_page has not already been registered with that name
47
-        if (isset(self::$_ee_admin_page_registry[ $identifier ])) {
47
+        if (isset(self::$_ee_admin_page_registry[$identifier])) {
48 48
             throw new EE_Error(
49 49
                 sprintf(
50 50
                     __(
@@ -67,11 +67,11 @@  discard block
 block discarded – undo
67 67
         }
68 68
 
69 69
         // make sure we don't register twice
70
-        if (isset(self::$_ee_admin_page_registry[ $identifier ])) {
70
+        if (isset(self::$_ee_admin_page_registry[$identifier])) {
71 71
             return;
72 72
         }
73 73
 
74
-        if (! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_Admin__loaded')) {
74
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons') || did_action('AHEE__EE_Admin__loaded')) {
75 75
             EE_Error::doing_it_wrong(
76 76
                 __METHOD__,
77 77
                 sprintf(
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
         }
87 87
 
88 88
         // add incoming stuff to our registry property
89
-        self::$_ee_admin_page_registry[ $identifier ] = [
89
+        self::$_ee_admin_page_registry[$identifier] = [
90 90
             'page_path' => $setup_args['page_path'],
91 91
             'config'    => $setup_args,
92 92
         ];
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
      */
114 114
     public static function deregister($identifier = '')
115 115
     {
116
-        unset(self::$_ee_admin_page_registry[ $identifier ]);
116
+        unset(self::$_ee_admin_page_registry[$identifier]);
117 117
     }
118 118
 
119 119
 
@@ -125,9 +125,9 @@  discard block
 block discarded – undo
125 125
      */
126 126
     public static function set_page_basename($installed_refs)
127 127
     {
128
-        if (! empty(self::$_ee_admin_page_registry)) {
128
+        if ( ! empty(self::$_ee_admin_page_registry)) {
129 129
             foreach (self::$_ee_admin_page_registry as $basename => $args) {
130
-                $installed_refs[ $basename ] = $args['page_path'];
130
+                $installed_refs[$basename] = $args['page_path'];
131 131
             }
132 132
         }
133 133
         return $installed_refs;
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
     public static function set_page_path($paths)
144 144
     {
145 145
         foreach (self::$_ee_admin_page_registry as $basename => $args) {
146
-            $paths[ $basename ] = $args['page_path'];
146
+            $paths[$basename] = $args['page_path'];
147 147
         }
148 148
         return $paths;
149 149
     }
Please login to merge, or discard this patch.