Completed
Branch BUG/dont-reuse-DMS-scripts-dur... (666ca1)
by
unknown
06:04 queued 03:37
created
core/EE_Data_Migration_Manager.core.php 2 patches
Indentation   +1316 added lines, -1316 removed lines patch added patch discarded remove patch
@@ -32,1320 +32,1320 @@
 block discarded – undo
32 32
 class EE_Data_Migration_Manager implements ResettableInterface
33 33
 {
34 34
 
35
-    /**
36
-     *
37
-     * @var EE_Registry
38
-     */
39
-    // protected $EE;
40
-    /**
41
-     * name of the WordPress option which stores an array of data about
42
-     */
43
-    const data_migrations_option_name = 'ee_data_migration';
44
-
45
-
46
-    const data_migration_script_option_prefix         = 'ee_data_migration_script_';
47
-
48
-    const data_migration_script_mapping_option_prefix = 'ee_dms_map_';
49
-
50
-    /**
51
-     * name of the WordPress option which stores the database' current version. IE, the code may be at version 4.2.0,
52
-     * but as migrations are performed the database will progress from 3.1.35 to 4.1.0 etc.
53
-     */
54
-    const current_database_state = 'ee_data_migration_current_db_state';
55
-
56
-    /**
57
-     * Special status string returned when we're positive there are no more data migration
58
-     * scripts that can be run.
59
-     */
60
-    const status_no_more_migration_scripts = 'no_more_migration_scripts';
61
-
62
-    /**
63
-     * string indicating the migration should continue
64
-     */
65
-    const status_continue = 'status_continue';
66
-
67
-    /**
68
-     * string indicating the migration has completed and should be ended
69
-     */
70
-    const status_completed = 'status_completed';
71
-
72
-    /**
73
-     * string indicating a fatal error occurred and the data migration should be completely aborted
74
-     */
75
-    const status_fatal_error = 'status_fatal_error';
76
-
77
-    /**
78
-     * the number of 'items' (usually DB rows) to migrate on each 'step' (ajax request sent
79
-     * during migration)
80
-     */
81
-    const step_size = 50;
82
-
83
-    /**
84
-     * option name that stores the queue of ee plugins needing to have
85
-     * their data initialized (or re-initialized) once we are done migrations
86
-     */
87
-    const db_init_queue_option_name = 'ee_db_init_queue';
88
-
89
-    /**
90
-     * Array of information concerning data migrations that have run in the history
91
-     * of this EE installation. Keys should be the name of the version the script upgraded to
92
-     *
93
-     * @var EE_Data_Migration_Script_Base[]
94
-     */
95
-    private $_data_migrations_ran = null;
96
-
97
-    /**
98
-     * The last run script. It's nice to store this somewhere accessible, as its easiest
99
-     * to know which was the last run by which is the newest wp option; but in most of the code
100
-     * we just use the local $_data_migration_ran array, which organized the scripts differently
101
-     *
102
-     * @var EE_Data_Migration_Script_Base
103
-     */
104
-    private $_last_ran_script = null;
105
-
106
-    /**
107
-     * Similarly to _last_ran_script, but this is the last INCOMPLETE migration script.
108
-     *
109
-     * @var EE_Data_Migration_Script_Base
110
-     */
111
-    private $_last_ran_incomplete_script = null;
112
-
113
-    /**
114
-     * array where keys are classnames, and values are filepaths of all the known migration scripts
115
-     *
116
-     * @var array
117
-     */
118
-    private $_data_migration_class_to_filepath_map;
119
-
120
-    /**
121
-     * the following 4 properties are fully set on construction.
122
-     * Note: the first two apply to whether to continue running ALL migration scripts (ie, even though we're finished
123
-     * one, we may want to start the next one); whereas the last two indicate whether to continue running a single
124
-     * data migration script
125
-     *
126
-     * @var array
127
-     */
128
-    public $stati_that_indicate_to_continue_migrations              = [];
129
-
130
-    public $stati_that_indicate_to_stop_migrations                  = [];
131
-
132
-    public $stati_that_indicate_to_continue_single_migration_script = [];
133
-
134
-    public $stati_that_indicate_to_stop_single_migration_script     = [];
135
-
136
-    /**
137
-     * @var TableManager $table_manager
138
-     */
139
-    protected $_table_manager;
140
-
141
-    /**
142
-     * @var TableAnalysis $table_analysis
143
-     */
144
-    protected $_table_analysis;
145
-
146
-    /**
147
-     * @var array $script_migration_versions
148
-     */
149
-    protected $script_migration_versions;
150
-
151
-    /**
152
-     * @var EE_Data_Migration_Manager $_instance
153
-     * @access    private
154
-     */
155
-    private static $_instance = null;
156
-
157
-
158
-    /**
159
-     * @singleton method used to instantiate class object
160
-     * @access    public
161
-     * @return EE_Data_Migration_Manager instance
162
-     */
163
-    public static function instance()
164
-    {
165
-        // check if class object is instantiated
166
-        if (! self::$_instance instanceof EE_Data_Migration_Manager) {
167
-            self::$_instance = new self();
168
-        }
169
-        return self::$_instance;
170
-    }
171
-
172
-
173
-    /**
174
-     * resets the singleton to its brand-new state (but does NOT delete old references to the old singleton. Meaning,
175
-     * all new usages of the singleton should be made with Classname::instance()) and returns it
176
-     *
177
-     * @return EE_Data_Migration_Manager
178
-     */
179
-    public static function reset()
180
-    {
181
-        self::$_instance = null;
182
-        return self::instance();
183
-    }
184
-
185
-
186
-    /**
187
-     * @throws EE_Error
188
-     * @throws ReflectionException
189
-     */
190
-    private function __construct()
191
-    {
192
-        $this->stati_that_indicate_to_continue_migrations              = [
193
-            self::status_continue,
194
-            self::status_completed,
195
-        ];
196
-        $this->stati_that_indicate_to_stop_migrations                  = [
197
-            self::status_fatal_error,
198
-            self::status_no_more_migration_scripts,
199
-        ];
200
-        $this->stati_that_indicate_to_continue_single_migration_script = [
201
-            self::status_continue,
202
-        ];
203
-        $this->stati_that_indicate_to_stop_single_migration_script     = [
204
-            self::status_completed,
205
-            self::status_fatal_error
206
-            // note: status_no_more_migration_scripts doesn't apply
207
-        ];
208
-        // make sure we've included the base migration script, because we may need the EE_DMS_Unknown_1_0_0 class
209
-        // to be defined, because right now it doesn't get autoloaded on its own
210
-        EE_Registry::instance()->load_core('Data_Migration_Class_Base', [], true);
211
-        EE_Registry::instance()->load_core('Data_Migration_Script_Base', [], true);
212
-        EE_Registry::instance()->load_core('DMS_Unknown_1_0_0', [], true);
213
-        EE_Registry::instance()->load_core('Data_Migration_Script_Stage', [], true);
214
-        EE_Registry::instance()->load_core('Data_Migration_Script_Stage_Table', [], true);
215
-        $this->_table_manager  = EE_Registry::instance()->create('TableManager', [], true);
216
-        $this->_table_analysis = EE_Registry::instance()->create('TableAnalysis', [], true);
217
-    }
218
-
219
-
220
-    /**
221
-     * Deciphers, from an option's name, what plugin and version it relates to (see _save_migrations_ran to see what
222
-     * the option names are like, but generally they're like
223
-     * 'ee_data_migration_script_Core.4.1.0' in 4.2 or 'ee_data_migration_script_4.1.0' before that).
224
-     * The option name shouldn't ever be like 'ee_data_migration_script_Core.4.1.0.reg' because it's derived,
225
-     * indirectly, from the data migration's classname, which should always be like EE_DMS_%s_%d_%d_%d.dms.php
226
-     * (ex: EE_DMS_Core_4_1_0.dms.php)
227
-     *
228
-     * @param string $option_name (see EE_Data_Migration_Manage::_save_migrations_ran() where the option name is set)
229
-     * @return array where the first item is the plugin slug (eg 'Core','Calendar', etc.) and the 2nd is the version of
230
-     *                            that plugin (eg '4.1.0')
231
-     */
232
-    private function _get_plugin_slug_and_version_string_from_dms_option_name($option_name)
233
-    {
234
-        $plugin_slug_and_version_string = str_replace(
235
-            EE_Data_Migration_Manager::data_migration_script_option_prefix,
236
-            "",
237
-            $option_name
238
-        );
239
-        // check if $plugin_slug_and_version_string is like '4.1.0' (4.1-style) or 'Core.4.1.0' (4.2-style)
240
-        $parts = explode(".", $plugin_slug_and_version_string);
241
-
242
-        if (count($parts) == 4) {
243
-            // it's 4.2-style.eg Core.4.1.0
244
-            $plugin_slug    = $parts[0];                                     // eg Core
245
-            $version_string = $parts[1] . "." . $parts[2] . "." . $parts[3]; // eg 4.1.0
246
-        } else {
247
-            // it's 4.1-style: eg 4.1.0
248
-            $plugin_slug    = 'Core';
249
-            $version_string = $plugin_slug_and_version_string;// eg 4.1.0
250
-        }
251
-        return [$plugin_slug, $version_string];
252
-    }
253
-
254
-
255
-    /**
256
-     * Gets the DMS class from the WordPress option, otherwise throws an EE_Error if it's not
257
-     * for a known DMS class.
258
-     *
259
-     * @param string $dms_option_name
260
-     * @param string $dms_option_value (serialized)
261
-     * @return EE_Data_Migration_Script_Base
262
-     * @throws EE_Error
263
-     */
264
-    private function _get_dms_class_from_wp_option($dms_option_name, $dms_option_value)
265
-    {
266
-        $data_migration_data = maybe_unserialize($dms_option_value);
267
-        if (isset($data_migration_data['class']) && class_exists($data_migration_data['class'])) {
268
-            // During multisite migrations, it's possible we already grabbed another instance of this class
269
-            // but for a different blog. Make sure we don't reuse them (as they store info specific
270
-            // to their respective blog, like which database table to migrate).
271
-            $class = LoaderFactory::getLoader()->getNew($data_migration_data['class']);
272
-            if ($class instanceof EE_Data_Migration_Script_Base) {
273
-                $class->instantiate_from_array_of_properties($data_migration_data);
274
-                return $class;
275
-            } else {
276
-                // huh, so it's an object but not a data migration script?? that shouldn't happen
277
-                // just leave it as an array (which will probably just get ignored)
278
-                throw new EE_Error(
279
-                    sprintf(
280
-                        esc_html__(
281
-                            "Trying to retrieve DMS class from wp option. No DMS by the name '%s' exists",
282
-                            'event_espresso'
283
-                        ),
284
-                        $data_migration_data['class']
285
-                    )
286
-                );
287
-            }
288
-        } else {
289
-            // so the data doesn't specify a class. So it must either be a legacy array of info or some array (which we'll probably just ignore), or a class that no longer exists
290
-            throw new EE_Error(
291
-                sprintf(
292
-                    esc_html__("The wp option  with key '%s' does not represent a DMS", 'event_espresso'),
293
-                    $dms_option_name
294
-                )
295
-            );
296
-        }
297
-    }
298
-
299
-
300
-    /**
301
-     * Gets the array describing what data migrations have run.
302
-     * Also has a side effect of recording which was the last run,
303
-     * and which was the last run which hasn't finished yet
304
-     *
305
-     * @return array where each element should be an array of EE_Data_Migration_Script_Base
306
-     *               (but also has a few legacy arrays in there - which should probably be ignored)
307
-     * @throws EE_Error
308
-     */
309
-    public function get_data_migrations_ran()
310
-    {
311
-        if (! $this->_data_migrations_ran) {
312
-            // setup autoloaders for each of the scripts in there
313
-            $this->get_all_data_migration_scripts_available();
314
-            $data_migrations_options =
315
-                $this->get_all_migration_script_options();// get_option(EE_Data_Migration_Manager::data_migrations_option_name,get_option('espresso_data_migrations',array()));
316
-
317
-            $data_migrations_ran = [];
318
-            // convert into data migration script classes where possible
319
-            foreach ($data_migrations_options as $data_migration_option) {
320
-                list($plugin_slug, $version_string) = $this->_get_plugin_slug_and_version_string_from_dms_option_name(
321
-                    $data_migration_option['option_name']
322
-                );
323
-
324
-                try {
325
-                    $class                                                  = $this->_get_dms_class_from_wp_option(
326
-                        $data_migration_option['option_name'],
327
-                        $data_migration_option['option_value']
328
-                    );
329
-                    $data_migrations_ran[ $plugin_slug ][ $version_string ] = $class;
330
-                    // ok so far THIS is the 'last-run-script'... unless we find another on next iteration
331
-                    $this->_last_ran_script = $class;
332
-                    if (! $class->is_completed()) {
333
-                        // sometimes we also like to know which was the last incomplete script (or if there are any at all)
334
-                        $this->_last_ran_incomplete_script = $class;
335
-                    }
336
-                } catch (EE_Error $e) {
337
-                    // ok so it's not a DMS. We'll just keep it, although other code will need to expect non-DMSs
338
-                    $data_migrations_ran[ $plugin_slug ][ $version_string ] = maybe_unserialize(
339
-                        $data_migration_option['option_value']
340
-                    );
341
-                }
342
-            }
343
-            // so here the array of $data_migrations_ran is actually a mix of classes and a few legacy arrays
344
-            $this->_data_migrations_ran = $data_migrations_ran;
345
-            if (! $this->_data_migrations_ran || ! is_array($this->_data_migrations_ran)) {
346
-                $this->_data_migrations_ran = [];
347
-            }
348
-        }
349
-        return $this->_data_migrations_ran;
350
-    }
351
-
352
-
353
-    /**
354
-     *
355
-     * @param string $script_name eg 'DMS_Core_4_1_0'
356
-     * @param string $old_table   eg 'wp_events_detail'
357
-     * @param string $old_pk      eg 'wp_esp_posts'
358
-     * @param        $new_table
359
-     * @return mixed string or int
360
-     * @throws EE_Error
361
-     * @throws ReflectionException
362
-     */
363
-    public function get_mapping_new_pk($script_name, $old_table, $old_pk, $new_table)
364
-    {
365
-        $script  = EE_Registry::instance()->load_dms($script_name);
366
-        return $script->get_mapping_new_pk($old_table, $old_pk, $new_table);
367
-    }
368
-
369
-
370
-    /**
371
-     * Gets all the options containing migration scripts that have been run. Ordering is important: it's assumed that
372
-     * the last option returned in this array is the most-recently run DMS option
373
-     *
374
-     * @return array
375
-     */
376
-    public function get_all_migration_script_options()
377
-    {
378
-        global $wpdb;
379
-        return $wpdb->get_results(
380
-            "SELECT * FROM {$wpdb->options} WHERE option_name like '"
381
-            . EE_Data_Migration_Manager::data_migration_script_option_prefix
382
-            . "%' ORDER BY option_id ASC",
383
-            ARRAY_A
384
-        );
385
-    }
386
-
387
-
388
-    /**
389
-     * Gets the array of folders which contain data migration scripts. Also adds them to be auto-loaded
390
-     *
391
-     * @return array where each value is the full folder path of a folder containing data migration scripts, WITH
392
-     *               slashes at the end of the folder name.
393
-     */
394
-    public function get_data_migration_script_folders()
395
-    {
396
-        return apply_filters(
397
-            'FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',
398
-            ['Core' => EE_CORE . 'data_migration_scripts']
399
-        );
400
-    }
401
-
402
-
403
-    /**
404
-     * Gets the version the migration script upgrades to
405
-     *
406
-     * @param string $migration_script_name eg 'EE_DMS_Core_4_1_0'
407
-     * @return array {
408
-     *      @type string  $slug     like 'Core','Calendar',etc
409
-     *      @type string  $version  like 4.3.0
410
-     * }
411
-     * @throws EE_Error
412
-     */
413
-    public function script_migrates_to_version($migration_script_name, $eeAddonClass = '')
414
-    {
415
-        if (isset($this->script_migration_versions[ $migration_script_name ])) {
416
-            return $this->script_migration_versions[ $migration_script_name ];
417
-        }
418
-        $dms_info                                                  = $this->parse_dms_classname($migration_script_name);
419
-        $this->script_migration_versions[ $migration_script_name ] = [
420
-            'slug'    => $eeAddonClass !== '' ? $eeAddonClass : $dms_info['slug'],
421
-            'version' => $dms_info['major_version']
422
-                         . "."
423
-                         . $dms_info['minor_version']
424
-                         . "."
425
-                         . $dms_info['micro_version'],
426
-        ];
427
-        return $this->script_migration_versions[ $migration_script_name ];
428
-    }
429
-
430
-
431
-    /**
432
-     * Gets the juicy details out of a dms filename like 'EE_DMS_Core_4_1_0'
433
-     *
434
-     * @param string $classname
435
-     * @return array with keys 'slug','major_version','minor_version', and 'micro_version' (the last 3 are integers)
436
-     * @throws EE_Error
437
-     */
438
-    public function parse_dms_classname($classname)
439
-    {
440
-        $matches = [];
441
-        preg_match('~EE_DMS_(.*)_([0-9]*)_([0-9]*)_([0-9]*)~', $classname, $matches);
442
-        if (! $matches || ! (isset($matches[1]) && isset($matches[2]) && isset($matches[3]))) {
443
-            throw new EE_Error(
444
-                sprintf(
445
-                    esc_html__(
446
-                        "%s is not a valid Data Migration Script. The classname should be like EE_DMS_w_x_y_z, where w is either 'Core' or the slug of an addon and x, y and z are numbers, ",
447
-                        "event_espresso"
448
-                    ),
449
-                    $classname
450
-                )
451
-            );
452
-        }
453
-        return [
454
-            'slug'          => $matches[1],
455
-            'major_version' => intval($matches[2]),
456
-            'minor_version' => intval($matches[3]),
457
-            'micro_version' => intval($matches[4]),
458
-        ];
459
-    }
460
-
461
-
462
-    /**
463
-     * Ensures that the option indicating the current DB version is set. This should only be
464
-     * a concern when activating EE for the first time, THEORETICALLY.
465
-     * If we detect that we're activating EE4 over top of EE3.1, then we set the current db state to 3.1.x, otherwise
466
-     * to 4.1.x.
467
-     *
468
-     * @return string of current db state
469
-     */
470
-    public function ensure_current_database_state_is_set()
471
-    {
472
-        $espresso_db_core_updates = get_option('espresso_db_update', []);
473
-        $db_state                 = get_option(EE_Data_Migration_Manager::current_database_state);
474
-        if (! $db_state) {
475
-            // mark the DB as being in the state as the last version in there.
476
-            // this is done to trigger maintenance mode and do data migration scripts
477
-            // if the admin installed this version of EE over 3.1.x or 4.0.x
478
-            // otherwise, the normal maintenance mode code is fine
479
-            $previous_versions_installed = array_keys($espresso_db_core_updates);
480
-            $previous_version_installed  = end($previous_versions_installed);
481
-            if (version_compare('4.1.0', $previous_version_installed)) {
482
-                // last installed version was less than 4.1, so we want the data migrations to happen.
483
-                // SO, we're going to say the DB is at that state
484
-                $db_state = ['Core' => $previous_version_installed];
485
-            } else {
486
-                $db_state = ['Core' => EVENT_ESPRESSO_VERSION];
487
-            }
488
-            update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
489
-        }
490
-        // in 4.1, $db_state would have only been a simple string like '4.1.0',
491
-        // but in 4.2+ it should be an array with at least key 'Core' and the value of that plugin's
492
-        // db, and possibly other keys for other addons like 'Calendar','Permissions',etc
493
-        if (! is_array($db_state)) {
494
-            $db_state = ['Core' => $db_state];
495
-            update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
496
-        }
497
-        return $db_state;
498
-    }
499
-
500
-
501
-    /**
502
-     * Checks if there are any data migration scripts that ought to be run.
503
-     * If found, returns the instantiated classes.
504
-     * If none are found (ie, they've all already been run, or they don't apply), returns an empty array
505
-     *
506
-     * @return EE_Data_Migration_Script_Base[]
507
-     * @throws EE_Error
508
-     * @throws EE_Error
509
-     */
510
-    public function check_for_applicable_data_migration_scripts()
511
-    {
512
-        // get the option describing what options have already run
513
-        $scripts_ran = $this->get_data_migrations_ran();
514
-        // $scripts_ran = array('4.1.0.core'=>array('monkey'=>null));
515
-        $script_class_and_filepaths_available = $this->get_all_data_migration_scripts_available();
516
-
517
-
518
-        $current_database_state = $this->ensure_current_database_state_is_set();
519
-        // determine which have already been run
520
-        $script_classes_that_should_run_per_iteration = [];
521
-        $iteration                                    = 0;
522
-        $next_database_state_to_consider              = $current_database_state;
523
-        $theoretical_database_state = null;
524
-        do {
525
-            // the next state after the currently-considered one
526
-            // will start off looking the same as the current, but we may make additions...
527
-            $theoretical_database_state = $next_database_state_to_consider;
528
-            // the next db state to consider is
529
-            // "what would the DB be like had we run all the scripts we found that applied last time?"
530
-            foreach ($script_class_and_filepaths_available as $classname => $filepath) {
531
-                $migrates_to_version         = $this->script_migrates_to_version($classname);
532
-                $script_converts_plugin_slug = $migrates_to_version['slug'];
533
-                $script_converts_to_version  = $migrates_to_version['version'];
534
-                // check if this version script is DONE or not; or if it's never been run
535
-                if (
536
-                    ! $scripts_ran
537
-                    || ! isset($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ])
538
-                ) {
539
-                    // we haven't run this conversion script before
540
-                    // now check if it applies...
541
-                    // note that we've added an autoloader for it on get_all_data_migration_scripts_available
542
-                    // Also, make sure we get a new one. It's possible this is being ran during a multisite migration,
543
-                    // in which case we don't want to reuse a DMS script from a different blog!
544
-                    $script = LoaderFactory::getLoader()->getNew($classname);
545
-                    /* @var $script EE_Data_Migration_Script_Base */
546
-                    $can_migrate = $script->can_migrate_from_version($theoretical_database_state);
547
-                    if ($can_migrate) {
548
-                        $script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
549
-                        $migrates_to_version                                                                 =
550
-                            $script->migrates_to_version();
551
-                        $next_database_state_to_consider[ $migrates_to_version['slug'] ]                     =
552
-                            $migrates_to_version['version'];
553
-                        unset($script_class_and_filepaths_available[ $classname ]);
554
-                    }
555
-                } elseif (
556
-                    $scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ]
557
-                          instanceof
558
-                          EE_Data_Migration_Script_Base
559
-                ) {
560
-                    // this script has been run, or at least started
561
-                    $script = $scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ];
562
-                    if ($script->get_status() !== self::status_completed) {
563
-                        // this script is already underway... keep going with it
564
-                        $script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
565
-                        $migrates_to_version                                                                 =
566
-                            $script->migrates_to_version();
567
-                        $next_database_state_to_consider[ $migrates_to_version['slug'] ]                     =
568
-                            $migrates_to_version['version'];
569
-                        unset($script_class_and_filepaths_available[ $classname ]);
570
-                    }
571
-                    // else it must have a status that indicates it has finished,
572
-                    // so we don't want to try and run it again
573
-                }
574
-                // else it exists, but it's not  a proper data migration script maybe the script got renamed?
575
-                // or was simply removed from EE? either way, it's certainly not runnable!
576
-            }
577
-            $iteration++;
578
-        } while ($next_database_state_to_consider !== $theoretical_database_state && $iteration < 6);
579
-        // ok we have all the scripts that should run, now let's make them into flat array
580
-        $scripts_that_should_run = [];
581
-        foreach ($script_classes_that_should_run_per_iteration as $scripts_at_priority) {
582
-            ksort($scripts_at_priority);
583
-            foreach ($scripts_at_priority as $scripts) {
584
-                foreach ($scripts as $script) {
585
-                    $scripts_that_should_run[ get_class($script) ] = $script;
586
-                }
587
-            }
588
-        }
589
-
590
-        do_action(
591
-            'AHEE__EE_Data_Migration_Manager__check_for_applicable_data_migration_scripts__scripts_that_should_run',
592
-            $scripts_that_should_run
593
-        );
594
-        return $scripts_that_should_run;
595
-    }
596
-
597
-
598
-    /**
599
-     * Gets the script which is currently being run, if there is one. If $include_completed_scripts is set to TRUE
600
-     * it will return the last run script even if it's complete.
601
-     * This means: if you want to find the currently-executing script, leave it as FALSE.
602
-     * If you really just want to find the script which ran most recently, regardless of status, leave it as TRUE.
603
-     *
604
-     * @param bool $include_completed_scripts
605
-     * @return EE_Data_Migration_Script_Base
606
-     * @throws EE_Error
607
-     */
608
-    public function get_last_ran_script($include_completed_scripts = false)
609
-    {
610
-        // make sure we've set up the class properties _last_ran_script and _last_ran_incomplete_script
611
-        if (! $this->_data_migrations_ran) {
612
-            $this->get_data_migrations_ran();
613
-        }
614
-        if ($include_completed_scripts) {
615
-            return $this->_last_ran_script;
616
-        } else {
617
-            return $this->_last_ran_incomplete_script;
618
-        }
619
-    }
620
-
621
-
622
-    /**
623
-     * Runs the data migration scripts (well, each request to this method calls one of the
624
-     * data migration scripts' migration_step() functions).
625
-     *
626
-     * @param int   $step_size
627
-     * @return array {
628
-     *                                  // where the first item is one EE_Data_Migration_Script_Base's stati,
629
-     *                                  //and the second item is a string describing what was done
630
-     * @type int    $records_to_migrate from the current migration script
631
-     * @type int    $records_migrated
632
-     * @type string $status             one of EE_Data_Migration_Manager::status_*
633
-     * @type string $script             verbose name of the current DMS
634
-     * @type string $message            string describing what was done during this step
635
-     *                                  }
636
-     * @throws EE_Error
637
-     */
638
-    public function migration_step($step_size = 0)
639
-    {
640
-
641
-        // bandaid fix for issue https://events.codebasehq.com/projects/event-espresso/tickets/7535
642
-        if (class_exists('EE_CPT_Strategy')) {
643
-            remove_action('pre_get_posts', [EE_CPT_Strategy::instance(), 'pre_get_posts'], 5);
644
-        }
645
-
646
-        try {
647
-            $currently_executing_script = $this->get_last_ran_script();
648
-            if (! $currently_executing_script) {
649
-                // Find the next script that needs to execute
650
-                $scripts = $this->check_for_applicable_data_migration_scripts();
651
-                if (! $scripts) {
652
-                    // huh, no more scripts to run... apparently we're done!
653
-                    // but don't forget to make sure initial data is there
654
-                    // we should be good to allow them to exit maintenance mode now
655
-                    EE_Maintenance_Mode::instance()->set_maintenance_level(
656
-                        EE_Maintenance_Mode::level_0_not_in_maintenance
657
-                    );
658
-                    // saving migrations run should actually be unnecessary,
659
-                    // but leaving in place just in case... remember this migration was finished
660
-                    // (even if we time out while initializing db for core and plugins)
661
-                    $this->_save_migrations_ran();
662
-                    // make sure DB was updated AFTER we've recorded the migration was done
663
-                    $this->initialize_db_for_enqueued_ee_plugins();
664
-                    return [
665
-                        'records_to_migrate' => 1,
666
-                        'records_migrated'   => 1,
667
-                        'status'             => self::status_no_more_migration_scripts,
668
-                        'script'             => esc_html__("Data Migration Completed Successfully", "event_espresso"),
669
-                        'message'            => esc_html__("All done!", "event_espresso"),
670
-                    ];
671
-                }
672
-                $currently_executing_script = array_shift($scripts);
673
-                // and add to the array/wp option showing the scripts run
674
-
675
-                $migrates_to                                            =
676
-                    $this->script_migrates_to_version(get_class($currently_executing_script));
677
-                $plugin_slug                                            = $migrates_to['slug'];
678
-                $version                                                = $migrates_to['version'];
679
-                $this->_data_migrations_ran[ $plugin_slug ][ $version ] = $currently_executing_script;
680
-            }
681
-            $current_script_name = get_class($currently_executing_script);
682
-        } catch (Exception $e) {
683
-            // an exception occurred while trying to get migration scripts
684
-
685
-            $message = sprintf(
686
-                esc_html__("Error Message: %sStack Trace:%s", "event_espresso"),
687
-                $e->getMessage() . '<br>',
688
-                $e->getTraceAsString()
689
-            );
690
-            // record it on the array of data migration scripts run. This will be overwritten next time we try and try to run data migrations
691
-            // but that's ok-- it's just an FYI to support that we couldn't even run any data migrations
692
-            $this->add_error_to_migrations_ran(
693
-                sprintf(esc_html__("Could not run data migrations because: %s", "event_espresso"), $message)
694
-            );
695
-            return [
696
-                'records_to_migrate' => 1,
697
-                'records_migrated'   => 0,
698
-                'status'             => self::status_fatal_error,
699
-                'script'             => esc_html__("Error loading data migration scripts", "event_espresso"),
700
-                'message'            => $message,
701
-            ];
702
-        }
703
-        // can we wrap it up and verify default data?
704
-        $init_dbs = false;
705
-        // ok so we definitely have a data migration script
706
-        try {
707
-            // how big of a bite do we want to take? Allow users to easily override via their wp-config
708
-            if (absint($step_size) < 1) {
709
-                $step_size = defined('EE_MIGRATION_STEP_SIZE') && absint(EE_MIGRATION_STEP_SIZE)
710
-                    ? EE_MIGRATION_STEP_SIZE
711
-                    : EE_Data_Migration_Manager::step_size;
712
-            }
713
-            // do what we came to do!
714
-            $currently_executing_script->migration_step($step_size);
715
-            switch ($currently_executing_script->get_status()) {
716
-                case EE_Data_Migration_Manager::status_continue:
717
-                    $response_array = [
718
-                        'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
719
-                        'records_migrated'   => $currently_executing_script->count_records_migrated(),
720
-                        'status'             => EE_Data_Migration_Manager::status_continue,
721
-                        'message'            => $currently_executing_script->get_feedback_message(),
722
-                        'script'             => $currently_executing_script->pretty_name(),
723
-                    ];
724
-                    break;
725
-                case EE_Data_Migration_Manager::status_completed:
726
-                    // ok so THAT script has completed
727
-                    $this->update_current_database_state_to($this->script_migrates_to_version($current_script_name));
728
-                    $response_array = [
729
-                        'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
730
-                        'records_migrated'   => $currently_executing_script->count_records_migrated(),
731
-                        'status'             => EE_Data_Migration_Manager::status_completed,
732
-                        'message'            => $currently_executing_script->get_feedback_message(),
733
-                        'script'             => sprintf(
734
-                            esc_html__("%s Completed", 'event_espresso'),
735
-                            $currently_executing_script->pretty_name()
736
-                        ),
737
-                    ];
738
-                    // check if there are any more after this one.
739
-                    $scripts_remaining = $this->check_for_applicable_data_migration_scripts();
740
-                    if (! $scripts_remaining) {
741
-                        // we should be good to allow them to exit maintenance mode now
742
-                        EE_Maintenance_Mode::instance()->set_maintenance_level(
743
-                            EE_Maintenance_Mode::level_0_not_in_maintenance
744
-                        );
745
-                        // huh, no more scripts to run... apparently we're done!
746
-                        // but don't forget to make sure initial data is there
747
-                        $init_dbs                 = true;
748
-                        $response_array['status'] = self::status_no_more_migration_scripts;
749
-                    }
750
-                    break;
751
-                default:
752
-                    $response_array = [
753
-                        'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
754
-                        'records_migrated'   => $currently_executing_script->count_records_migrated(),
755
-                        'status'             => $currently_executing_script->get_status(),
756
-                        'message'            => sprintf(
757
-                            esc_html__("Minor errors occurred during %s: %s", "event_espresso"),
758
-                            $currently_executing_script->pretty_name(),
759
-                            implode(", ", $currently_executing_script->get_errors())
760
-                        ),
761
-                        'script'             => $currently_executing_script->pretty_name(),
762
-                    ];
763
-                    break;
764
-            }
765
-        } catch (Exception $e) {
766
-            // ok so some exception was thrown which killed the data migration script
767
-            // double-check we have a real script
768
-            if ($currently_executing_script instanceof EE_Data_Migration_Script_Base) {
769
-                $script_name = $currently_executing_script->pretty_name();
770
-                $currently_executing_script->set_broken();
771
-                $currently_executing_script->add_error($e->getMessage());
772
-            } else {
773
-                $script_name = esc_html__("Error getting Migration Script", "event_espresso");
774
-            }
775
-            $response_array = [
776
-                'records_to_migrate' => 1,
777
-                'records_migrated'   => 0,
778
-                'status'             => self::status_fatal_error,
779
-                'message'            => sprintf(
780
-                    esc_html__("A fatal error occurred during the migration: %s", "event_espresso"),
781
-                    $e->getMessage()
782
-                ),
783
-                'script'             => $script_name,
784
-            ];
785
-        }
786
-        $successful_save = $this->_save_migrations_ran();
787
-        if ($successful_save !== true) {
788
-            // ok so the current wp option didn't save. that's tricky, because we'd like to update it
789
-            // and mark it as having a fatal error, but remember- WE CAN'T SAVE THIS WP OPTION!
790
-            // however, if we throw an exception, and return that, then the next request
791
-            // won't have as much info in it, and it may be able to save
792
-            throw new EE_Error(
793
-                sprintf(
794
-                    esc_html__(
795
-                        "The error '%s' occurred updating the status of the migration. This is a FATAL ERROR, but the error is preventing the system from remembering that. Please contact event espresso support.",
796
-                        "event_espresso"
797
-                    ),
798
-                    $successful_save
799
-                )
800
-            );
801
-        }
802
-        // if we're all done, initialize EE plugins' default data etc.
803
-        if ($init_dbs) {
804
-            $this->initialize_db_for_enqueued_ee_plugins();
805
-        }
806
-        return $response_array;
807
-    }
808
-
809
-
810
-    /**
811
-     * Echo out JSON response to migration script AJAX requests. Takes precautions
812
-     * to buffer output so that we don't throw junk into our json.
813
-     *
814
-     * @return array with keys:
815
-     * 'records_to_migrate' which counts ALL the records for the current migration, and should remain constant. (ie,
816
-     * it's NOT the count of hwo many remain)
817
-     * 'records_migrated' which also counts ALL the records which have been migrated (ie, percent_complete =
818
-     * records_migrated/records_to_migrate)
819
-     * 'status'=>a string, one of EE_Data_migration_Manager::status_*
820
-     * 'message'=>a string, containing any message you want to show to the user. We may decide to split this up into
821
-     * errors, notifications, and successes
822
-     * 'script'=>a pretty name of the script currently running
823
-     */
824
-    public function response_to_migration_ajax_request()
825
-    {
826
-        ob_start();
827
-        try {
828
-            $response = $this->migration_step();
829
-        } catch (Exception $e) {
830
-            $response = [
831
-                'records_to_migrate' => 0,
832
-                'records_migrated'   => 0,
833
-                'status'             => EE_Data_Migration_Manager::status_fatal_error,
834
-                'message'            => sprintf(
835
-                    esc_html__("Unknown fatal error occurred: %s", "event_espresso"),
836
-                    $e->getMessage()
837
-                ),
838
-                'script'             => 'Unknown',
839
-            ];
840
-            $this->add_error_to_migrations_ran($e->getMessage() . "; Stack trace:" . $e->getTraceAsString());
841
-        }
842
-        $warnings_etc = @ob_get_contents();
843
-        ob_end_clean();
844
-        $response['message'] .= $warnings_etc;
845
-        return $response;
846
-    }
847
-
848
-
849
-    /**
850
-     * Updates the WordPress option that keeps track of which EE version the database
851
-     * is at (ie, the code may be at 4.1.0, but the database is still at 3.1.35)
852
-     *
853
-     * @param array $slug_and_version {
854
-     * @type string $slug             like 'Core' or 'Calendar',
855
-     * @type string $version          like '4.1.0'
856
-     *                                }
857
-     * @return void
858
-     */
859
-    public function update_current_database_state_to($slug_and_version = null)
860
-    {
861
-        if (! $slug_and_version) {
862
-            // no version was provided, assume it should be at the current code version
863
-            $slug_and_version = ['slug' => 'Core', 'version' => espresso_version()];
864
-        }
865
-        $current_database_state                              = get_option(self::current_database_state);
866
-        $current_database_state[ $slug_and_version['slug'] ] = $slug_and_version['version'];
867
-        update_option(self::current_database_state, $current_database_state);
868
-    }
869
-
870
-
871
-    /**
872
-     * Determines if the database is currently at a state matching what's indicated in $slug and $version.
873
-     *
874
-     * @param array $slug_and_version {
875
-     * @type string $slug             like 'Core' or 'Calendar',
876
-     * @type string $version          like '4.1.0'
877
-     *                                }
878
-     * @return boolean
879
-     */
880
-    public function database_needs_updating_to($slug_and_version)
881
-    {
882
-
883
-        $slug                   = $slug_and_version['slug'];
884
-        $version                = $slug_and_version['version'];
885
-        $current_database_state = get_option(self::current_database_state);
886
-        if (! isset($current_database_state[ $slug ])) {
887
-            return true;
888
-        } else {
889
-            // just compare the first 3 parts of version string, eg "4.7.1", not "4.7.1.dev.032" because DBs shouldn't change on nano version changes
890
-            $version_parts_current_db_state     = array_slice(explode('.', $current_database_state[ $slug ]), 0, 3);
891
-            $version_parts_of_provided_db_state = array_slice(explode('.', $version), 0, 3);
892
-            $needs_updating                     = false;
893
-            foreach ($version_parts_current_db_state as $offset => $version_part_in_current_db_state) {
894
-                if ($version_part_in_current_db_state < $version_parts_of_provided_db_state[ $offset ]) {
895
-                    $needs_updating = true;
896
-                    break;
897
-                }
898
-            }
899
-            return $needs_updating;
900
-        }
901
-    }
902
-
903
-
904
-    /**
905
-     * Gets all the data migration scripts available in the core folder and folders
906
-     * in addons. Has the side effect of adding them for autoloading
907
-     *
908
-     * @return array keys are expected classnames, values are their filepaths
909
-     * @throws InvalidInterfaceException
910
-     * @throws InvalidDataTypeException
911
-     * @throws EE_Error
912
-     * @throws InvalidArgumentException
913
-     */
914
-    public function get_all_data_migration_scripts_available()
915
-    {
916
-        if (! $this->_data_migration_class_to_filepath_map) {
917
-            $this->_data_migration_class_to_filepath_map = [];
918
-            foreach ($this->get_data_migration_script_folders() as $eeAddonClass => $folder_path) {
919
-                // strip any placeholders added to classname to make it a unique array key
920
-                $eeAddonClass = trim($eeAddonClass, '*');
921
-                $eeAddonClass = $eeAddonClass === 'Core' || class_exists($eeAddonClass)
922
-                    ? $eeAddonClass
923
-                    : '';
924
-                $folder_path  = EEH_File::end_with_directory_separator($folder_path);
925
-                $files        = glob($folder_path . '*.dms.php');
926
-                if (empty($files)) {
927
-                    continue;
928
-                }
929
-                foreach ($files as $file) {
930
-                    $pos_of_last_slash = strrpos($file, '/');
931
-                    $classname         = str_replace('.dms.php', '', substr($file, $pos_of_last_slash + 1));
932
-                    $migrates_to       = $this->script_migrates_to_version($classname, $eeAddonClass);
933
-                    $slug              = $migrates_to['slug'];
934
-                    // check that the slug as contained in the DMS is associated with
935
-                    // the slug of an addon or core
936
-                    if ($slug !== 'Core' && EE_Registry::instance()->get_addon_by_name($slug) === null) {
937
-                        EE_Error::doing_it_wrong(
938
-                            __FUNCTION__,
939
-                            sprintf(
940
-                                esc_html__(
941
-                                    'The data migration script "%s" migrates the "%s" data, but there is no EE addon with that name. There is only: %s. ',
942
-                                    'event_espresso'
943
-                                ),
944
-                                $classname,
945
-                                $slug,
946
-                                implode(', ', array_keys(EE_Registry::instance()->get_addons_by_name()))
947
-                            ),
948
-                            '4.3.0.alpha.019'
949
-                        );
950
-                    }
951
-                    $this->_data_migration_class_to_filepath_map[ $classname ] = $file;
952
-                }
953
-            }
954
-            EEH_Autoloader::register_autoloader($this->_data_migration_class_to_filepath_map);
955
-        }
956
-        return $this->_data_migration_class_to_filepath_map;
957
-    }
958
-
959
-
960
-    /**
961
-     * Once we have an addon that works with EE4.1, we will actually want to fetch the PUE slugs
962
-     * from each addon, and check if they need updating,
963
-     *
964
-     * @return boolean
965
-     */
966
-    public function addons_need_updating()
967
-    {
968
-        return false;
969
-    }
970
-
971
-
972
-    /**
973
-     * Adds this error string to the data_migrations_ran array, but we don't necessarily know
974
-     * where to put it, so we just throw it in there... better than nothing...
975
-     *
976
-     * @param string $error_message
977
-     */
978
-    public function add_error_to_migrations_ran($error_message)
979
-    {
980
-        // get last-run migration script
981
-        global $wpdb;
982
-        $last_migration_script_option = $wpdb->get_row(
983
-            "SELECT * FROM $wpdb->options WHERE option_name like '"
984
-            . EE_Data_Migration_Manager::data_migration_script_option_prefix
985
-            . "%' ORDER BY option_id DESC LIMIT 1",
986
-            ARRAY_A
987
-        );
988
-
989
-        $last_ran_migration_script_properties = isset($last_migration_script_option['option_value'])
990
-            ? maybe_unserialize($last_migration_script_option['option_value']) : null;
991
-        // now, tread lightly because we're here because a FATAL non-catchable error
992
-        // was thrown last time when we were trying to run a data migration script
993
-        // so the fatal error could have happened while getting the migration script
994
-        // or doing running it...
995
-        $versions_migrated_to = isset($last_migration_script_option['option_name']) ? str_replace(
996
-            EE_Data_Migration_Manager::data_migration_script_option_prefix,
997
-            "",
998
-            $last_migration_script_option['option_name']
999
-        ) : null;
1000
-
1001
-        // check if it THINKS it's a data migration script and especially if it's one that HASN'T finished yet
1002
-        // because if it has finished, then it obviously couldn't be the cause of this error, right? (because it's all done)
1003
-        if (
1004
-            isset($last_ran_migration_script_properties['class'])
1005
-            && isset($last_ran_migration_script_properties['_status'])
1006
-            && $last_ran_migration_script_properties['_status'] != self::status_completed
1007
-        ) {
1008
-            // ok then just add this error to its list of errors
1009
-            $last_ran_migration_script_properties['_errors'][] = $error_message;
1010
-            $last_ran_migration_script_properties['_status']   = self::status_fatal_error;
1011
-        } else {
1012
-            // so we don't even know which script was last running
1013
-            // use the data migration error stub, which is designed specifically for this type of thing
1014
-            $general_migration_error = new EE_DMS_Unknown_1_0_0();
1015
-            $general_migration_error->add_error($error_message);
1016
-            $general_migration_error->set_broken();
1017
-            $last_ran_migration_script_properties = $general_migration_error->properties_as_array();
1018
-            $versions_migrated_to                 = 'Unknown.1.0.0';
1019
-            // now just to make sure appears as last (in case the were previously a fatal error like this)
1020
-            // delete the old one
1021
-            delete_option(self::data_migration_script_option_prefix . $versions_migrated_to);
1022
-        }
1023
-        update_option(
1024
-            self::data_migration_script_option_prefix . $versions_migrated_to,
1025
-            $last_ran_migration_script_properties
1026
-        );
1027
-    }
1028
-
1029
-
1030
-    /**
1031
-     * saves what data migrations have run to the database
1032
-     *
1033
-     * @return bool|string TRUE if successfully saved migrations ran, string if an error occurred
1034
-     * @throws EE_Error
1035
-     */
1036
-    protected function _save_migrations_ran()
1037
-    {
1038
-        if ($this->_data_migrations_ran == null) {
1039
-            $this->get_data_migrations_ran();
1040
-        }
1041
-        // now, we don't want to save actual classes to the DB because that's messy
1042
-        $successful_updates = true;
1043
-        foreach ($this->_data_migrations_ran as $plugin_slug => $migrations_ran_for_plugin) {
1044
-            foreach ($migrations_ran_for_plugin as $version_string => $array_or_migration_obj) {
1045
-                $plugin_slug_for_use_in_option_name = $plugin_slug . ".";
1046
-                $option_name                        =
1047
-                    self::data_migration_script_option_prefix . $plugin_slug_for_use_in_option_name . $version_string;
1048
-                $old_option_value                   = get_option($option_name);
1049
-                if ($array_or_migration_obj instanceof EE_Data_Migration_Script_Base) {
1050
-                    $script_array_for_saving = $array_or_migration_obj->properties_as_array();
1051
-                    if ($old_option_value != $script_array_for_saving) {
1052
-                        $successful_updates = update_option($option_name, $script_array_for_saving);
1053
-                    }
1054
-                } else {// we don't know what this array-thing is. So just save it as-is
1055
-                    if ($old_option_value != $array_or_migration_obj) {
1056
-                        $successful_updates = update_option($option_name, $array_or_migration_obj);
1057
-                    }
1058
-                }
1059
-                if (! $successful_updates) {
1060
-                    global $wpdb;
1061
-                    return $wpdb->last_error;
1062
-                }
1063
-            }
1064
-        }
1065
-        return true;
1066
-        // $updated = update_option(self::data_migrations_option_name, $array_of_migrations);
1067
-        // if ($updated !== true) {
1068
-        //     global $wpdb;
1069
-        //     return $wpdb->last_error;
1070
-        // } else {
1071
-        //     return true;
1072
-        // }
1073
-        // wp_mail(
1074
-        //     "[email protected]",
1075
-        //     time() . " price debug info",
1076
-        //     "updated: $updated, last error: $last_error, byte length of option: " . strlen(
1077
-        //         serialize($array_of_migrations)
1078
-        //     )
1079
-        // );
1080
-    }
1081
-
1082
-
1083
-    /**
1084
-     * Takes an array of data migration script properties and re-creates the class from
1085
-     * them. The argument $properties_array is assumed to have been made by
1086
-     * EE_Data_Migration_Script_Base::properties_as_array()
1087
-     *
1088
-     * @param array $properties_array
1089
-     * @return EE_Data_Migration_Script_Base
1090
-     * @throws EE_Error
1091
-     */
1092
-    public function _instantiate_script_from_properties_array($properties_array)
1093
-    {
1094
-        if (! isset($properties_array['class'])) {
1095
-            throw new EE_Error(
1096
-                sprintf(
1097
-                    esc_html__("Properties array  has no 'class' properties. Here's what it has: %s", "event_espresso"),
1098
-                    implode(",", $properties_array)
1099
-                )
1100
-            );
1101
-        }
1102
-        $class_name = $properties_array['class'];
1103
-        if (! class_exists($class_name)) {
1104
-            throw new EE_Error(sprintf(
1105
-                esc_html__("There is no migration script named %s", "event_espresso"),
1106
-                $class_name
1107
-            ));
1108
-        }
1109
-        $class = new $class_name();
1110
-        if (! $class instanceof EE_Data_Migration_Script_Base) {
1111
-            throw new EE_Error(
1112
-                sprintf(
1113
-                    esc_html__(
1114
-                        "Class '%s' is supposed to be a migration script. Its not, its a '%s'",
1115
-                        "event_espresso"
1116
-                    ),
1117
-                    $class_name,
1118
-                    get_class($class)
1119
-                )
1120
-            );
1121
-        }
1122
-        $class->instantiate_from_array_of_properties($properties_array);
1123
-        return $class;
1124
-    }
1125
-
1126
-
1127
-    /**
1128
-     * Gets the classname for the most up-to-date DMS (ie, the one that will finally
1129
-     * leave the DB in a state usable by the current plugin code).
1130
-     *
1131
-     * @param string $plugin_slug the slug for the ee plugin we are searching for. Default is 'Core'
1132
-     * @return string
1133
-     * @throws EE_Error
1134
-     * @throws EE_Error
1135
-     */
1136
-    public function get_most_up_to_date_dms($plugin_slug = 'Core')
1137
-    {
1138
-        $class_to_filepath_map         = $this->get_all_data_migration_scripts_available();
1139
-        $most_up_to_date_dms_classname = null;
1140
-        foreach ($class_to_filepath_map as $classname => $filepath) {
1141
-            if ($most_up_to_date_dms_classname === null) {
1142
-                $migrates_to      = $this->script_migrates_to_version($classname);
1143
-                $this_plugin_slug = $migrates_to['slug'];
1144
-                if ($this_plugin_slug == $plugin_slug) {
1145
-                    // if it's for core, it wins
1146
-                    $most_up_to_date_dms_classname = $classname;
1147
-                }
1148
-                // if it wasn't for core, we must keep searching for one that is!
1149
-                continue;
1150
-            }
1151
-            $champion_migrates_to  = $this->script_migrates_to_version($most_up_to_date_dms_classname);
1152
-            $contender_migrates_to = $this->script_migrates_to_version($classname);
1153
-            if (
1154
-                $contender_migrates_to['slug'] == $plugin_slug
1155
-                && version_compare(
1156
-                    $champion_migrates_to['version'],
1157
-                    $contender_migrates_to['version'],
1158
-                    '<'
1159
-                )
1160
-            ) {
1161
-                // so the contenders version is higher, and it's for Core
1162
-                $most_up_to_date_dms_classname = $classname;
1163
-            }
1164
-        }
1165
-        return $most_up_to_date_dms_classname;
1166
-    }
1167
-
1168
-
1169
-    /**
1170
-     * Gets the migration script specified but ONLY if it has already run.
1171
-     *
1172
-     * Eg, if you wanted to see if 'EE_DMS_Core_4_1_0' has run, you would run the following code:
1173
-     * <code> $core_4_1_0_dms_ran = EE_Data_Migration_Manager::instance()->get_migration_ran( '4.1.0', 'Core' ) !==
1174
-     * NULL;</code> This is especially useful in addons' data migration scripts, this way they can tell if a core (or
1175
-     * other addon) DMS has run, in case the current DMS depends on it.
1176
-     *
1177
-     * @param string $version     the version the DMS searched for migrates to. Usually just the content before the 3rd
1178
-     *                            period. Eg '4.1.0'
1179
-     * @param string $plugin_slug like 'Core', 'Mailchimp', 'Calendar', etc
1180
-     * @return EE_Data_Migration_Script_Base
1181
-     * @throws EE_Error
1182
-     */
1183
-    public function get_migration_ran($version, $plugin_slug = 'Core')
1184
-    {
1185
-        $migrations_ran = $this->get_data_migrations_ran();
1186
-        if (isset($migrations_ran[ $plugin_slug ]) && isset($migrations_ran[ $plugin_slug ][ $version ])) {
1187
-            return $migrations_ran[ $plugin_slug ][ $version ];
1188
-        } else {
1189
-            return null;
1190
-        }
1191
-    }
1192
-
1193
-
1194
-    /**
1195
-     * Resets the borked data migration scripts, so they're no longer borked, and we can again attempt to migrate
1196
-     *
1197
-     * @return bool
1198
-     * @throws EE_Error
1199
-     */
1200
-    public function reattempt()
1201
-    {
1202
-        // find if the last-run script was borked
1203
-        // set it as being non-borked (we shouldn't ever get DMSs that we don't recognize)
1204
-        // add an 'error' saying that we attempted to reset
1205
-        // does it have a stage that was borked too? if so make it no longer borked
1206
-        // add an 'error' saying we attempted to reset
1207
-        $last_ran_script = $this->get_last_ran_script();
1208
-        if ($last_ran_script instanceof EE_DMS_Unknown_1_0_0) {
1209
-            // if it was an error DMS, just mark it as complete (if another error occurs it will overwrite it)
1210
-            $last_ran_script->set_completed();
1211
-        } elseif ($last_ran_script instanceof EE_Data_Migration_Script_Base) {
1212
-            $last_ran_script->reattempt();
1213
-        } else {
1214
-            throw new EE_Error(
1215
-                sprintf(
1216
-                    esc_html__(
1217
-                        'Unable to reattempt the last ran migration script because it was not a valid migration script. || It was %s',
1218
-                        'event_espresso'
1219
-                    ),
1220
-                    print_r($last_ran_script, true)
1221
-                )
1222
-            );
1223
-        }
1224
-        return $this->_save_migrations_ran();
1225
-    }
1226
-
1227
-
1228
-    /**
1229
-     * Gets whether this particular migration has run or not
1230
-     *
1231
-     * @param string $version     the version the DMS searched for migrates to. Usually just the content before the 3rd
1232
-     *                            period. Eg '4.1.0'
1233
-     * @param string $plugin_slug like 'Core', 'Mailchimp', 'Calendar', etc
1234
-     * @return boolean
1235
-     * @throws EE_Error
1236
-     */
1237
-    public function migration_has_ran($version, $plugin_slug = 'Core')
1238
-    {
1239
-        return $this->get_migration_ran($version, $plugin_slug) !== null;
1240
-    }
1241
-
1242
-
1243
-    /**
1244
-     * Enqueues this ee plugin to have its data initialized
1245
-     *
1246
-     * @param string $plugin_slug either 'Core' or EE_Addon::name()'s return value
1247
-     */
1248
-    public function enqueue_db_initialization_for($plugin_slug)
1249
-    {
1250
-        $queue = $this->get_db_initialization_queue();
1251
-        if (! in_array($plugin_slug, $queue)) {
1252
-            $queue[] = $plugin_slug;
1253
-        }
1254
-        update_option(self::db_init_queue_option_name, $queue);
1255
-    }
1256
-
1257
-
1258
-    /**
1259
-     * Calls EE_Addon::initialize_db_if_no_migrations_required() on each addon
1260
-     * specified in EE_Data_Migration_Manager::get_db_init_queue(), and if 'Core' is
1261
-     * in the queue, calls EE_System::initialize_db_if_no_migrations_required().
1262
-     *
1263
-     * @throws EE_Error
1264
-     */
1265
-    public function initialize_db_for_enqueued_ee_plugins()
1266
-    {
1267
-        $queue = $this->get_db_initialization_queue();
1268
-        foreach ($queue as $plugin_slug) {
1269
-            $most_up_to_date_dms = $this->get_most_up_to_date_dms($plugin_slug);
1270
-            if (! $most_up_to_date_dms) {
1271
-                // if there is NO DMS for this plugin, obviously there's no schema to verify anyways
1272
-                $verify_db = false;
1273
-            } else {
1274
-                $most_up_to_date_dms_migrates_to = $this->script_migrates_to_version($most_up_to_date_dms);
1275
-                $verify_db                       = $this->database_needs_updating_to($most_up_to_date_dms_migrates_to);
1276
-            }
1277
-            if ($plugin_slug == 'Core') {
1278
-                EE_System::instance()->initialize_db_if_no_migrations_required(
1279
-                    false,
1280
-                    $verify_db
1281
-                );
1282
-            } else {
1283
-                // just loop through the addons to make sure their database is set up
1284
-                foreach (EE_Registry::instance()->addons as $addon) {
1285
-                    if ($addon->name() == $plugin_slug) {
1286
-                        $addon->initialize_db_if_no_migrations_required($verify_db);
1287
-                        break;
1288
-                    }
1289
-                }
1290
-            }
1291
-        }
1292
-        // because we just initialized the DBs for the enqueued ee plugins
1293
-        // we don't need to keep remembering which ones needed to be initialized
1294
-        delete_option(self::db_init_queue_option_name);
1295
-    }
1296
-
1297
-
1298
-    /**
1299
-     * Gets a numerically-indexed array of plugin slugs that need to have their databases
1300
-     * (re-)initialized after migrations are complete. ie, each element should be either
1301
-     * 'Core', or the return value of EE_Addon::name() for an addon
1302
-     *
1303
-     * @return array
1304
-     */
1305
-    public function get_db_initialization_queue()
1306
-    {
1307
-        return get_option(self::db_init_queue_option_name, []);
1308
-    }
1309
-
1310
-
1311
-    /**
1312
-     * Gets the injected table analyzer, or throws an exception
1313
-     *
1314
-     * @return TableAnalysis
1315
-     * @throws EE_Error
1316
-     */
1317
-    protected function _get_table_analysis()
1318
-    {
1319
-        if ($this->_table_analysis instanceof TableAnalysis) {
1320
-            return $this->_table_analysis;
1321
-        } else {
1322
-            throw new EE_Error(
1323
-                sprintf(
1324
-                    esc_html__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
1325
-                    get_class($this)
1326
-                )
1327
-            );
1328
-        }
1329
-    }
1330
-
1331
-
1332
-    /**
1333
-     * Gets the injected table manager, or throws an exception
1334
-     *
1335
-     * @return TableManager
1336
-     * @throws EE_Error
1337
-     */
1338
-    protected function _get_table_manager()
1339
-    {
1340
-        if ($this->_table_manager instanceof TableManager) {
1341
-            return $this->_table_manager;
1342
-        } else {
1343
-            throw new EE_Error(
1344
-                sprintf(
1345
-                    esc_html__('Table manager class on class %1$s is not set properly.', 'event_espresso'),
1346
-                    get_class($this)
1347
-                )
1348
-            );
1349
-        }
1350
-    }
35
+	/**
36
+	 *
37
+	 * @var EE_Registry
38
+	 */
39
+	// protected $EE;
40
+	/**
41
+	 * name of the WordPress option which stores an array of data about
42
+	 */
43
+	const data_migrations_option_name = 'ee_data_migration';
44
+
45
+
46
+	const data_migration_script_option_prefix         = 'ee_data_migration_script_';
47
+
48
+	const data_migration_script_mapping_option_prefix = 'ee_dms_map_';
49
+
50
+	/**
51
+	 * name of the WordPress option which stores the database' current version. IE, the code may be at version 4.2.0,
52
+	 * but as migrations are performed the database will progress from 3.1.35 to 4.1.0 etc.
53
+	 */
54
+	const current_database_state = 'ee_data_migration_current_db_state';
55
+
56
+	/**
57
+	 * Special status string returned when we're positive there are no more data migration
58
+	 * scripts that can be run.
59
+	 */
60
+	const status_no_more_migration_scripts = 'no_more_migration_scripts';
61
+
62
+	/**
63
+	 * string indicating the migration should continue
64
+	 */
65
+	const status_continue = 'status_continue';
66
+
67
+	/**
68
+	 * string indicating the migration has completed and should be ended
69
+	 */
70
+	const status_completed = 'status_completed';
71
+
72
+	/**
73
+	 * string indicating a fatal error occurred and the data migration should be completely aborted
74
+	 */
75
+	const status_fatal_error = 'status_fatal_error';
76
+
77
+	/**
78
+	 * the number of 'items' (usually DB rows) to migrate on each 'step' (ajax request sent
79
+	 * during migration)
80
+	 */
81
+	const step_size = 50;
82
+
83
+	/**
84
+	 * option name that stores the queue of ee plugins needing to have
85
+	 * their data initialized (or re-initialized) once we are done migrations
86
+	 */
87
+	const db_init_queue_option_name = 'ee_db_init_queue';
88
+
89
+	/**
90
+	 * Array of information concerning data migrations that have run in the history
91
+	 * of this EE installation. Keys should be the name of the version the script upgraded to
92
+	 *
93
+	 * @var EE_Data_Migration_Script_Base[]
94
+	 */
95
+	private $_data_migrations_ran = null;
96
+
97
+	/**
98
+	 * The last run script. It's nice to store this somewhere accessible, as its easiest
99
+	 * to know which was the last run by which is the newest wp option; but in most of the code
100
+	 * we just use the local $_data_migration_ran array, which organized the scripts differently
101
+	 *
102
+	 * @var EE_Data_Migration_Script_Base
103
+	 */
104
+	private $_last_ran_script = null;
105
+
106
+	/**
107
+	 * Similarly to _last_ran_script, but this is the last INCOMPLETE migration script.
108
+	 *
109
+	 * @var EE_Data_Migration_Script_Base
110
+	 */
111
+	private $_last_ran_incomplete_script = null;
112
+
113
+	/**
114
+	 * array where keys are classnames, and values are filepaths of all the known migration scripts
115
+	 *
116
+	 * @var array
117
+	 */
118
+	private $_data_migration_class_to_filepath_map;
119
+
120
+	/**
121
+	 * the following 4 properties are fully set on construction.
122
+	 * Note: the first two apply to whether to continue running ALL migration scripts (ie, even though we're finished
123
+	 * one, we may want to start the next one); whereas the last two indicate whether to continue running a single
124
+	 * data migration script
125
+	 *
126
+	 * @var array
127
+	 */
128
+	public $stati_that_indicate_to_continue_migrations              = [];
129
+
130
+	public $stati_that_indicate_to_stop_migrations                  = [];
131
+
132
+	public $stati_that_indicate_to_continue_single_migration_script = [];
133
+
134
+	public $stati_that_indicate_to_stop_single_migration_script     = [];
135
+
136
+	/**
137
+	 * @var TableManager $table_manager
138
+	 */
139
+	protected $_table_manager;
140
+
141
+	/**
142
+	 * @var TableAnalysis $table_analysis
143
+	 */
144
+	protected $_table_analysis;
145
+
146
+	/**
147
+	 * @var array $script_migration_versions
148
+	 */
149
+	protected $script_migration_versions;
150
+
151
+	/**
152
+	 * @var EE_Data_Migration_Manager $_instance
153
+	 * @access    private
154
+	 */
155
+	private static $_instance = null;
156
+
157
+
158
+	/**
159
+	 * @singleton method used to instantiate class object
160
+	 * @access    public
161
+	 * @return EE_Data_Migration_Manager instance
162
+	 */
163
+	public static function instance()
164
+	{
165
+		// check if class object is instantiated
166
+		if (! self::$_instance instanceof EE_Data_Migration_Manager) {
167
+			self::$_instance = new self();
168
+		}
169
+		return self::$_instance;
170
+	}
171
+
172
+
173
+	/**
174
+	 * resets the singleton to its brand-new state (but does NOT delete old references to the old singleton. Meaning,
175
+	 * all new usages of the singleton should be made with Classname::instance()) and returns it
176
+	 *
177
+	 * @return EE_Data_Migration_Manager
178
+	 */
179
+	public static function reset()
180
+	{
181
+		self::$_instance = null;
182
+		return self::instance();
183
+	}
184
+
185
+
186
+	/**
187
+	 * @throws EE_Error
188
+	 * @throws ReflectionException
189
+	 */
190
+	private function __construct()
191
+	{
192
+		$this->stati_that_indicate_to_continue_migrations              = [
193
+			self::status_continue,
194
+			self::status_completed,
195
+		];
196
+		$this->stati_that_indicate_to_stop_migrations                  = [
197
+			self::status_fatal_error,
198
+			self::status_no_more_migration_scripts,
199
+		];
200
+		$this->stati_that_indicate_to_continue_single_migration_script = [
201
+			self::status_continue,
202
+		];
203
+		$this->stati_that_indicate_to_stop_single_migration_script     = [
204
+			self::status_completed,
205
+			self::status_fatal_error
206
+			// note: status_no_more_migration_scripts doesn't apply
207
+		];
208
+		// make sure we've included the base migration script, because we may need the EE_DMS_Unknown_1_0_0 class
209
+		// to be defined, because right now it doesn't get autoloaded on its own
210
+		EE_Registry::instance()->load_core('Data_Migration_Class_Base', [], true);
211
+		EE_Registry::instance()->load_core('Data_Migration_Script_Base', [], true);
212
+		EE_Registry::instance()->load_core('DMS_Unknown_1_0_0', [], true);
213
+		EE_Registry::instance()->load_core('Data_Migration_Script_Stage', [], true);
214
+		EE_Registry::instance()->load_core('Data_Migration_Script_Stage_Table', [], true);
215
+		$this->_table_manager  = EE_Registry::instance()->create('TableManager', [], true);
216
+		$this->_table_analysis = EE_Registry::instance()->create('TableAnalysis', [], true);
217
+	}
218
+
219
+
220
+	/**
221
+	 * Deciphers, from an option's name, what plugin and version it relates to (see _save_migrations_ran to see what
222
+	 * the option names are like, but generally they're like
223
+	 * 'ee_data_migration_script_Core.4.1.0' in 4.2 or 'ee_data_migration_script_4.1.0' before that).
224
+	 * The option name shouldn't ever be like 'ee_data_migration_script_Core.4.1.0.reg' because it's derived,
225
+	 * indirectly, from the data migration's classname, which should always be like EE_DMS_%s_%d_%d_%d.dms.php
226
+	 * (ex: EE_DMS_Core_4_1_0.dms.php)
227
+	 *
228
+	 * @param string $option_name (see EE_Data_Migration_Manage::_save_migrations_ran() where the option name is set)
229
+	 * @return array where the first item is the plugin slug (eg 'Core','Calendar', etc.) and the 2nd is the version of
230
+	 *                            that plugin (eg '4.1.0')
231
+	 */
232
+	private function _get_plugin_slug_and_version_string_from_dms_option_name($option_name)
233
+	{
234
+		$plugin_slug_and_version_string = str_replace(
235
+			EE_Data_Migration_Manager::data_migration_script_option_prefix,
236
+			"",
237
+			$option_name
238
+		);
239
+		// check if $plugin_slug_and_version_string is like '4.1.0' (4.1-style) or 'Core.4.1.0' (4.2-style)
240
+		$parts = explode(".", $plugin_slug_and_version_string);
241
+
242
+		if (count($parts) == 4) {
243
+			// it's 4.2-style.eg Core.4.1.0
244
+			$plugin_slug    = $parts[0];                                     // eg Core
245
+			$version_string = $parts[1] . "." . $parts[2] . "." . $parts[3]; // eg 4.1.0
246
+		} else {
247
+			// it's 4.1-style: eg 4.1.0
248
+			$plugin_slug    = 'Core';
249
+			$version_string = $plugin_slug_and_version_string;// eg 4.1.0
250
+		}
251
+		return [$plugin_slug, $version_string];
252
+	}
253
+
254
+
255
+	/**
256
+	 * Gets the DMS class from the WordPress option, otherwise throws an EE_Error if it's not
257
+	 * for a known DMS class.
258
+	 *
259
+	 * @param string $dms_option_name
260
+	 * @param string $dms_option_value (serialized)
261
+	 * @return EE_Data_Migration_Script_Base
262
+	 * @throws EE_Error
263
+	 */
264
+	private function _get_dms_class_from_wp_option($dms_option_name, $dms_option_value)
265
+	{
266
+		$data_migration_data = maybe_unserialize($dms_option_value);
267
+		if (isset($data_migration_data['class']) && class_exists($data_migration_data['class'])) {
268
+			// During multisite migrations, it's possible we already grabbed another instance of this class
269
+			// but for a different blog. Make sure we don't reuse them (as they store info specific
270
+			// to their respective blog, like which database table to migrate).
271
+			$class = LoaderFactory::getLoader()->getNew($data_migration_data['class']);
272
+			if ($class instanceof EE_Data_Migration_Script_Base) {
273
+				$class->instantiate_from_array_of_properties($data_migration_data);
274
+				return $class;
275
+			} else {
276
+				// huh, so it's an object but not a data migration script?? that shouldn't happen
277
+				// just leave it as an array (which will probably just get ignored)
278
+				throw new EE_Error(
279
+					sprintf(
280
+						esc_html__(
281
+							"Trying to retrieve DMS class from wp option. No DMS by the name '%s' exists",
282
+							'event_espresso'
283
+						),
284
+						$data_migration_data['class']
285
+					)
286
+				);
287
+			}
288
+		} else {
289
+			// so the data doesn't specify a class. So it must either be a legacy array of info or some array (which we'll probably just ignore), or a class that no longer exists
290
+			throw new EE_Error(
291
+				sprintf(
292
+					esc_html__("The wp option  with key '%s' does not represent a DMS", 'event_espresso'),
293
+					$dms_option_name
294
+				)
295
+			);
296
+		}
297
+	}
298
+
299
+
300
+	/**
301
+	 * Gets the array describing what data migrations have run.
302
+	 * Also has a side effect of recording which was the last run,
303
+	 * and which was the last run which hasn't finished yet
304
+	 *
305
+	 * @return array where each element should be an array of EE_Data_Migration_Script_Base
306
+	 *               (but also has a few legacy arrays in there - which should probably be ignored)
307
+	 * @throws EE_Error
308
+	 */
309
+	public function get_data_migrations_ran()
310
+	{
311
+		if (! $this->_data_migrations_ran) {
312
+			// setup autoloaders for each of the scripts in there
313
+			$this->get_all_data_migration_scripts_available();
314
+			$data_migrations_options =
315
+				$this->get_all_migration_script_options();// get_option(EE_Data_Migration_Manager::data_migrations_option_name,get_option('espresso_data_migrations',array()));
316
+
317
+			$data_migrations_ran = [];
318
+			// convert into data migration script classes where possible
319
+			foreach ($data_migrations_options as $data_migration_option) {
320
+				list($plugin_slug, $version_string) = $this->_get_plugin_slug_and_version_string_from_dms_option_name(
321
+					$data_migration_option['option_name']
322
+				);
323
+
324
+				try {
325
+					$class                                                  = $this->_get_dms_class_from_wp_option(
326
+						$data_migration_option['option_name'],
327
+						$data_migration_option['option_value']
328
+					);
329
+					$data_migrations_ran[ $plugin_slug ][ $version_string ] = $class;
330
+					// ok so far THIS is the 'last-run-script'... unless we find another on next iteration
331
+					$this->_last_ran_script = $class;
332
+					if (! $class->is_completed()) {
333
+						// sometimes we also like to know which was the last incomplete script (or if there are any at all)
334
+						$this->_last_ran_incomplete_script = $class;
335
+					}
336
+				} catch (EE_Error $e) {
337
+					// ok so it's not a DMS. We'll just keep it, although other code will need to expect non-DMSs
338
+					$data_migrations_ran[ $plugin_slug ][ $version_string ] = maybe_unserialize(
339
+						$data_migration_option['option_value']
340
+					);
341
+				}
342
+			}
343
+			// so here the array of $data_migrations_ran is actually a mix of classes and a few legacy arrays
344
+			$this->_data_migrations_ran = $data_migrations_ran;
345
+			if (! $this->_data_migrations_ran || ! is_array($this->_data_migrations_ran)) {
346
+				$this->_data_migrations_ran = [];
347
+			}
348
+		}
349
+		return $this->_data_migrations_ran;
350
+	}
351
+
352
+
353
+	/**
354
+	 *
355
+	 * @param string $script_name eg 'DMS_Core_4_1_0'
356
+	 * @param string $old_table   eg 'wp_events_detail'
357
+	 * @param string $old_pk      eg 'wp_esp_posts'
358
+	 * @param        $new_table
359
+	 * @return mixed string or int
360
+	 * @throws EE_Error
361
+	 * @throws ReflectionException
362
+	 */
363
+	public function get_mapping_new_pk($script_name, $old_table, $old_pk, $new_table)
364
+	{
365
+		$script  = EE_Registry::instance()->load_dms($script_name);
366
+		return $script->get_mapping_new_pk($old_table, $old_pk, $new_table);
367
+	}
368
+
369
+
370
+	/**
371
+	 * Gets all the options containing migration scripts that have been run. Ordering is important: it's assumed that
372
+	 * the last option returned in this array is the most-recently run DMS option
373
+	 *
374
+	 * @return array
375
+	 */
376
+	public function get_all_migration_script_options()
377
+	{
378
+		global $wpdb;
379
+		return $wpdb->get_results(
380
+			"SELECT * FROM {$wpdb->options} WHERE option_name like '"
381
+			. EE_Data_Migration_Manager::data_migration_script_option_prefix
382
+			. "%' ORDER BY option_id ASC",
383
+			ARRAY_A
384
+		);
385
+	}
386
+
387
+
388
+	/**
389
+	 * Gets the array of folders which contain data migration scripts. Also adds them to be auto-loaded
390
+	 *
391
+	 * @return array where each value is the full folder path of a folder containing data migration scripts, WITH
392
+	 *               slashes at the end of the folder name.
393
+	 */
394
+	public function get_data_migration_script_folders()
395
+	{
396
+		return apply_filters(
397
+			'FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',
398
+			['Core' => EE_CORE . 'data_migration_scripts']
399
+		);
400
+	}
401
+
402
+
403
+	/**
404
+	 * Gets the version the migration script upgrades to
405
+	 *
406
+	 * @param string $migration_script_name eg 'EE_DMS_Core_4_1_0'
407
+	 * @return array {
408
+	 *      @type string  $slug     like 'Core','Calendar',etc
409
+	 *      @type string  $version  like 4.3.0
410
+	 * }
411
+	 * @throws EE_Error
412
+	 */
413
+	public function script_migrates_to_version($migration_script_name, $eeAddonClass = '')
414
+	{
415
+		if (isset($this->script_migration_versions[ $migration_script_name ])) {
416
+			return $this->script_migration_versions[ $migration_script_name ];
417
+		}
418
+		$dms_info                                                  = $this->parse_dms_classname($migration_script_name);
419
+		$this->script_migration_versions[ $migration_script_name ] = [
420
+			'slug'    => $eeAddonClass !== '' ? $eeAddonClass : $dms_info['slug'],
421
+			'version' => $dms_info['major_version']
422
+						 . "."
423
+						 . $dms_info['minor_version']
424
+						 . "."
425
+						 . $dms_info['micro_version'],
426
+		];
427
+		return $this->script_migration_versions[ $migration_script_name ];
428
+	}
429
+
430
+
431
+	/**
432
+	 * Gets the juicy details out of a dms filename like 'EE_DMS_Core_4_1_0'
433
+	 *
434
+	 * @param string $classname
435
+	 * @return array with keys 'slug','major_version','minor_version', and 'micro_version' (the last 3 are integers)
436
+	 * @throws EE_Error
437
+	 */
438
+	public function parse_dms_classname($classname)
439
+	{
440
+		$matches = [];
441
+		preg_match('~EE_DMS_(.*)_([0-9]*)_([0-9]*)_([0-9]*)~', $classname, $matches);
442
+		if (! $matches || ! (isset($matches[1]) && isset($matches[2]) && isset($matches[3]))) {
443
+			throw new EE_Error(
444
+				sprintf(
445
+					esc_html__(
446
+						"%s is not a valid Data Migration Script. The classname should be like EE_DMS_w_x_y_z, where w is either 'Core' or the slug of an addon and x, y and z are numbers, ",
447
+						"event_espresso"
448
+					),
449
+					$classname
450
+				)
451
+			);
452
+		}
453
+		return [
454
+			'slug'          => $matches[1],
455
+			'major_version' => intval($matches[2]),
456
+			'minor_version' => intval($matches[3]),
457
+			'micro_version' => intval($matches[4]),
458
+		];
459
+	}
460
+
461
+
462
+	/**
463
+	 * Ensures that the option indicating the current DB version is set. This should only be
464
+	 * a concern when activating EE for the first time, THEORETICALLY.
465
+	 * If we detect that we're activating EE4 over top of EE3.1, then we set the current db state to 3.1.x, otherwise
466
+	 * to 4.1.x.
467
+	 *
468
+	 * @return string of current db state
469
+	 */
470
+	public function ensure_current_database_state_is_set()
471
+	{
472
+		$espresso_db_core_updates = get_option('espresso_db_update', []);
473
+		$db_state                 = get_option(EE_Data_Migration_Manager::current_database_state);
474
+		if (! $db_state) {
475
+			// mark the DB as being in the state as the last version in there.
476
+			// this is done to trigger maintenance mode and do data migration scripts
477
+			// if the admin installed this version of EE over 3.1.x or 4.0.x
478
+			// otherwise, the normal maintenance mode code is fine
479
+			$previous_versions_installed = array_keys($espresso_db_core_updates);
480
+			$previous_version_installed  = end($previous_versions_installed);
481
+			if (version_compare('4.1.0', $previous_version_installed)) {
482
+				// last installed version was less than 4.1, so we want the data migrations to happen.
483
+				// SO, we're going to say the DB is at that state
484
+				$db_state = ['Core' => $previous_version_installed];
485
+			} else {
486
+				$db_state = ['Core' => EVENT_ESPRESSO_VERSION];
487
+			}
488
+			update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
489
+		}
490
+		// in 4.1, $db_state would have only been a simple string like '4.1.0',
491
+		// but in 4.2+ it should be an array with at least key 'Core' and the value of that plugin's
492
+		// db, and possibly other keys for other addons like 'Calendar','Permissions',etc
493
+		if (! is_array($db_state)) {
494
+			$db_state = ['Core' => $db_state];
495
+			update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
496
+		}
497
+		return $db_state;
498
+	}
499
+
500
+
501
+	/**
502
+	 * Checks if there are any data migration scripts that ought to be run.
503
+	 * If found, returns the instantiated classes.
504
+	 * If none are found (ie, they've all already been run, or they don't apply), returns an empty array
505
+	 *
506
+	 * @return EE_Data_Migration_Script_Base[]
507
+	 * @throws EE_Error
508
+	 * @throws EE_Error
509
+	 */
510
+	public function check_for_applicable_data_migration_scripts()
511
+	{
512
+		// get the option describing what options have already run
513
+		$scripts_ran = $this->get_data_migrations_ran();
514
+		// $scripts_ran = array('4.1.0.core'=>array('monkey'=>null));
515
+		$script_class_and_filepaths_available = $this->get_all_data_migration_scripts_available();
516
+
517
+
518
+		$current_database_state = $this->ensure_current_database_state_is_set();
519
+		// determine which have already been run
520
+		$script_classes_that_should_run_per_iteration = [];
521
+		$iteration                                    = 0;
522
+		$next_database_state_to_consider              = $current_database_state;
523
+		$theoretical_database_state = null;
524
+		do {
525
+			// the next state after the currently-considered one
526
+			// will start off looking the same as the current, but we may make additions...
527
+			$theoretical_database_state = $next_database_state_to_consider;
528
+			// the next db state to consider is
529
+			// "what would the DB be like had we run all the scripts we found that applied last time?"
530
+			foreach ($script_class_and_filepaths_available as $classname => $filepath) {
531
+				$migrates_to_version         = $this->script_migrates_to_version($classname);
532
+				$script_converts_plugin_slug = $migrates_to_version['slug'];
533
+				$script_converts_to_version  = $migrates_to_version['version'];
534
+				// check if this version script is DONE or not; or if it's never been run
535
+				if (
536
+					! $scripts_ran
537
+					|| ! isset($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ])
538
+				) {
539
+					// we haven't run this conversion script before
540
+					// now check if it applies...
541
+					// note that we've added an autoloader for it on get_all_data_migration_scripts_available
542
+					// Also, make sure we get a new one. It's possible this is being ran during a multisite migration,
543
+					// in which case we don't want to reuse a DMS script from a different blog!
544
+					$script = LoaderFactory::getLoader()->getNew($classname);
545
+					/* @var $script EE_Data_Migration_Script_Base */
546
+					$can_migrate = $script->can_migrate_from_version($theoretical_database_state);
547
+					if ($can_migrate) {
548
+						$script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
549
+						$migrates_to_version                                                                 =
550
+							$script->migrates_to_version();
551
+						$next_database_state_to_consider[ $migrates_to_version['slug'] ]                     =
552
+							$migrates_to_version['version'];
553
+						unset($script_class_and_filepaths_available[ $classname ]);
554
+					}
555
+				} elseif (
556
+					$scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ]
557
+						  instanceof
558
+						  EE_Data_Migration_Script_Base
559
+				) {
560
+					// this script has been run, or at least started
561
+					$script = $scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ];
562
+					if ($script->get_status() !== self::status_completed) {
563
+						// this script is already underway... keep going with it
564
+						$script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
565
+						$migrates_to_version                                                                 =
566
+							$script->migrates_to_version();
567
+						$next_database_state_to_consider[ $migrates_to_version['slug'] ]                     =
568
+							$migrates_to_version['version'];
569
+						unset($script_class_and_filepaths_available[ $classname ]);
570
+					}
571
+					// else it must have a status that indicates it has finished,
572
+					// so we don't want to try and run it again
573
+				}
574
+				// else it exists, but it's not  a proper data migration script maybe the script got renamed?
575
+				// or was simply removed from EE? either way, it's certainly not runnable!
576
+			}
577
+			$iteration++;
578
+		} while ($next_database_state_to_consider !== $theoretical_database_state && $iteration < 6);
579
+		// ok we have all the scripts that should run, now let's make them into flat array
580
+		$scripts_that_should_run = [];
581
+		foreach ($script_classes_that_should_run_per_iteration as $scripts_at_priority) {
582
+			ksort($scripts_at_priority);
583
+			foreach ($scripts_at_priority as $scripts) {
584
+				foreach ($scripts as $script) {
585
+					$scripts_that_should_run[ get_class($script) ] = $script;
586
+				}
587
+			}
588
+		}
589
+
590
+		do_action(
591
+			'AHEE__EE_Data_Migration_Manager__check_for_applicable_data_migration_scripts__scripts_that_should_run',
592
+			$scripts_that_should_run
593
+		);
594
+		return $scripts_that_should_run;
595
+	}
596
+
597
+
598
+	/**
599
+	 * Gets the script which is currently being run, if there is one. If $include_completed_scripts is set to TRUE
600
+	 * it will return the last run script even if it's complete.
601
+	 * This means: if you want to find the currently-executing script, leave it as FALSE.
602
+	 * If you really just want to find the script which ran most recently, regardless of status, leave it as TRUE.
603
+	 *
604
+	 * @param bool $include_completed_scripts
605
+	 * @return EE_Data_Migration_Script_Base
606
+	 * @throws EE_Error
607
+	 */
608
+	public function get_last_ran_script($include_completed_scripts = false)
609
+	{
610
+		// make sure we've set up the class properties _last_ran_script and _last_ran_incomplete_script
611
+		if (! $this->_data_migrations_ran) {
612
+			$this->get_data_migrations_ran();
613
+		}
614
+		if ($include_completed_scripts) {
615
+			return $this->_last_ran_script;
616
+		} else {
617
+			return $this->_last_ran_incomplete_script;
618
+		}
619
+	}
620
+
621
+
622
+	/**
623
+	 * Runs the data migration scripts (well, each request to this method calls one of the
624
+	 * data migration scripts' migration_step() functions).
625
+	 *
626
+	 * @param int   $step_size
627
+	 * @return array {
628
+	 *                                  // where the first item is one EE_Data_Migration_Script_Base's stati,
629
+	 *                                  //and the second item is a string describing what was done
630
+	 * @type int    $records_to_migrate from the current migration script
631
+	 * @type int    $records_migrated
632
+	 * @type string $status             one of EE_Data_Migration_Manager::status_*
633
+	 * @type string $script             verbose name of the current DMS
634
+	 * @type string $message            string describing what was done during this step
635
+	 *                                  }
636
+	 * @throws EE_Error
637
+	 */
638
+	public function migration_step($step_size = 0)
639
+	{
640
+
641
+		// bandaid fix for issue https://events.codebasehq.com/projects/event-espresso/tickets/7535
642
+		if (class_exists('EE_CPT_Strategy')) {
643
+			remove_action('pre_get_posts', [EE_CPT_Strategy::instance(), 'pre_get_posts'], 5);
644
+		}
645
+
646
+		try {
647
+			$currently_executing_script = $this->get_last_ran_script();
648
+			if (! $currently_executing_script) {
649
+				// Find the next script that needs to execute
650
+				$scripts = $this->check_for_applicable_data_migration_scripts();
651
+				if (! $scripts) {
652
+					// huh, no more scripts to run... apparently we're done!
653
+					// but don't forget to make sure initial data is there
654
+					// we should be good to allow them to exit maintenance mode now
655
+					EE_Maintenance_Mode::instance()->set_maintenance_level(
656
+						EE_Maintenance_Mode::level_0_not_in_maintenance
657
+					);
658
+					// saving migrations run should actually be unnecessary,
659
+					// but leaving in place just in case... remember this migration was finished
660
+					// (even if we time out while initializing db for core and plugins)
661
+					$this->_save_migrations_ran();
662
+					// make sure DB was updated AFTER we've recorded the migration was done
663
+					$this->initialize_db_for_enqueued_ee_plugins();
664
+					return [
665
+						'records_to_migrate' => 1,
666
+						'records_migrated'   => 1,
667
+						'status'             => self::status_no_more_migration_scripts,
668
+						'script'             => esc_html__("Data Migration Completed Successfully", "event_espresso"),
669
+						'message'            => esc_html__("All done!", "event_espresso"),
670
+					];
671
+				}
672
+				$currently_executing_script = array_shift($scripts);
673
+				// and add to the array/wp option showing the scripts run
674
+
675
+				$migrates_to                                            =
676
+					$this->script_migrates_to_version(get_class($currently_executing_script));
677
+				$plugin_slug                                            = $migrates_to['slug'];
678
+				$version                                                = $migrates_to['version'];
679
+				$this->_data_migrations_ran[ $plugin_slug ][ $version ] = $currently_executing_script;
680
+			}
681
+			$current_script_name = get_class($currently_executing_script);
682
+		} catch (Exception $e) {
683
+			// an exception occurred while trying to get migration scripts
684
+
685
+			$message = sprintf(
686
+				esc_html__("Error Message: %sStack Trace:%s", "event_espresso"),
687
+				$e->getMessage() . '<br>',
688
+				$e->getTraceAsString()
689
+			);
690
+			// record it on the array of data migration scripts run. This will be overwritten next time we try and try to run data migrations
691
+			// but that's ok-- it's just an FYI to support that we couldn't even run any data migrations
692
+			$this->add_error_to_migrations_ran(
693
+				sprintf(esc_html__("Could not run data migrations because: %s", "event_espresso"), $message)
694
+			);
695
+			return [
696
+				'records_to_migrate' => 1,
697
+				'records_migrated'   => 0,
698
+				'status'             => self::status_fatal_error,
699
+				'script'             => esc_html__("Error loading data migration scripts", "event_espresso"),
700
+				'message'            => $message,
701
+			];
702
+		}
703
+		// can we wrap it up and verify default data?
704
+		$init_dbs = false;
705
+		// ok so we definitely have a data migration script
706
+		try {
707
+			// how big of a bite do we want to take? Allow users to easily override via their wp-config
708
+			if (absint($step_size) < 1) {
709
+				$step_size = defined('EE_MIGRATION_STEP_SIZE') && absint(EE_MIGRATION_STEP_SIZE)
710
+					? EE_MIGRATION_STEP_SIZE
711
+					: EE_Data_Migration_Manager::step_size;
712
+			}
713
+			// do what we came to do!
714
+			$currently_executing_script->migration_step($step_size);
715
+			switch ($currently_executing_script->get_status()) {
716
+				case EE_Data_Migration_Manager::status_continue:
717
+					$response_array = [
718
+						'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
719
+						'records_migrated'   => $currently_executing_script->count_records_migrated(),
720
+						'status'             => EE_Data_Migration_Manager::status_continue,
721
+						'message'            => $currently_executing_script->get_feedback_message(),
722
+						'script'             => $currently_executing_script->pretty_name(),
723
+					];
724
+					break;
725
+				case EE_Data_Migration_Manager::status_completed:
726
+					// ok so THAT script has completed
727
+					$this->update_current_database_state_to($this->script_migrates_to_version($current_script_name));
728
+					$response_array = [
729
+						'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
730
+						'records_migrated'   => $currently_executing_script->count_records_migrated(),
731
+						'status'             => EE_Data_Migration_Manager::status_completed,
732
+						'message'            => $currently_executing_script->get_feedback_message(),
733
+						'script'             => sprintf(
734
+							esc_html__("%s Completed", 'event_espresso'),
735
+							$currently_executing_script->pretty_name()
736
+						),
737
+					];
738
+					// check if there are any more after this one.
739
+					$scripts_remaining = $this->check_for_applicable_data_migration_scripts();
740
+					if (! $scripts_remaining) {
741
+						// we should be good to allow them to exit maintenance mode now
742
+						EE_Maintenance_Mode::instance()->set_maintenance_level(
743
+							EE_Maintenance_Mode::level_0_not_in_maintenance
744
+						);
745
+						// huh, no more scripts to run... apparently we're done!
746
+						// but don't forget to make sure initial data is there
747
+						$init_dbs                 = true;
748
+						$response_array['status'] = self::status_no_more_migration_scripts;
749
+					}
750
+					break;
751
+				default:
752
+					$response_array = [
753
+						'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
754
+						'records_migrated'   => $currently_executing_script->count_records_migrated(),
755
+						'status'             => $currently_executing_script->get_status(),
756
+						'message'            => sprintf(
757
+							esc_html__("Minor errors occurred during %s: %s", "event_espresso"),
758
+							$currently_executing_script->pretty_name(),
759
+							implode(", ", $currently_executing_script->get_errors())
760
+						),
761
+						'script'             => $currently_executing_script->pretty_name(),
762
+					];
763
+					break;
764
+			}
765
+		} catch (Exception $e) {
766
+			// ok so some exception was thrown which killed the data migration script
767
+			// double-check we have a real script
768
+			if ($currently_executing_script instanceof EE_Data_Migration_Script_Base) {
769
+				$script_name = $currently_executing_script->pretty_name();
770
+				$currently_executing_script->set_broken();
771
+				$currently_executing_script->add_error($e->getMessage());
772
+			} else {
773
+				$script_name = esc_html__("Error getting Migration Script", "event_espresso");
774
+			}
775
+			$response_array = [
776
+				'records_to_migrate' => 1,
777
+				'records_migrated'   => 0,
778
+				'status'             => self::status_fatal_error,
779
+				'message'            => sprintf(
780
+					esc_html__("A fatal error occurred during the migration: %s", "event_espresso"),
781
+					$e->getMessage()
782
+				),
783
+				'script'             => $script_name,
784
+			];
785
+		}
786
+		$successful_save = $this->_save_migrations_ran();
787
+		if ($successful_save !== true) {
788
+			// ok so the current wp option didn't save. that's tricky, because we'd like to update it
789
+			// and mark it as having a fatal error, but remember- WE CAN'T SAVE THIS WP OPTION!
790
+			// however, if we throw an exception, and return that, then the next request
791
+			// won't have as much info in it, and it may be able to save
792
+			throw new EE_Error(
793
+				sprintf(
794
+					esc_html__(
795
+						"The error '%s' occurred updating the status of the migration. This is a FATAL ERROR, but the error is preventing the system from remembering that. Please contact event espresso support.",
796
+						"event_espresso"
797
+					),
798
+					$successful_save
799
+				)
800
+			);
801
+		}
802
+		// if we're all done, initialize EE plugins' default data etc.
803
+		if ($init_dbs) {
804
+			$this->initialize_db_for_enqueued_ee_plugins();
805
+		}
806
+		return $response_array;
807
+	}
808
+
809
+
810
+	/**
811
+	 * Echo out JSON response to migration script AJAX requests. Takes precautions
812
+	 * to buffer output so that we don't throw junk into our json.
813
+	 *
814
+	 * @return array with keys:
815
+	 * 'records_to_migrate' which counts ALL the records for the current migration, and should remain constant. (ie,
816
+	 * it's NOT the count of hwo many remain)
817
+	 * 'records_migrated' which also counts ALL the records which have been migrated (ie, percent_complete =
818
+	 * records_migrated/records_to_migrate)
819
+	 * 'status'=>a string, one of EE_Data_migration_Manager::status_*
820
+	 * 'message'=>a string, containing any message you want to show to the user. We may decide to split this up into
821
+	 * errors, notifications, and successes
822
+	 * 'script'=>a pretty name of the script currently running
823
+	 */
824
+	public function response_to_migration_ajax_request()
825
+	{
826
+		ob_start();
827
+		try {
828
+			$response = $this->migration_step();
829
+		} catch (Exception $e) {
830
+			$response = [
831
+				'records_to_migrate' => 0,
832
+				'records_migrated'   => 0,
833
+				'status'             => EE_Data_Migration_Manager::status_fatal_error,
834
+				'message'            => sprintf(
835
+					esc_html__("Unknown fatal error occurred: %s", "event_espresso"),
836
+					$e->getMessage()
837
+				),
838
+				'script'             => 'Unknown',
839
+			];
840
+			$this->add_error_to_migrations_ran($e->getMessage() . "; Stack trace:" . $e->getTraceAsString());
841
+		}
842
+		$warnings_etc = @ob_get_contents();
843
+		ob_end_clean();
844
+		$response['message'] .= $warnings_etc;
845
+		return $response;
846
+	}
847
+
848
+
849
+	/**
850
+	 * Updates the WordPress option that keeps track of which EE version the database
851
+	 * is at (ie, the code may be at 4.1.0, but the database is still at 3.1.35)
852
+	 *
853
+	 * @param array $slug_and_version {
854
+	 * @type string $slug             like 'Core' or 'Calendar',
855
+	 * @type string $version          like '4.1.0'
856
+	 *                                }
857
+	 * @return void
858
+	 */
859
+	public function update_current_database_state_to($slug_and_version = null)
860
+	{
861
+		if (! $slug_and_version) {
862
+			// no version was provided, assume it should be at the current code version
863
+			$slug_and_version = ['slug' => 'Core', 'version' => espresso_version()];
864
+		}
865
+		$current_database_state                              = get_option(self::current_database_state);
866
+		$current_database_state[ $slug_and_version['slug'] ] = $slug_and_version['version'];
867
+		update_option(self::current_database_state, $current_database_state);
868
+	}
869
+
870
+
871
+	/**
872
+	 * Determines if the database is currently at a state matching what's indicated in $slug and $version.
873
+	 *
874
+	 * @param array $slug_and_version {
875
+	 * @type string $slug             like 'Core' or 'Calendar',
876
+	 * @type string $version          like '4.1.0'
877
+	 *                                }
878
+	 * @return boolean
879
+	 */
880
+	public function database_needs_updating_to($slug_and_version)
881
+	{
882
+
883
+		$slug                   = $slug_and_version['slug'];
884
+		$version                = $slug_and_version['version'];
885
+		$current_database_state = get_option(self::current_database_state);
886
+		if (! isset($current_database_state[ $slug ])) {
887
+			return true;
888
+		} else {
889
+			// just compare the first 3 parts of version string, eg "4.7.1", not "4.7.1.dev.032" because DBs shouldn't change on nano version changes
890
+			$version_parts_current_db_state     = array_slice(explode('.', $current_database_state[ $slug ]), 0, 3);
891
+			$version_parts_of_provided_db_state = array_slice(explode('.', $version), 0, 3);
892
+			$needs_updating                     = false;
893
+			foreach ($version_parts_current_db_state as $offset => $version_part_in_current_db_state) {
894
+				if ($version_part_in_current_db_state < $version_parts_of_provided_db_state[ $offset ]) {
895
+					$needs_updating = true;
896
+					break;
897
+				}
898
+			}
899
+			return $needs_updating;
900
+		}
901
+	}
902
+
903
+
904
+	/**
905
+	 * Gets all the data migration scripts available in the core folder and folders
906
+	 * in addons. Has the side effect of adding them for autoloading
907
+	 *
908
+	 * @return array keys are expected classnames, values are their filepaths
909
+	 * @throws InvalidInterfaceException
910
+	 * @throws InvalidDataTypeException
911
+	 * @throws EE_Error
912
+	 * @throws InvalidArgumentException
913
+	 */
914
+	public function get_all_data_migration_scripts_available()
915
+	{
916
+		if (! $this->_data_migration_class_to_filepath_map) {
917
+			$this->_data_migration_class_to_filepath_map = [];
918
+			foreach ($this->get_data_migration_script_folders() as $eeAddonClass => $folder_path) {
919
+				// strip any placeholders added to classname to make it a unique array key
920
+				$eeAddonClass = trim($eeAddonClass, '*');
921
+				$eeAddonClass = $eeAddonClass === 'Core' || class_exists($eeAddonClass)
922
+					? $eeAddonClass
923
+					: '';
924
+				$folder_path  = EEH_File::end_with_directory_separator($folder_path);
925
+				$files        = glob($folder_path . '*.dms.php');
926
+				if (empty($files)) {
927
+					continue;
928
+				}
929
+				foreach ($files as $file) {
930
+					$pos_of_last_slash = strrpos($file, '/');
931
+					$classname         = str_replace('.dms.php', '', substr($file, $pos_of_last_slash + 1));
932
+					$migrates_to       = $this->script_migrates_to_version($classname, $eeAddonClass);
933
+					$slug              = $migrates_to['slug'];
934
+					// check that the slug as contained in the DMS is associated with
935
+					// the slug of an addon or core
936
+					if ($slug !== 'Core' && EE_Registry::instance()->get_addon_by_name($slug) === null) {
937
+						EE_Error::doing_it_wrong(
938
+							__FUNCTION__,
939
+							sprintf(
940
+								esc_html__(
941
+									'The data migration script "%s" migrates the "%s" data, but there is no EE addon with that name. There is only: %s. ',
942
+									'event_espresso'
943
+								),
944
+								$classname,
945
+								$slug,
946
+								implode(', ', array_keys(EE_Registry::instance()->get_addons_by_name()))
947
+							),
948
+							'4.3.0.alpha.019'
949
+						);
950
+					}
951
+					$this->_data_migration_class_to_filepath_map[ $classname ] = $file;
952
+				}
953
+			}
954
+			EEH_Autoloader::register_autoloader($this->_data_migration_class_to_filepath_map);
955
+		}
956
+		return $this->_data_migration_class_to_filepath_map;
957
+	}
958
+
959
+
960
+	/**
961
+	 * Once we have an addon that works with EE4.1, we will actually want to fetch the PUE slugs
962
+	 * from each addon, and check if they need updating,
963
+	 *
964
+	 * @return boolean
965
+	 */
966
+	public function addons_need_updating()
967
+	{
968
+		return false;
969
+	}
970
+
971
+
972
+	/**
973
+	 * Adds this error string to the data_migrations_ran array, but we don't necessarily know
974
+	 * where to put it, so we just throw it in there... better than nothing...
975
+	 *
976
+	 * @param string $error_message
977
+	 */
978
+	public function add_error_to_migrations_ran($error_message)
979
+	{
980
+		// get last-run migration script
981
+		global $wpdb;
982
+		$last_migration_script_option = $wpdb->get_row(
983
+			"SELECT * FROM $wpdb->options WHERE option_name like '"
984
+			. EE_Data_Migration_Manager::data_migration_script_option_prefix
985
+			. "%' ORDER BY option_id DESC LIMIT 1",
986
+			ARRAY_A
987
+		);
988
+
989
+		$last_ran_migration_script_properties = isset($last_migration_script_option['option_value'])
990
+			? maybe_unserialize($last_migration_script_option['option_value']) : null;
991
+		// now, tread lightly because we're here because a FATAL non-catchable error
992
+		// was thrown last time when we were trying to run a data migration script
993
+		// so the fatal error could have happened while getting the migration script
994
+		// or doing running it...
995
+		$versions_migrated_to = isset($last_migration_script_option['option_name']) ? str_replace(
996
+			EE_Data_Migration_Manager::data_migration_script_option_prefix,
997
+			"",
998
+			$last_migration_script_option['option_name']
999
+		) : null;
1000
+
1001
+		// check if it THINKS it's a data migration script and especially if it's one that HASN'T finished yet
1002
+		// because if it has finished, then it obviously couldn't be the cause of this error, right? (because it's all done)
1003
+		if (
1004
+			isset($last_ran_migration_script_properties['class'])
1005
+			&& isset($last_ran_migration_script_properties['_status'])
1006
+			&& $last_ran_migration_script_properties['_status'] != self::status_completed
1007
+		) {
1008
+			// ok then just add this error to its list of errors
1009
+			$last_ran_migration_script_properties['_errors'][] = $error_message;
1010
+			$last_ran_migration_script_properties['_status']   = self::status_fatal_error;
1011
+		} else {
1012
+			// so we don't even know which script was last running
1013
+			// use the data migration error stub, which is designed specifically for this type of thing
1014
+			$general_migration_error = new EE_DMS_Unknown_1_0_0();
1015
+			$general_migration_error->add_error($error_message);
1016
+			$general_migration_error->set_broken();
1017
+			$last_ran_migration_script_properties = $general_migration_error->properties_as_array();
1018
+			$versions_migrated_to                 = 'Unknown.1.0.0';
1019
+			// now just to make sure appears as last (in case the were previously a fatal error like this)
1020
+			// delete the old one
1021
+			delete_option(self::data_migration_script_option_prefix . $versions_migrated_to);
1022
+		}
1023
+		update_option(
1024
+			self::data_migration_script_option_prefix . $versions_migrated_to,
1025
+			$last_ran_migration_script_properties
1026
+		);
1027
+	}
1028
+
1029
+
1030
+	/**
1031
+	 * saves what data migrations have run to the database
1032
+	 *
1033
+	 * @return bool|string TRUE if successfully saved migrations ran, string if an error occurred
1034
+	 * @throws EE_Error
1035
+	 */
1036
+	protected function _save_migrations_ran()
1037
+	{
1038
+		if ($this->_data_migrations_ran == null) {
1039
+			$this->get_data_migrations_ran();
1040
+		}
1041
+		// now, we don't want to save actual classes to the DB because that's messy
1042
+		$successful_updates = true;
1043
+		foreach ($this->_data_migrations_ran as $plugin_slug => $migrations_ran_for_plugin) {
1044
+			foreach ($migrations_ran_for_plugin as $version_string => $array_or_migration_obj) {
1045
+				$plugin_slug_for_use_in_option_name = $plugin_slug . ".";
1046
+				$option_name                        =
1047
+					self::data_migration_script_option_prefix . $plugin_slug_for_use_in_option_name . $version_string;
1048
+				$old_option_value                   = get_option($option_name);
1049
+				if ($array_or_migration_obj instanceof EE_Data_Migration_Script_Base) {
1050
+					$script_array_for_saving = $array_or_migration_obj->properties_as_array();
1051
+					if ($old_option_value != $script_array_for_saving) {
1052
+						$successful_updates = update_option($option_name, $script_array_for_saving);
1053
+					}
1054
+				} else {// we don't know what this array-thing is. So just save it as-is
1055
+					if ($old_option_value != $array_or_migration_obj) {
1056
+						$successful_updates = update_option($option_name, $array_or_migration_obj);
1057
+					}
1058
+				}
1059
+				if (! $successful_updates) {
1060
+					global $wpdb;
1061
+					return $wpdb->last_error;
1062
+				}
1063
+			}
1064
+		}
1065
+		return true;
1066
+		// $updated = update_option(self::data_migrations_option_name, $array_of_migrations);
1067
+		// if ($updated !== true) {
1068
+		//     global $wpdb;
1069
+		//     return $wpdb->last_error;
1070
+		// } else {
1071
+		//     return true;
1072
+		// }
1073
+		// wp_mail(
1074
+		//     "[email protected]",
1075
+		//     time() . " price debug info",
1076
+		//     "updated: $updated, last error: $last_error, byte length of option: " . strlen(
1077
+		//         serialize($array_of_migrations)
1078
+		//     )
1079
+		// );
1080
+	}
1081
+
1082
+
1083
+	/**
1084
+	 * Takes an array of data migration script properties and re-creates the class from
1085
+	 * them. The argument $properties_array is assumed to have been made by
1086
+	 * EE_Data_Migration_Script_Base::properties_as_array()
1087
+	 *
1088
+	 * @param array $properties_array
1089
+	 * @return EE_Data_Migration_Script_Base
1090
+	 * @throws EE_Error
1091
+	 */
1092
+	public function _instantiate_script_from_properties_array($properties_array)
1093
+	{
1094
+		if (! isset($properties_array['class'])) {
1095
+			throw new EE_Error(
1096
+				sprintf(
1097
+					esc_html__("Properties array  has no 'class' properties. Here's what it has: %s", "event_espresso"),
1098
+					implode(",", $properties_array)
1099
+				)
1100
+			);
1101
+		}
1102
+		$class_name = $properties_array['class'];
1103
+		if (! class_exists($class_name)) {
1104
+			throw new EE_Error(sprintf(
1105
+				esc_html__("There is no migration script named %s", "event_espresso"),
1106
+				$class_name
1107
+			));
1108
+		}
1109
+		$class = new $class_name();
1110
+		if (! $class instanceof EE_Data_Migration_Script_Base) {
1111
+			throw new EE_Error(
1112
+				sprintf(
1113
+					esc_html__(
1114
+						"Class '%s' is supposed to be a migration script. Its not, its a '%s'",
1115
+						"event_espresso"
1116
+					),
1117
+					$class_name,
1118
+					get_class($class)
1119
+				)
1120
+			);
1121
+		}
1122
+		$class->instantiate_from_array_of_properties($properties_array);
1123
+		return $class;
1124
+	}
1125
+
1126
+
1127
+	/**
1128
+	 * Gets the classname for the most up-to-date DMS (ie, the one that will finally
1129
+	 * leave the DB in a state usable by the current plugin code).
1130
+	 *
1131
+	 * @param string $plugin_slug the slug for the ee plugin we are searching for. Default is 'Core'
1132
+	 * @return string
1133
+	 * @throws EE_Error
1134
+	 * @throws EE_Error
1135
+	 */
1136
+	public function get_most_up_to_date_dms($plugin_slug = 'Core')
1137
+	{
1138
+		$class_to_filepath_map         = $this->get_all_data_migration_scripts_available();
1139
+		$most_up_to_date_dms_classname = null;
1140
+		foreach ($class_to_filepath_map as $classname => $filepath) {
1141
+			if ($most_up_to_date_dms_classname === null) {
1142
+				$migrates_to      = $this->script_migrates_to_version($classname);
1143
+				$this_plugin_slug = $migrates_to['slug'];
1144
+				if ($this_plugin_slug == $plugin_slug) {
1145
+					// if it's for core, it wins
1146
+					$most_up_to_date_dms_classname = $classname;
1147
+				}
1148
+				// if it wasn't for core, we must keep searching for one that is!
1149
+				continue;
1150
+			}
1151
+			$champion_migrates_to  = $this->script_migrates_to_version($most_up_to_date_dms_classname);
1152
+			$contender_migrates_to = $this->script_migrates_to_version($classname);
1153
+			if (
1154
+				$contender_migrates_to['slug'] == $plugin_slug
1155
+				&& version_compare(
1156
+					$champion_migrates_to['version'],
1157
+					$contender_migrates_to['version'],
1158
+					'<'
1159
+				)
1160
+			) {
1161
+				// so the contenders version is higher, and it's for Core
1162
+				$most_up_to_date_dms_classname = $classname;
1163
+			}
1164
+		}
1165
+		return $most_up_to_date_dms_classname;
1166
+	}
1167
+
1168
+
1169
+	/**
1170
+	 * Gets the migration script specified but ONLY if it has already run.
1171
+	 *
1172
+	 * Eg, if you wanted to see if 'EE_DMS_Core_4_1_0' has run, you would run the following code:
1173
+	 * <code> $core_4_1_0_dms_ran = EE_Data_Migration_Manager::instance()->get_migration_ran( '4.1.0', 'Core' ) !==
1174
+	 * NULL;</code> This is especially useful in addons' data migration scripts, this way they can tell if a core (or
1175
+	 * other addon) DMS has run, in case the current DMS depends on it.
1176
+	 *
1177
+	 * @param string $version     the version the DMS searched for migrates to. Usually just the content before the 3rd
1178
+	 *                            period. Eg '4.1.0'
1179
+	 * @param string $plugin_slug like 'Core', 'Mailchimp', 'Calendar', etc
1180
+	 * @return EE_Data_Migration_Script_Base
1181
+	 * @throws EE_Error
1182
+	 */
1183
+	public function get_migration_ran($version, $plugin_slug = 'Core')
1184
+	{
1185
+		$migrations_ran = $this->get_data_migrations_ran();
1186
+		if (isset($migrations_ran[ $plugin_slug ]) && isset($migrations_ran[ $plugin_slug ][ $version ])) {
1187
+			return $migrations_ran[ $plugin_slug ][ $version ];
1188
+		} else {
1189
+			return null;
1190
+		}
1191
+	}
1192
+
1193
+
1194
+	/**
1195
+	 * Resets the borked data migration scripts, so they're no longer borked, and we can again attempt to migrate
1196
+	 *
1197
+	 * @return bool
1198
+	 * @throws EE_Error
1199
+	 */
1200
+	public function reattempt()
1201
+	{
1202
+		// find if the last-run script was borked
1203
+		// set it as being non-borked (we shouldn't ever get DMSs that we don't recognize)
1204
+		// add an 'error' saying that we attempted to reset
1205
+		// does it have a stage that was borked too? if so make it no longer borked
1206
+		// add an 'error' saying we attempted to reset
1207
+		$last_ran_script = $this->get_last_ran_script();
1208
+		if ($last_ran_script instanceof EE_DMS_Unknown_1_0_0) {
1209
+			// if it was an error DMS, just mark it as complete (if another error occurs it will overwrite it)
1210
+			$last_ran_script->set_completed();
1211
+		} elseif ($last_ran_script instanceof EE_Data_Migration_Script_Base) {
1212
+			$last_ran_script->reattempt();
1213
+		} else {
1214
+			throw new EE_Error(
1215
+				sprintf(
1216
+					esc_html__(
1217
+						'Unable to reattempt the last ran migration script because it was not a valid migration script. || It was %s',
1218
+						'event_espresso'
1219
+					),
1220
+					print_r($last_ran_script, true)
1221
+				)
1222
+			);
1223
+		}
1224
+		return $this->_save_migrations_ran();
1225
+	}
1226
+
1227
+
1228
+	/**
1229
+	 * Gets whether this particular migration has run or not
1230
+	 *
1231
+	 * @param string $version     the version the DMS searched for migrates to. Usually just the content before the 3rd
1232
+	 *                            period. Eg '4.1.0'
1233
+	 * @param string $plugin_slug like 'Core', 'Mailchimp', 'Calendar', etc
1234
+	 * @return boolean
1235
+	 * @throws EE_Error
1236
+	 */
1237
+	public function migration_has_ran($version, $plugin_slug = 'Core')
1238
+	{
1239
+		return $this->get_migration_ran($version, $plugin_slug) !== null;
1240
+	}
1241
+
1242
+
1243
+	/**
1244
+	 * Enqueues this ee plugin to have its data initialized
1245
+	 *
1246
+	 * @param string $plugin_slug either 'Core' or EE_Addon::name()'s return value
1247
+	 */
1248
+	public function enqueue_db_initialization_for($plugin_slug)
1249
+	{
1250
+		$queue = $this->get_db_initialization_queue();
1251
+		if (! in_array($plugin_slug, $queue)) {
1252
+			$queue[] = $plugin_slug;
1253
+		}
1254
+		update_option(self::db_init_queue_option_name, $queue);
1255
+	}
1256
+
1257
+
1258
+	/**
1259
+	 * Calls EE_Addon::initialize_db_if_no_migrations_required() on each addon
1260
+	 * specified in EE_Data_Migration_Manager::get_db_init_queue(), and if 'Core' is
1261
+	 * in the queue, calls EE_System::initialize_db_if_no_migrations_required().
1262
+	 *
1263
+	 * @throws EE_Error
1264
+	 */
1265
+	public function initialize_db_for_enqueued_ee_plugins()
1266
+	{
1267
+		$queue = $this->get_db_initialization_queue();
1268
+		foreach ($queue as $plugin_slug) {
1269
+			$most_up_to_date_dms = $this->get_most_up_to_date_dms($plugin_slug);
1270
+			if (! $most_up_to_date_dms) {
1271
+				// if there is NO DMS for this plugin, obviously there's no schema to verify anyways
1272
+				$verify_db = false;
1273
+			} else {
1274
+				$most_up_to_date_dms_migrates_to = $this->script_migrates_to_version($most_up_to_date_dms);
1275
+				$verify_db                       = $this->database_needs_updating_to($most_up_to_date_dms_migrates_to);
1276
+			}
1277
+			if ($plugin_slug == 'Core') {
1278
+				EE_System::instance()->initialize_db_if_no_migrations_required(
1279
+					false,
1280
+					$verify_db
1281
+				);
1282
+			} else {
1283
+				// just loop through the addons to make sure their database is set up
1284
+				foreach (EE_Registry::instance()->addons as $addon) {
1285
+					if ($addon->name() == $plugin_slug) {
1286
+						$addon->initialize_db_if_no_migrations_required($verify_db);
1287
+						break;
1288
+					}
1289
+				}
1290
+			}
1291
+		}
1292
+		// because we just initialized the DBs for the enqueued ee plugins
1293
+		// we don't need to keep remembering which ones needed to be initialized
1294
+		delete_option(self::db_init_queue_option_name);
1295
+	}
1296
+
1297
+
1298
+	/**
1299
+	 * Gets a numerically-indexed array of plugin slugs that need to have their databases
1300
+	 * (re-)initialized after migrations are complete. ie, each element should be either
1301
+	 * 'Core', or the return value of EE_Addon::name() for an addon
1302
+	 *
1303
+	 * @return array
1304
+	 */
1305
+	public function get_db_initialization_queue()
1306
+	{
1307
+		return get_option(self::db_init_queue_option_name, []);
1308
+	}
1309
+
1310
+
1311
+	/**
1312
+	 * Gets the injected table analyzer, or throws an exception
1313
+	 *
1314
+	 * @return TableAnalysis
1315
+	 * @throws EE_Error
1316
+	 */
1317
+	protected function _get_table_analysis()
1318
+	{
1319
+		if ($this->_table_analysis instanceof TableAnalysis) {
1320
+			return $this->_table_analysis;
1321
+		} else {
1322
+			throw new EE_Error(
1323
+				sprintf(
1324
+					esc_html__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
1325
+					get_class($this)
1326
+				)
1327
+			);
1328
+		}
1329
+	}
1330
+
1331
+
1332
+	/**
1333
+	 * Gets the injected table manager, or throws an exception
1334
+	 *
1335
+	 * @return TableManager
1336
+	 * @throws EE_Error
1337
+	 */
1338
+	protected function _get_table_manager()
1339
+	{
1340
+		if ($this->_table_manager instanceof TableManager) {
1341
+			return $this->_table_manager;
1342
+		} else {
1343
+			throw new EE_Error(
1344
+				sprintf(
1345
+					esc_html__('Table manager class on class %1$s is not set properly.', 'event_espresso'),
1346
+					get_class($this)
1347
+				)
1348
+			);
1349
+		}
1350
+	}
1351 1351
 }
Please login to merge, or discard this patch.
Spacing   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
     public static function instance()
164 164
     {
165 165
         // check if class object is instantiated
166
-        if (! self::$_instance instanceof EE_Data_Migration_Manager) {
166
+        if ( ! self::$_instance instanceof EE_Data_Migration_Manager) {
167 167
             self::$_instance = new self();
168 168
         }
169 169
         return self::$_instance;
@@ -189,11 +189,11 @@  discard block
 block discarded – undo
189 189
      */
190 190
     private function __construct()
191 191
     {
192
-        $this->stati_that_indicate_to_continue_migrations              = [
192
+        $this->stati_that_indicate_to_continue_migrations = [
193 193
             self::status_continue,
194 194
             self::status_completed,
195 195
         ];
196
-        $this->stati_that_indicate_to_stop_migrations                  = [
196
+        $this->stati_that_indicate_to_stop_migrations = [
197 197
             self::status_fatal_error,
198 198
             self::status_no_more_migration_scripts,
199 199
         ];
@@ -241,12 +241,12 @@  discard block
 block discarded – undo
241 241
 
242 242
         if (count($parts) == 4) {
243 243
             // it's 4.2-style.eg Core.4.1.0
244
-            $plugin_slug    = $parts[0];                                     // eg Core
245
-            $version_string = $parts[1] . "." . $parts[2] . "." . $parts[3]; // eg 4.1.0
244
+            $plugin_slug    = $parts[0]; // eg Core
245
+            $version_string = $parts[1].".".$parts[2].".".$parts[3]; // eg 4.1.0
246 246
         } else {
247 247
             // it's 4.1-style: eg 4.1.0
248 248
             $plugin_slug    = 'Core';
249
-            $version_string = $plugin_slug_and_version_string;// eg 4.1.0
249
+            $version_string = $plugin_slug_and_version_string; // eg 4.1.0
250 250
         }
251 251
         return [$plugin_slug, $version_string];
252 252
     }
@@ -308,11 +308,11 @@  discard block
 block discarded – undo
308 308
      */
309 309
     public function get_data_migrations_ran()
310 310
     {
311
-        if (! $this->_data_migrations_ran) {
311
+        if ( ! $this->_data_migrations_ran) {
312 312
             // setup autoloaders for each of the scripts in there
313 313
             $this->get_all_data_migration_scripts_available();
314 314
             $data_migrations_options =
315
-                $this->get_all_migration_script_options();// get_option(EE_Data_Migration_Manager::data_migrations_option_name,get_option('espresso_data_migrations',array()));
315
+                $this->get_all_migration_script_options(); // get_option(EE_Data_Migration_Manager::data_migrations_option_name,get_option('espresso_data_migrations',array()));
316 316
 
317 317
             $data_migrations_ran = [];
318 318
             // convert into data migration script classes where possible
@@ -322,27 +322,27 @@  discard block
 block discarded – undo
322 322
                 );
323 323
 
324 324
                 try {
325
-                    $class                                                  = $this->_get_dms_class_from_wp_option(
325
+                    $class = $this->_get_dms_class_from_wp_option(
326 326
                         $data_migration_option['option_name'],
327 327
                         $data_migration_option['option_value']
328 328
                     );
329
-                    $data_migrations_ran[ $plugin_slug ][ $version_string ] = $class;
329
+                    $data_migrations_ran[$plugin_slug][$version_string] = $class;
330 330
                     // ok so far THIS is the 'last-run-script'... unless we find another on next iteration
331 331
                     $this->_last_ran_script = $class;
332
-                    if (! $class->is_completed()) {
332
+                    if ( ! $class->is_completed()) {
333 333
                         // sometimes we also like to know which was the last incomplete script (or if there are any at all)
334 334
                         $this->_last_ran_incomplete_script = $class;
335 335
                     }
336 336
                 } catch (EE_Error $e) {
337 337
                     // ok so it's not a DMS. We'll just keep it, although other code will need to expect non-DMSs
338
-                    $data_migrations_ran[ $plugin_slug ][ $version_string ] = maybe_unserialize(
338
+                    $data_migrations_ran[$plugin_slug][$version_string] = maybe_unserialize(
339 339
                         $data_migration_option['option_value']
340 340
                     );
341 341
                 }
342 342
             }
343 343
             // so here the array of $data_migrations_ran is actually a mix of classes and a few legacy arrays
344 344
             $this->_data_migrations_ran = $data_migrations_ran;
345
-            if (! $this->_data_migrations_ran || ! is_array($this->_data_migrations_ran)) {
345
+            if ( ! $this->_data_migrations_ran || ! is_array($this->_data_migrations_ran)) {
346 346
                 $this->_data_migrations_ran = [];
347 347
             }
348 348
         }
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
      */
363 363
     public function get_mapping_new_pk($script_name, $old_table, $old_pk, $new_table)
364 364
     {
365
-        $script  = EE_Registry::instance()->load_dms($script_name);
365
+        $script = EE_Registry::instance()->load_dms($script_name);
366 366
         return $script->get_mapping_new_pk($old_table, $old_pk, $new_table);
367 367
     }
368 368
 
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
     {
396 396
         return apply_filters(
397 397
             'FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',
398
-            ['Core' => EE_CORE . 'data_migration_scripts']
398
+            ['Core' => EE_CORE.'data_migration_scripts']
399 399
         );
400 400
     }
401 401
 
@@ -412,11 +412,11 @@  discard block
 block discarded – undo
412 412
      */
413 413
     public function script_migrates_to_version($migration_script_name, $eeAddonClass = '')
414 414
     {
415
-        if (isset($this->script_migration_versions[ $migration_script_name ])) {
416
-            return $this->script_migration_versions[ $migration_script_name ];
415
+        if (isset($this->script_migration_versions[$migration_script_name])) {
416
+            return $this->script_migration_versions[$migration_script_name];
417 417
         }
418 418
         $dms_info                                                  = $this->parse_dms_classname($migration_script_name);
419
-        $this->script_migration_versions[ $migration_script_name ] = [
419
+        $this->script_migration_versions[$migration_script_name] = [
420 420
             'slug'    => $eeAddonClass !== '' ? $eeAddonClass : $dms_info['slug'],
421 421
             'version' => $dms_info['major_version']
422 422
                          . "."
@@ -424,7 +424,7 @@  discard block
 block discarded – undo
424 424
                          . "."
425 425
                          . $dms_info['micro_version'],
426 426
         ];
427
-        return $this->script_migration_versions[ $migration_script_name ];
427
+        return $this->script_migration_versions[$migration_script_name];
428 428
     }
429 429
 
430 430
 
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
     {
440 440
         $matches = [];
441 441
         preg_match('~EE_DMS_(.*)_([0-9]*)_([0-9]*)_([0-9]*)~', $classname, $matches);
442
-        if (! $matches || ! (isset($matches[1]) && isset($matches[2]) && isset($matches[3]))) {
442
+        if ( ! $matches || ! (isset($matches[1]) && isset($matches[2]) && isset($matches[3]))) {
443 443
             throw new EE_Error(
444 444
                 sprintf(
445 445
                     esc_html__(
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
     {
472 472
         $espresso_db_core_updates = get_option('espresso_db_update', []);
473 473
         $db_state                 = get_option(EE_Data_Migration_Manager::current_database_state);
474
-        if (! $db_state) {
474
+        if ( ! $db_state) {
475 475
             // mark the DB as being in the state as the last version in there.
476 476
             // this is done to trigger maintenance mode and do data migration scripts
477 477
             // if the admin installed this version of EE over 3.1.x or 4.0.x
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
         // in 4.1, $db_state would have only been a simple string like '4.1.0',
491 491
         // but in 4.2+ it should be an array with at least key 'Core' and the value of that plugin's
492 492
         // db, and possibly other keys for other addons like 'Calendar','Permissions',etc
493
-        if (! is_array($db_state)) {
493
+        if ( ! is_array($db_state)) {
494 494
             $db_state = ['Core' => $db_state];
495 495
             update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
496 496
         }
@@ -534,7 +534,7 @@  discard block
 block discarded – undo
534 534
                 // check if this version script is DONE or not; or if it's never been run
535 535
                 if (
536 536
                     ! $scripts_ran
537
-                    || ! isset($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ])
537
+                    || ! isset($scripts_ran[$script_converts_plugin_slug][$script_converts_to_version])
538 538
                 ) {
539 539
                     // we haven't run this conversion script before
540 540
                     // now check if it applies...
@@ -545,28 +545,28 @@  discard block
 block discarded – undo
545 545
                     /* @var $script EE_Data_Migration_Script_Base */
546 546
                     $can_migrate = $script->can_migrate_from_version($theoretical_database_state);
547 547
                     if ($can_migrate) {
548
-                        $script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
548
+                        $script_classes_that_should_run_per_iteration[$iteration][$script->priority()][] = $script;
549 549
                         $migrates_to_version                                                                 =
550 550
                             $script->migrates_to_version();
551
-                        $next_database_state_to_consider[ $migrates_to_version['slug'] ]                     =
551
+                        $next_database_state_to_consider[$migrates_to_version['slug']]                     =
552 552
                             $migrates_to_version['version'];
553
-                        unset($script_class_and_filepaths_available[ $classname ]);
553
+                        unset($script_class_and_filepaths_available[$classname]);
554 554
                     }
555 555
                 } elseif (
556
-                    $scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ]
556
+                    $scripts_ran[$script_converts_plugin_slug][$script_converts_to_version]
557 557
                           instanceof
558 558
                           EE_Data_Migration_Script_Base
559 559
                 ) {
560 560
                     // this script has been run, or at least started
561
-                    $script = $scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ];
561
+                    $script = $scripts_ran[$script_converts_plugin_slug][$script_converts_to_version];
562 562
                     if ($script->get_status() !== self::status_completed) {
563 563
                         // this script is already underway... keep going with it
564
-                        $script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
564
+                        $script_classes_that_should_run_per_iteration[$iteration][$script->priority()][] = $script;
565 565
                         $migrates_to_version                                                                 =
566 566
                             $script->migrates_to_version();
567
-                        $next_database_state_to_consider[ $migrates_to_version['slug'] ]                     =
567
+                        $next_database_state_to_consider[$migrates_to_version['slug']]                     =
568 568
                             $migrates_to_version['version'];
569
-                        unset($script_class_and_filepaths_available[ $classname ]);
569
+                        unset($script_class_and_filepaths_available[$classname]);
570 570
                     }
571 571
                     // else it must have a status that indicates it has finished,
572 572
                     // so we don't want to try and run it again
@@ -575,14 +575,14 @@  discard block
 block discarded – undo
575 575
                 // or was simply removed from EE? either way, it's certainly not runnable!
576 576
             }
577 577
             $iteration++;
578
-        } while ($next_database_state_to_consider !== $theoretical_database_state && $iteration < 6);
578
+        }while ($next_database_state_to_consider !== $theoretical_database_state && $iteration < 6);
579 579
         // ok we have all the scripts that should run, now let's make them into flat array
580 580
         $scripts_that_should_run = [];
581 581
         foreach ($script_classes_that_should_run_per_iteration as $scripts_at_priority) {
582 582
             ksort($scripts_at_priority);
583 583
             foreach ($scripts_at_priority as $scripts) {
584 584
                 foreach ($scripts as $script) {
585
-                    $scripts_that_should_run[ get_class($script) ] = $script;
585
+                    $scripts_that_should_run[get_class($script)] = $script;
586 586
                 }
587 587
             }
588 588
         }
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
     public function get_last_ran_script($include_completed_scripts = false)
609 609
     {
610 610
         // make sure we've set up the class properties _last_ran_script and _last_ran_incomplete_script
611
-        if (! $this->_data_migrations_ran) {
611
+        if ( ! $this->_data_migrations_ran) {
612 612
             $this->get_data_migrations_ran();
613 613
         }
614 614
         if ($include_completed_scripts) {
@@ -645,10 +645,10 @@  discard block
 block discarded – undo
645 645
 
646 646
         try {
647 647
             $currently_executing_script = $this->get_last_ran_script();
648
-            if (! $currently_executing_script) {
648
+            if ( ! $currently_executing_script) {
649 649
                 // Find the next script that needs to execute
650 650
                 $scripts = $this->check_for_applicable_data_migration_scripts();
651
-                if (! $scripts) {
651
+                if ( ! $scripts) {
652 652
                     // huh, no more scripts to run... apparently we're done!
653 653
                     // but don't forget to make sure initial data is there
654 654
                     // we should be good to allow them to exit maintenance mode now
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
                     $this->script_migrates_to_version(get_class($currently_executing_script));
677 677
                 $plugin_slug                                            = $migrates_to['slug'];
678 678
                 $version                                                = $migrates_to['version'];
679
-                $this->_data_migrations_ran[ $plugin_slug ][ $version ] = $currently_executing_script;
679
+                $this->_data_migrations_ran[$plugin_slug][$version] = $currently_executing_script;
680 680
             }
681 681
             $current_script_name = get_class($currently_executing_script);
682 682
         } catch (Exception $e) {
@@ -684,7 +684,7 @@  discard block
 block discarded – undo
684 684
 
685 685
             $message = sprintf(
686 686
                 esc_html__("Error Message: %sStack Trace:%s", "event_espresso"),
687
-                $e->getMessage() . '<br>',
687
+                $e->getMessage().'<br>',
688 688
                 $e->getTraceAsString()
689 689
             );
690 690
             // record it on the array of data migration scripts run. This will be overwritten next time we try and try to run data migrations
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
                     ];
738 738
                     // check if there are any more after this one.
739 739
                     $scripts_remaining = $this->check_for_applicable_data_migration_scripts();
740
-                    if (! $scripts_remaining) {
740
+                    if ( ! $scripts_remaining) {
741 741
                         // we should be good to allow them to exit maintenance mode now
742 742
                         EE_Maintenance_Mode::instance()->set_maintenance_level(
743 743
                             EE_Maintenance_Mode::level_0_not_in_maintenance
@@ -837,7 +837,7 @@  discard block
 block discarded – undo
837 837
                 ),
838 838
                 'script'             => 'Unknown',
839 839
             ];
840
-            $this->add_error_to_migrations_ran($e->getMessage() . "; Stack trace:" . $e->getTraceAsString());
840
+            $this->add_error_to_migrations_ran($e->getMessage()."; Stack trace:".$e->getTraceAsString());
841 841
         }
842 842
         $warnings_etc = @ob_get_contents();
843 843
         ob_end_clean();
@@ -858,12 +858,12 @@  discard block
 block discarded – undo
858 858
      */
859 859
     public function update_current_database_state_to($slug_and_version = null)
860 860
     {
861
-        if (! $slug_and_version) {
861
+        if ( ! $slug_and_version) {
862 862
             // no version was provided, assume it should be at the current code version
863 863
             $slug_and_version = ['slug' => 'Core', 'version' => espresso_version()];
864 864
         }
865 865
         $current_database_state                              = get_option(self::current_database_state);
866
-        $current_database_state[ $slug_and_version['slug'] ] = $slug_and_version['version'];
866
+        $current_database_state[$slug_and_version['slug']] = $slug_and_version['version'];
867 867
         update_option(self::current_database_state, $current_database_state);
868 868
     }
869 869
 
@@ -883,15 +883,15 @@  discard block
 block discarded – undo
883 883
         $slug                   = $slug_and_version['slug'];
884 884
         $version                = $slug_and_version['version'];
885 885
         $current_database_state = get_option(self::current_database_state);
886
-        if (! isset($current_database_state[ $slug ])) {
886
+        if ( ! isset($current_database_state[$slug])) {
887 887
             return true;
888 888
         } else {
889 889
             // just compare the first 3 parts of version string, eg "4.7.1", not "4.7.1.dev.032" because DBs shouldn't change on nano version changes
890
-            $version_parts_current_db_state     = array_slice(explode('.', $current_database_state[ $slug ]), 0, 3);
890
+            $version_parts_current_db_state     = array_slice(explode('.', $current_database_state[$slug]), 0, 3);
891 891
             $version_parts_of_provided_db_state = array_slice(explode('.', $version), 0, 3);
892 892
             $needs_updating                     = false;
893 893
             foreach ($version_parts_current_db_state as $offset => $version_part_in_current_db_state) {
894
-                if ($version_part_in_current_db_state < $version_parts_of_provided_db_state[ $offset ]) {
894
+                if ($version_part_in_current_db_state < $version_parts_of_provided_db_state[$offset]) {
895 895
                     $needs_updating = true;
896 896
                     break;
897 897
                 }
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
      */
914 914
     public function get_all_data_migration_scripts_available()
915 915
     {
916
-        if (! $this->_data_migration_class_to_filepath_map) {
916
+        if ( ! $this->_data_migration_class_to_filepath_map) {
917 917
             $this->_data_migration_class_to_filepath_map = [];
918 918
             foreach ($this->get_data_migration_script_folders() as $eeAddonClass => $folder_path) {
919 919
                 // strip any placeholders added to classname to make it a unique array key
@@ -922,7 +922,7 @@  discard block
 block discarded – undo
922 922
                     ? $eeAddonClass
923 923
                     : '';
924 924
                 $folder_path  = EEH_File::end_with_directory_separator($folder_path);
925
-                $files        = glob($folder_path . '*.dms.php');
925
+                $files        = glob($folder_path.'*.dms.php');
926 926
                 if (empty($files)) {
927 927
                     continue;
928 928
                 }
@@ -948,7 +948,7 @@  discard block
 block discarded – undo
948 948
                             '4.3.0.alpha.019'
949 949
                         );
950 950
                     }
951
-                    $this->_data_migration_class_to_filepath_map[ $classname ] = $file;
951
+                    $this->_data_migration_class_to_filepath_map[$classname] = $file;
952 952
                 }
953 953
             }
954 954
             EEH_Autoloader::register_autoloader($this->_data_migration_class_to_filepath_map);
@@ -1018,10 +1018,10 @@  discard block
 block discarded – undo
1018 1018
             $versions_migrated_to                 = 'Unknown.1.0.0';
1019 1019
             // now just to make sure appears as last (in case the were previously a fatal error like this)
1020 1020
             // delete the old one
1021
-            delete_option(self::data_migration_script_option_prefix . $versions_migrated_to);
1021
+            delete_option(self::data_migration_script_option_prefix.$versions_migrated_to);
1022 1022
         }
1023 1023
         update_option(
1024
-            self::data_migration_script_option_prefix . $versions_migrated_to,
1024
+            self::data_migration_script_option_prefix.$versions_migrated_to,
1025 1025
             $last_ran_migration_script_properties
1026 1026
         );
1027 1027
     }
@@ -1042,9 +1042,9 @@  discard block
 block discarded – undo
1042 1042
         $successful_updates = true;
1043 1043
         foreach ($this->_data_migrations_ran as $plugin_slug => $migrations_ran_for_plugin) {
1044 1044
             foreach ($migrations_ran_for_plugin as $version_string => $array_or_migration_obj) {
1045
-                $plugin_slug_for_use_in_option_name = $plugin_slug . ".";
1045
+                $plugin_slug_for_use_in_option_name = $plugin_slug.".";
1046 1046
                 $option_name                        =
1047
-                    self::data_migration_script_option_prefix . $plugin_slug_for_use_in_option_name . $version_string;
1047
+                    self::data_migration_script_option_prefix.$plugin_slug_for_use_in_option_name.$version_string;
1048 1048
                 $old_option_value                   = get_option($option_name);
1049 1049
                 if ($array_or_migration_obj instanceof EE_Data_Migration_Script_Base) {
1050 1050
                     $script_array_for_saving = $array_or_migration_obj->properties_as_array();
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
                         $successful_updates = update_option($option_name, $array_or_migration_obj);
1057 1057
                     }
1058 1058
                 }
1059
-                if (! $successful_updates) {
1059
+                if ( ! $successful_updates) {
1060 1060
                     global $wpdb;
1061 1061
                     return $wpdb->last_error;
1062 1062
                 }
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
      */
1092 1092
     public function _instantiate_script_from_properties_array($properties_array)
1093 1093
     {
1094
-        if (! isset($properties_array['class'])) {
1094
+        if ( ! isset($properties_array['class'])) {
1095 1095
             throw new EE_Error(
1096 1096
                 sprintf(
1097 1097
                     esc_html__("Properties array  has no 'class' properties. Here's what it has: %s", "event_espresso"),
@@ -1100,14 +1100,14 @@  discard block
 block discarded – undo
1100 1100
             );
1101 1101
         }
1102 1102
         $class_name = $properties_array['class'];
1103
-        if (! class_exists($class_name)) {
1103
+        if ( ! class_exists($class_name)) {
1104 1104
             throw new EE_Error(sprintf(
1105 1105
                 esc_html__("There is no migration script named %s", "event_espresso"),
1106 1106
                 $class_name
1107 1107
             ));
1108 1108
         }
1109 1109
         $class = new $class_name();
1110
-        if (! $class instanceof EE_Data_Migration_Script_Base) {
1110
+        if ( ! $class instanceof EE_Data_Migration_Script_Base) {
1111 1111
             throw new EE_Error(
1112 1112
                 sprintf(
1113 1113
                     esc_html__(
@@ -1183,8 +1183,8 @@  discard block
 block discarded – undo
1183 1183
     public function get_migration_ran($version, $plugin_slug = 'Core')
1184 1184
     {
1185 1185
         $migrations_ran = $this->get_data_migrations_ran();
1186
-        if (isset($migrations_ran[ $plugin_slug ]) && isset($migrations_ran[ $plugin_slug ][ $version ])) {
1187
-            return $migrations_ran[ $plugin_slug ][ $version ];
1186
+        if (isset($migrations_ran[$plugin_slug]) && isset($migrations_ran[$plugin_slug][$version])) {
1187
+            return $migrations_ran[$plugin_slug][$version];
1188 1188
         } else {
1189 1189
             return null;
1190 1190
         }
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
     public function enqueue_db_initialization_for($plugin_slug)
1249 1249
     {
1250 1250
         $queue = $this->get_db_initialization_queue();
1251
-        if (! in_array($plugin_slug, $queue)) {
1251
+        if ( ! in_array($plugin_slug, $queue)) {
1252 1252
             $queue[] = $plugin_slug;
1253 1253
         }
1254 1254
         update_option(self::db_init_queue_option_name, $queue);
@@ -1267,7 +1267,7 @@  discard block
 block discarded – undo
1267 1267
         $queue = $this->get_db_initialization_queue();
1268 1268
         foreach ($queue as $plugin_slug) {
1269 1269
             $most_up_to_date_dms = $this->get_most_up_to_date_dms($plugin_slug);
1270
-            if (! $most_up_to_date_dms) {
1270
+            if ( ! $most_up_to_date_dms) {
1271 1271
                 // if there is NO DMS for this plugin, obviously there's no schema to verify anyways
1272 1272
                 $verify_db = false;
1273 1273
             } else {
Please login to merge, or discard this patch.
core/helpers/EEH_MSG_Template.helper.php 1 patch
Indentation   +1249 added lines, -1249 removed lines patch added patch discarded remove patch
@@ -15,1253 +15,1253 @@
 block discarded – undo
15 15
 {
16 16
 
17 17
 
18
-    /**
19
-     * Holds a collection of EE_Message_Template_Pack objects.
20
-     * @type EE_Messages_Template_Pack_Collection
21
-     */
22
-    protected static $_template_pack_collection;
23
-
24
-
25
-    /**
26
-     * @throws EE_Error
27
-     */
28
-    private static function _set_autoloader()
29
-    {
30
-        EED_Messages::set_autoloaders();
31
-    }
32
-
33
-
34
-    /**
35
-     * generate_new_templates
36
-     * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
37
-     * automatically create the defaults for the event.  The user would then be redirected to edit the default context
38
-     * for the event.
39
-     *
40
-     * @access protected
41
-     * @param string $messenger     the messenger we are generating templates for
42
-     * @param array  $message_types array of message types that the templates are generated for.
43
-     * @param int    $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID
44
-     *                              to use as the base for the new generated template.
45
-     * @param bool   $global        true indicates generating templates on messenger activation. false requires GRP_ID
46
-     *                              for event specific template generation.
47
-     * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array
48
-     *                for templates that are generated.  If this is an empty array then it means no templates were
49
-     *                generated which usually means there was an error.  Anything in the array with an empty value for
50
-     *                `MTP_context` means that it was not a new generated template but just reactivated (which only
51
-     *                happens for global templates that already exist in the database.
52
-     * @throws EE_Error
53
-     * @throws ReflectionException
54
-     */
55
-    public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
56
-    {
57
-        // make sure message_type is an array.
58
-        $message_types = (array) $message_types;
59
-        $templates = array();
60
-
61
-        if (empty($messenger)) {
62
-            throw new EE_Error(esc_html__('We need a messenger to generate templates!', 'event_espresso'));
63
-        }
64
-
65
-        // if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
66
-        if (empty($message_types)) {
67
-            throw new EE_Error(esc_html__('We need at least one message type to generate templates!', 'event_espresso'));
68
-        }
69
-
70
-        EEH_MSG_Template::_set_autoloader();
71
-        foreach ($message_types as $message_type) {
72
-            // if this is global template generation.
73
-            if ($global) {
74
-                // let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
75
-                if (empty($GRP_ID)) {
76
-                    $GRP_ID = EEM_Message_Template_Group::instance()->get_one(
77
-                        array(
78
-                            array(
79
-                                'MTP_messenger'    => $messenger,
80
-                                'MTP_message_type' => $message_type,
81
-                                'MTP_is_global'    => true,
82
-                            ),
83
-                        )
84
-                    );
85
-                    $GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
86
-                }
87
-                // First let's determine if we already HAVE global templates for this messenger and message_type combination.
88
-                //  If we do then NO generation!!
89
-                if (EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
90
-                    $templates[] = array(
91
-                        'GRP_ID' => $GRP_ID,
92
-                        'MTP_context' => '',
93
-                    );
94
-                    // we already have generated templates for this so let's go to the next message type.
95
-                    continue;
96
-                }
97
-            }
98
-            $new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
99
-
100
-            if (! $new_message_template_group) {
101
-                continue;
102
-            }
103
-            $templates[] = $new_message_template_group;
104
-        }
105
-
106
-        return $templates;
107
-    }
108
-
109
-
110
-    /**
111
-     * The purpose of this method is to determine if there are already generated templates in the database for the
112
-     * given variables.
113
-     *
114
-     * @param string $messenger    messenger
115
-     * @param string $message_type message type
116
-     * @param int    $GRP_ID       GRP ID ( if a custom template) (if not provided then we're just doing global
117
-     *                             template check)
118
-     * @return bool                true = generated, false = hasn't been generated.
119
-     * @throws EE_Error
120
-     */
121
-    public static function already_generated($messenger, $message_type, $GRP_ID = 0)
122
-    {
123
-        EEH_MSG_Template::_set_autoloader();
124
-        // what method we use depends on whether we have an GRP_ID or not
125
-        $count = empty($GRP_ID)
126
-            ? EEM_Message_Template::instance()->count(
127
-                array(
128
-                    array(
129
-                        'Message_Template_Group.MTP_messenger'    => $messenger,
130
-                        'Message_Template_Group.MTP_message_type' => $message_type,
131
-                        'Message_Template_Group.MTP_is_global'    => true
132
-                    )
133
-                )
134
-            )
135
-            : EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
136
-
137
-        return $count > 0;
138
-    }
139
-
140
-
141
-    /**
142
-     * Updates all message templates matching the incoming messengers and message types to active status.
143
-     *
144
-     * @static
145
-     * @param array $messenger_names    Messenger slug
146
-     * @param array $message_type_names Message type slug
147
-     * @return  int                         count of updated records.
148
-     * @throws EE_Error
149
-     */
150
-    public static function update_to_active($messenger_names, $message_type_names)
151
-    {
152
-        $messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
153
-        $message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
154
-        return EEM_Message_Template_Group::instance()->update(
155
-            array( 'MTP_is_active' => 1 ),
156
-            array(
157
-                array(
158
-                    'MTP_messenger'     => array( 'IN', $messenger_names ),
159
-                    'MTP_message_type'  => array( 'IN', $message_type_names )
160
-                )
161
-            )
162
-        );
163
-    }
164
-
165
-
166
-    /**
167
-     * Updates all message template groups matching the incoming arguments to inactive status.
168
-     *
169
-     * @static
170
-     * @param array $messenger_names    The messenger slugs.
171
-     *                                  If empty then all templates matching the message types are marked inactive.
172
-     *                                  Otherwise only templates matching the messengers and message types.
173
-     * @param array $message_type_names The message type slugs.
174
-     *                                  If empty then all templates matching the messengers are marked inactive.
175
-     *                                  Otherwise only templates matching the messengers and message types.
176
-     *
177
-     * @return int  count of updated records.
178
-     * @throws EE_Error
179
-     */
180
-    public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
181
-    {
182
-        return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
183
-            $messenger_names,
184
-            $message_type_names
185
-        );
186
-    }
187
-
188
-
189
-    /**
190
-     * The purpose of this function is to return all installed message objects
191
-     * (messengers and message type regardless of whether they are ACTIVE or not)
192
-     *
193
-     * @param string $type
194
-     * @return array array consisting of installed messenger objects and installed message type objects.
195
-     * @throws EE_Error
196
-     * @throws ReflectionException
197
-     * @deprecated 4.9.0
198
-     * @static
199
-     */
200
-    public static function get_installed_message_objects($type = 'all')
201
-    {
202
-        self::_set_autoloader();
203
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
204
-        return array(
205
-            'messenger' => $message_resource_manager->installed_messengers(),
206
-            'message_type' => $message_resource_manager->installed_message_types()
207
-        );
208
-    }
209
-
210
-
211
-    /**
212
-     * This will return an array of shortcodes => labels from the
213
-     * messenger and message_type objects associated with this
214
-     * template.
215
-     *
216
-     * @param string $message_type
217
-     * @param string $messenger
218
-     * @param array  $fields                        What fields we're returning valid shortcodes for.
219
-     *                                              If empty then we assume all fields are to be returned. Optional.
220
-     * @param string $context                       What context we're going to return shortcodes for. Optional.
221
-     * @param bool   $merged                        If TRUE then we don't return shortcodes indexed by field,
222
-     *                                              but instead an array of the unique shortcodes for all the given (
223
-     *                                              or all) fields. Optional.
224
-     * @return array                                an array of shortcodes in the format
225
-     *                                              array( '[shortcode] => 'label')
226
-     *                                              OR
227
-     *                                              FALSE if no shortcodes found.
228
-     * @throws ReflectionException
229
-     * @throws EE_Error*@since 4.3.0
230
-     *
231
-     */
232
-    public static function get_shortcodes(
233
-        $message_type,
234
-        $messenger,
235
-        $fields = array(),
236
-        $context = 'admin',
237
-        $merged = false
238
-    ) {
239
-        $messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
240
-        $mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
241
-        /** @var EE_Message_Resource_Manager $message_resource_manager */
242
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
243
-        // convert slug to object
244
-        $messenger = $message_resource_manager->get_messenger($messenger);
245
-
246
-        // if messenger isn't a EE_messenger resource then bail.
247
-        if (! $messenger instanceof EE_messenger) {
248
-            return array();
249
-        }
250
-
251
-        // validate class for getting our list of shortcodes
252
-        $classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
253
-        if (! class_exists($classname)) {
254
-            $msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
255
-            $msg[] = sprintf(
256
-                esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
257
-                $classname
258
-            );
259
-            throw new EE_Error(implode('||', $msg));
260
-        }
261
-
262
-        /** @type EE_Messages_Validator $_VLD */
263
-        $_VLD = new $classname(array(), $context);
264
-        $valid_shortcodes = $_VLD->get_validators();
265
-
266
-        // let's make sure we're only getting the shortcode part of the validators
267
-        $shortcodes = array();
268
-        foreach ($valid_shortcodes as $field => $validators) {
269
-            $shortcodes[ $field ] = $validators['shortcodes'];
270
-        }
271
-        $valid_shortcodes = $shortcodes;
272
-
273
-        // if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
274
-        if (! empty($fields)) {
275
-            $specified_shortcodes = array();
276
-            foreach ($fields as $field) {
277
-                if (isset($valid_shortcodes[ $field ])) {
278
-                    $specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
279
-                }
280
-            }
281
-            $valid_shortcodes = $specified_shortcodes;
282
-        }
283
-
284
-        // if not merged then let's replace the fields with the localized fields
285
-        if (! $merged) {
286
-            // let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
287
-            $field_settings = $messenger->get_template_fields();
288
-            $localized = array();
289
-            foreach ($valid_shortcodes as $field => $shortcodes) {
290
-                // get localized field label
291
-                if (isset($field_settings[ $field ])) {
292
-                    // possible that this is used as a main field.
293
-                    if (empty($field_settings[ $field ])) {
294
-                        if (isset($field_settings['extra'][ $field ])) {
295
-                            $_field = $field_settings['extra'][ $field ]['main']['label'];
296
-                        } else {
297
-                            $_field = $field;
298
-                        }
299
-                    } else {
300
-                        $_field = $field_settings[ $field ]['label'];
301
-                    }
302
-                } elseif (isset($field_settings['extra'])) {
303
-                    // loop through extra "main fields" and see if any of their children have our field
304
-                    foreach ($field_settings['extra'] as $fields) {
305
-                        if (isset($fields[ $field ])) {
306
-                            $_field = $fields[ $field ]['label'];
307
-                        } else {
308
-                            $_field = $field;
309
-                        }
310
-                    }
311
-                } else {
312
-                    $_field = $field;
313
-                }
314
-                if (isset($_field)) {
315
-                    $localized[ (string) $_field ] = $shortcodes;
316
-                }
317
-            }
318
-            $valid_shortcodes = $localized;
319
-        }
320
-
321
-        // if $merged then let's merge all the shortcodes into one list NOT indexed by field.
322
-        if ($merged) {
323
-            $merged_codes = array();
324
-            foreach ($valid_shortcodes as $shortcode) {
325
-                foreach ($shortcode as $code => $label) {
326
-                    if (isset($merged_codes[ $code ])) {
327
-                        continue;
328
-                    } else {
329
-                        $merged_codes[ $code ] = $label;
330
-                    }
331
-                }
332
-            }
333
-            $valid_shortcodes = $merged_codes;
334
-        }
335
-
336
-        return $valid_shortcodes;
337
-    }
338
-
339
-
340
-    /**
341
-     * Get Messenger object.
342
-     *
343
-     * @param string $messenger messenger slug for the messenger object we want to retrieve.
344
-     * @return EE_messenger
345
-     * @throws ReflectionException
346
-     * @throws EE_Error*@since 4.3.0
347
-     * @deprecated 4.9.0
348
-     */
349
-    public static function messenger_obj($messenger)
350
-    {
351
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
352
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
353
-        return $Message_Resource_Manager->get_messenger($messenger);
354
-    }
355
-
356
-
357
-    /**
358
-     * get Message type object
359
-     *
360
-     * @param string $message_type the slug for the message type object to retrieve
361
-     * @return EE_message_type
362
-     * @throws ReflectionException
363
-     * @throws EE_Error*@since 4.3.0
364
-     * @deprecated 4.9.0
365
-     */
366
-    public static function message_type_obj($message_type)
367
-    {
368
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
369
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
370
-        return $Message_Resource_Manager->get_message_type($message_type);
371
-    }
372
-
373
-
374
-    /**
375
-     * Given a message_type slug, will return whether that message type is active in the system or not.
376
-     *
377
-     * @since    4.3.0
378
-     * @param string $message_type message type to check for.
379
-     * @return boolean
380
-     * @throws EE_Error
381
-     * @throws ReflectionException
382
-     */
383
-    public static function is_mt_active($message_type)
384
-    {
385
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
386
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
387
-        $active_mts = $Message_Resource_Manager->list_of_active_message_types();
388
-        return in_array($message_type, $active_mts);
389
-    }
390
-
391
-
392
-    /**
393
-     * Given a messenger slug, will return whether that messenger is active in the system or not.
394
-     *
395
-     * @since    4.3.0
396
-     *
397
-     * @param string $messenger slug for messenger to check.
398
-     * @return boolean
399
-     * @throws EE_Error
400
-     * @throws ReflectionException
401
-     */
402
-    public static function is_messenger_active($messenger)
403
-    {
404
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
405
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
406
-        $active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
407
-        return $active_messenger instanceof EE_messenger;
408
-    }
409
-
410
-
411
-    /**
412
-     * Used to return active messengers array stored in the wp options table.
413
-     * If no value is present in the option then an empty array is returned.
414
-     *
415
-     * @deprecated 4.9
416
-     * @since      4.3.1
417
-     *
418
-     * @return array
419
-     * @throws EE_Error
420
-     * @throws ReflectionException
421
-     */
422
-    public static function get_active_messengers_in_db()
423
-    {
424
-        EE_Error::doing_it_wrong(
425
-            __METHOD__,
426
-            esc_html__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
427
-            '4.9.0'
428
-        );
429
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
430
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
431
-        return $Message_Resource_Manager->get_active_messengers_option();
432
-    }
433
-
434
-
435
-    /**
436
-     * Used to update the active messengers array stored in the wp options table.
437
-     *
438
-     * @since      4.3.1
439
-     * @deprecated 4.9.0
440
-     *
441
-     * @param array $data_to_save Incoming data to save.
442
-     *
443
-     * @return bool FALSE if not updated, TRUE if updated.
444
-     * @throws EE_Error
445
-     * @throws ReflectionException
446
-     */
447
-    public static function update_active_messengers_in_db($data_to_save)
448
-    {
449
-        EE_Error::doing_it_wrong(
450
-            __METHOD__,
451
-            esc_html__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
452
-            '4.9.0'
453
-        );
454
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
455
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
456
-        return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
457
-    }
458
-
459
-
460
-    /**
461
-     * This does some validation of incoming params, determines what type of url is being prepped and returns the
462
-     * appropriate url trigger
463
-     *
464
-     * @param EE_message_type $message_type
465
-     * @param EE_Message $message
466
-     * @param EE_Registration | null $registration  The registration object must be included if this
467
-     *                                              is going to be a registration trigger url.
468
-     * @param string $sending_messenger             The (optional) sending messenger for the url.
469
-     *
470
-     * @return string
471
-     * @throws EE_Error
472
-     */
473
-    public static function get_url_trigger(
474
-        EE_message_type $message_type,
475
-        EE_Message $message,
476
-        $registration = null,
477
-        $sending_messenger = ''
478
-    ) {
479
-        // first determine if the url can be to the EE_Message object.
480
-        if (! $message_type->always_generate()) {
481
-            return EEH_MSG_Template::generate_browser_trigger($message);
482
-        }
483
-
484
-        // if $registration object is not valid then exit early because there's nothing that can be generated.
485
-        if (! $registration instanceof EE_Registration) {
486
-            throw new EE_Error(
487
-                esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
488
-            );
489
-        }
490
-
491
-        // validate given context
492
-        $contexts = $message_type->get_contexts();
493
-        if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
494
-            throw new EE_Error(
495
-                sprintf(
496
-                    esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
497
-                    $message->context(),
498
-                    get_class($message_type)
499
-                )
500
-            );
501
-        }
502
-
503
-        // valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
504
-        if (! empty($sending_messenger)) {
505
-            $with_messengers = $message_type->with_messengers();
506
-            if (
507
-                ! isset($with_messengers[ $message->messenger() ])
508
-                 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
509
-            ) {
510
-                throw new EE_Error(
511
-                    sprintf(
512
-                        esc_html__(
513
-                            'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
514
-                            'event_espresso'
515
-                        ),
516
-                        $sending_messenger,
517
-                        get_class($message_type)
518
-                    )
519
-                );
520
-            }
521
-        } else {
522
-            $sending_messenger = $message->messenger();
523
-        }
524
-        return EEH_MSG_Template::generate_url_trigger(
525
-            $sending_messenger,
526
-            $message->messenger(),
527
-            $message->context(),
528
-            $message->message_type(),
529
-            $registration,
530
-            $message->GRP_ID()
531
-        );
532
-    }
533
-
534
-
535
-    /**
536
-     * This returns the url for triggering a in browser view of a specific EE_Message object.
537
-     * @param EE_Message $message
538
-     * @return string.
539
-     */
540
-    public static function generate_browser_trigger(EE_Message $message)
541
-    {
542
-        $query_args = array(
543
-            'ee' => 'msg_browser_trigger',
544
-            'token' => $message->MSG_token()
545
-        );
546
-        return apply_filters(
547
-            'FHEE__EEH_MSG_Template__generate_browser_trigger',
548
-            add_query_arg($query_args, site_url()),
549
-            $message
550
-        );
551
-    }
552
-
553
-
554
-
555
-
556
-
557
-
558
-    /**
559
-     * This returns the url for triggering an in browser view of the error saved on the incoming message object.
560
-     * @param EE_Message $message
561
-     * @return string
562
-     */
563
-    public static function generate_error_display_trigger(EE_Message $message)
564
-    {
565
-        return apply_filters(
566
-            'FHEE__EEH_MSG_Template__generate_error_display_trigger',
567
-            add_query_arg(
568
-                array(
569
-                    'ee' => 'msg_browser_error_trigger',
570
-                    'token' => $message->MSG_token()
571
-                ),
572
-                site_url()
573
-            ),
574
-            $message
575
-        );
576
-    }
577
-
578
-
579
-    /**
580
-     * This generates a url trigger for the msg_url_trigger route using the given arguments
581
-     *
582
-     * @param string          $sending_messenger      The sending messenger slug.
583
-     * @param string          $generating_messenger   The generating messenger slug.
584
-     * @param string          $context                The context for the template.
585
-     * @param string          $message_type           The message type slug
586
-     * @param EE_Registration $registration
587
-     * @param integer         $message_template_group id   The EE_Message_Template_Group ID for the template.
588
-     * @param integer         $data_id                The id to the EE_Base_Class for getting the data used by the
589
-     *                                                trigger.
590
-     * @return string          The generated url.
591
-     * @throws EE_Error
592
-     */
593
-    public static function generate_url_trigger(
594
-        $sending_messenger,
595
-        $generating_messenger,
596
-        $context,
597
-        $message_type,
598
-        EE_Registration $registration,
599
-        $message_template_group,
600
-        $data_id = 0
601
-    ) {
602
-        $query_args = array(
603
-            'ee' => 'msg_url_trigger',
604
-            'snd_msgr' => $sending_messenger,
605
-            'gen_msgr' => $generating_messenger,
606
-            'message_type' => $message_type,
607
-            'context' => $context,
608
-            'token' => $registration->reg_url_link(),
609
-            'GRP_ID' => $message_template_group,
610
-            'id' => $data_id
611
-            );
612
-        $url = add_query_arg($query_args, get_home_url());
613
-
614
-        // made it here so now we can just get the url and filter it.  Filtered globally and by message type.
615
-        return apply_filters(
616
-            'FHEE__EEH_MSG_Template__generate_url_trigger',
617
-            $url,
618
-            $sending_messenger,
619
-            $generating_messenger,
620
-            $context,
621
-            $message_type,
622
-            $registration,
623
-            $message_template_group,
624
-            $data_id
625
-        );
626
-    }
627
-
628
-
629
-
630
-
631
-    /**
632
-     * Return the specific css for the action icon given.
633
-     *
634
-     * @param string $type  What action to return.
635
-     * @return string[]
636
-     * @since 4.9.0
637
-     */
638
-    public static function get_message_action_icon($type)
639
-    {
640
-        $action_icons = self::get_message_action_icons();
641
-        return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
642
-    }
643
-
644
-
645
-    /**
646
-     * This is used for retrieving the css classes used for the icons representing message actions.
647
-     *
648
-     * @since 4.9.0
649
-     *
650
-     * @return array
651
-     */
652
-    public static function get_message_action_icons()
653
-    {
654
-        return apply_filters(
655
-            'FHEE__EEH_MSG_Template__message_action_icons',
656
-            array(
657
-                'view' => array(
658
-                    'label' => esc_html__('View Message', 'event_espresso'),
659
-                    'css_class' => 'dashicons dashicons-welcome-view-site',
660
-                ),
661
-                'error' => array(
662
-                    'label' => esc_html__('View Error Message', 'event_espresso'),
663
-                    'css_class' => 'dashicons dashicons-info',
664
-                ),
665
-                'see_notifications_for' => array(
666
-                    'label' => esc_html__('View Related Messages', 'event_espresso'),
667
-                    'css_class' => 'dashicons dashicons-megaphone',
668
-                ),
669
-                'generate_now' => array(
670
-                    'label' => esc_html__('Generate the message now.', 'event_espresso'),
671
-                    'css_class' => 'dashicons dashicons-admin-tools',
672
-                ),
673
-                'send_now' => array(
674
-                    'label' => esc_html__('Send Immediately', 'event_espresso'),
675
-                    'css_class' => 'dashicons dashicons-controls-forward',
676
-                ),
677
-                'queue_for_resending' => array(
678
-                    'label' => esc_html__('Queue for Resending', 'event_espresso'),
679
-                    'css_class' => 'dashicons dashicons-controls-repeat',
680
-                ),
681
-                'view_transaction' => array(
682
-                    'label' => esc_html__('View related Transaction', 'event_espresso'),
683
-                    'css_class' => 'dashicons dashicons-cart',
684
-                )
685
-            )
686
-        );
687
-    }
688
-
689
-
690
-    /**
691
-     * This returns the url for a given action related to EE_Message.
692
-     *
693
-     * @param string     $type         What type of action to return the url for.
694
-     * @param EE_Message $message      Required for generating the correct url for some types.
695
-     * @param array      $query_params Any additional query params to be included with the generated url.
696
-     *
697
-     * @return string
698
-     * @throws EE_Error
699
-     * @throws ReflectionException
700
-     * @since 4.9.0
701
-     *
702
-     */
703
-    public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
704
-    {
705
-        $action_urls = self::get_message_action_urls($message, $query_params);
706
-        return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
707
-    }
708
-
709
-
710
-    /**
711
-     * This returns all the current urls for EE_Message actions.
712
-     *
713
-     * @since 4.9.0
714
-     *
715
-     * @param EE_Message $message      The EE_Message object required to generate correct urls for some types.
716
-     * @param array      $query_params Any additional query_params to be included with the generated url.
717
-     *
718
-     * @return array
719
-     * @throws EE_Error
720
-     * @throws ReflectionException
721
-     */
722
-    public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
723
-    {
724
-        EE_Registry::instance()->load_helper('URL');
725
-        // if $message is not an instance of EE_Message then let's just do a dummy.
726
-        $message = empty($message) ? EE_Message_Factory::create() : $message;
727
-        $action_urls =  apply_filters(
728
-            'FHEE__EEH_MSG_Template__get_message_action_url',
729
-            array(
730
-                'view' => EEH_MSG_Template::generate_browser_trigger($message),
731
-                'error' => EEH_MSG_Template::generate_error_display_trigger($message),
732
-                'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
733
-                    array_merge(
734
-                        array(
735
-                            'page' => 'espresso_messages',
736
-                            'action' => 'default',
737
-                            'filterby' => 1,
738
-                        ),
739
-                        $query_params
740
-                    ),
741
-                    admin_url('admin.php')
742
-                ),
743
-                'generate_now' => EEH_URL::add_query_args_and_nonce(
744
-                    array(
745
-                        'page' => 'espresso_messages',
746
-                        'action' => 'generate_now',
747
-                        'MSG_ID' => $message->ID()
748
-                    ),
749
-                    admin_url('admin.php')
750
-                ),
751
-                'send_now' => EEH_URL::add_query_args_and_nonce(
752
-                    array(
753
-                        'page' => 'espresso_messages',
754
-                        'action' => 'send_now',
755
-                        'MSG_ID' => $message->ID()
756
-                    ),
757
-                    admin_url('admin.php')
758
-                ),
759
-                'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
760
-                    array(
761
-                        'page' => 'espresso_messages',
762
-                        'action' => 'queue_for_resending',
763
-                        'MSG_ID' => $message->ID()
764
-                    ),
765
-                    admin_url('admin.php')
766
-                ),
767
-            )
768
-        );
769
-        if (
770
-            $message->TXN_ID() > 0
771
-            && EE_Registry::instance()->CAP->current_user_can(
772
-                'ee_read_transaction',
773
-                'espresso_transactions_default',
774
-                $message->TXN_ID()
775
-            )
776
-        ) {
777
-            $action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
778
-                array(
779
-                    'page' => 'espresso_transactions',
780
-                    'action' => 'view_transaction',
781
-                    'TXN_ID' => $message->TXN_ID()
782
-                ),
783
-                admin_url('admin.php')
784
-            );
785
-        } else {
786
-            $action_urls['view_transaction'] = '';
787
-        }
788
-        return $action_urls;
789
-    }
790
-
791
-
792
-    /**
793
-     * This returns a generated link html including the icon used for the action link for EE_Message actions.
794
-     *
795
-     * @param string          $type         What type of action the link is for (if invalid type is passed in then an
796
-     *                                      empty string is returned)
797
-     * @param EE_Message|null $message      The EE_Message object (required for some actions to generate correctly)
798
-     * @param array           $query_params Any extra query params to include in the generated link.
799
-     *
800
-     * @return string
801
-     * @throws EE_Error
802
-     * @throws ReflectionException
803
-     * @since 4.9.0
804
-     *
805
-     */
806
-    public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
807
-    {
808
-        $url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
809
-        $icon_css = EEH_MSG_Template::get_message_action_icon($type);
810
-        $title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
811
-
812
-        if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
813
-            return '';
814
-        }
815
-
816
-        $icon_css['css_class'] .= esc_attr(
817
-            apply_filters(
818
-                'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
819
-                ' js-ee-message-action-link ee-message-action-link-' . $type,
820
-                $type,
821
-                $message,
822
-                $query_params
823
-            )
824
-        );
825
-
826
-        return '<a href="' . $url . '" ' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
827
-    }
828
-
829
-
830
-
831
-
832
-
833
-    /**
834
-     * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
835
-     *
836
-     * @since 4.9.0
837
-     * @return array
838
-     */
839
-    public static function reg_status_to_message_type_array()
840
-    {
841
-        return (array) apply_filters(
842
-            'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
843
-            array(
844
-                EEM_Registration::status_id_approved => 'registration',
845
-                EEM_Registration::status_id_pending_payment => 'pending_approval',
846
-                EEM_Registration::status_id_not_approved => 'not_approved_registration',
847
-                EEM_Registration::status_id_cancelled => 'cancelled_registration',
848
-                EEM_Registration::status_id_declined => 'declined_registration'
849
-            )
850
-        );
851
-    }
852
-
853
-
854
-
855
-
856
-    /**
857
-     * This returns the corresponding registration message type slug to the given reg status. If there isn't a
858
-     * match, then returns an empty string.
859
-     *
860
-     * @since 4.9.0
861
-     * @param $reg_status
862
-     * @return string
863
-     */
864
-    public static function convert_reg_status_to_message_type($reg_status)
865
-    {
866
-        $reg_status_array = self::reg_status_to_message_type_array();
867
-        return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
868
-    }
869
-
870
-
871
-    /**
872
-     * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
873
-     *
874
-     * @since 4.9.0
875
-     * @return array
876
-     */
877
-    public static function payment_status_to_message_type_array()
878
-    {
879
-        return (array) apply_filters(
880
-            'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
881
-            array(
882
-                EEM_Payment::status_id_approved => 'payment',
883
-                EEM_Payment::status_id_pending => 'payment_pending',
884
-                EEM_Payment::status_id_cancelled => 'payment_cancelled',
885
-                EEM_Payment::status_id_declined => 'payment_declined',
886
-                EEM_Payment::status_id_failed => 'payment_failed'
887
-            )
888
-        );
889
-    }
890
-
891
-
892
-
893
-
894
-    /**
895
-     * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
896
-     * an empty string is returned
897
-     *
898
-     * @since 4.9.0
899
-     * @param $payment_status
900
-     * @return string
901
-     */
902
-    public static function convert_payment_status_to_message_type($payment_status)
903
-    {
904
-        $payment_status_array = self::payment_status_to_message_type_array();
905
-        return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
906
-    }
907
-
908
-
909
-    /**
910
-     * This is used to retrieve the template pack for the given name.
911
-     *
912
-     * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
913
-     *
914
-     * @return EE_Messages_Template_Pack
915
-     */
916
-    public static function get_template_pack($template_pack_name)
917
-    {
918
-        if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
919
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
920
-        }
921
-
922
-        // first see if in collection already
923
-        $template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
924
-
925
-        if ($template_pack instanceof EE_Messages_Template_Pack) {
926
-            return $template_pack;
927
-        }
928
-
929
-        // nope...let's get it.
930
-        // not set yet so let's attempt to get it.
931
-        $pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
932
-            ' ',
933
-            '_',
934
-            ucwords(
935
-                str_replace('_', ' ', $template_pack_name)
936
-            )
937
-        );
938
-        if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
939
-            return self::get_template_pack('default');
940
-        } else {
941
-            $template_pack = new $pack_class_name();
942
-            self::$_template_pack_collection->add($template_pack);
943
-            return $template_pack;
944
-        }
945
-    }
946
-
947
-
948
-
949
-
950
-    /**
951
-     * Globs template packs installed in core and returns the template pack collection with all installed template packs
952
-     * in it.
953
-     *
954
-     * @since 4.9.0
955
-     *
956
-     * @return EE_Messages_Template_Pack_Collection
957
-     */
958
-    public static function get_template_pack_collection()
959
-    {
960
-        $new_collection = false;
961
-        if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
962
-            self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
963
-            $new_collection = true;
964
-        }
965
-
966
-        // glob the defaults directory for messages
967
-        $templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
968
-        foreach ($templates as $template_path) {
969
-            // grab folder name
970
-            $template = basename($template_path);
971
-
972
-            if (! $new_collection) {
973
-                // already have it?
974
-                if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
975
-                    continue;
976
-                }
977
-            }
978
-
979
-            // setup classname.
980
-            $template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
981
-                ' ',
982
-                '_',
983
-                ucwords(
984
-                    str_replace(
985
-                        '_',
986
-                        ' ',
987
-                        $template
988
-                    )
989
-                )
990
-            );
991
-            if (! class_exists($template_pack_class_name)) {
992
-                continue;
993
-            }
994
-            self::$_template_pack_collection->add(new $template_pack_class_name());
995
-        }
996
-
997
-        /**
998
-         * Filter for plugins to add in any additional template packs
999
-         * Note the filter name here is for backward compat, this used to be found in EED_Messages.
1000
-         */
1001
-        $additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
1002
-        foreach ((array) $additional_template_packs as $template_pack) {
1003
-            if (
1004
-                self::$_template_pack_collection->get_by_name(
1005
-                    $template_pack->dbref
1006
-                ) instanceof EE_Messages_Template_Pack
1007
-            ) {
1008
-                continue;
1009
-            }
1010
-            self::$_template_pack_collection->add($template_pack);
1011
-        }
1012
-        return self::$_template_pack_collection;
1013
-    }
1014
-
1015
-
1016
-    /**
1017
-     * This is a wrapper for the protected _create_new_templates function
1018
-     *
1019
-     * @param string $messenger_name
1020
-     * @param string $message_type_name message type that the templates are being created for
1021
-     * @param int    $GRP_ID
1022
-     * @param bool   $global
1023
-     * @return array
1024
-     * @throws EE_Error
1025
-     * @throws ReflectionException
1026
-     */
1027
-    public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1028
-    {
1029
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1030
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1031
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1032
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1033
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1034
-            return array();
1035
-        }
1036
-        // whew made it this far!  Okay, let's go ahead and create the templates then
1037
-        return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1038
-    }
1039
-
1040
-
1041
-    /**
1042
-     * @param EE_messenger     $messenger
1043
-     * @param EE_message_type  $message_type
1044
-     * @param                  $GRP_ID
1045
-     * @param                  $global
1046
-     * @return array|mixed
1047
-     * @throws EE_Error
1048
-     * @throws ReflectionException
1049
-     */
1050
-    protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1051
-    {
1052
-        // if we're creating a custom template then we don't need to use the defaults class
1053
-        if (! $global) {
1054
-            return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1055
-        }
1056
-        /** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1057
-        $Message_Template_Defaults = EE_Registry::factory(
1058
-            'EE_Messages_Template_Defaults',
1059
-            array( $messenger, $message_type, $GRP_ID )
1060
-        );
1061
-        // generate templates
1062
-        $success = $Message_Template_Defaults->create_new_templates();
1063
-
1064
-        // if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1065
-        // its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1066
-        // attempts.
1067
-        if (! $success) {
1068
-            /** @var EE_Message_Resource_Manager $message_resource_manager */
1069
-            $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1070
-            $message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1071
-        }
1072
-
1073
-        /**
1074
-         * $success is in an array in the following format
1075
-         * array(
1076
-         *    'GRP_ID' => $new_grp_id,
1077
-         *    'MTP_context' => $first_context_in_new_templates,
1078
-         * )
1079
-         */
1080
-        return $success;
1081
-    }
1082
-
1083
-
1084
-    /**
1085
-     * This creates a custom template using the incoming GRP_ID
1086
-     *
1087
-     * @param EE_messenger    $messenger
1088
-     * @param EE_message_type $message_type
1089
-     * @param int             $GRP_ID           GRP_ID for the template_group being used as the base
1090
-     * @return  array $success              This will be an array in the format:
1091
-     *                                          array(
1092
-     *                                          'GRP_ID' => $new_grp_id,
1093
-     *                                          'MTP_context' => $first_context_in_created_template
1094
-     *                                          )
1095
-     * @throws EE_Error
1096
-     * @throws ReflectionException
1097
-     * @access private
1098
-     */
1099
-    private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1100
-    {
1101
-        // defaults
1102
-        $success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1103
-        // get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1104
-        $Message_Template_Group = empty($GRP_ID)
1105
-            ? EEM_Message_Template_Group::instance()->get_one(
1106
-                array(
1107
-                    array(
1108
-                        'MTP_messenger'    => $messenger->name,
1109
-                        'MTP_message_type' => $message_type->name,
1110
-                        'MTP_is_global'    => true
1111
-                    )
1112
-                )
1113
-            )
1114
-            : EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1115
-        // if we don't have a mtg at this point then we need to bail.
1116
-        if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1117
-            EE_Error::add_error(
1118
-                sprintf(
1119
-                    esc_html__(
1120
-                        'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1121
-                        'event_espresso'
1122
-                    ),
1123
-                    $GRP_ID
1124
-                ),
1125
-                __FILE__,
1126
-                __FUNCTION__,
1127
-                __LINE__
1128
-            );
1129
-            return $success;
1130
-        }
1131
-        // let's get all the related message_template objects for this group.
1132
-        $message_templates = $Message_Template_Group->message_templates();
1133
-        // now we have what we need to setup the new template
1134
-        $new_mtg = clone $Message_Template_Group;
1135
-        $new_mtg->set('GRP_ID', 0);
1136
-        $new_mtg->set('MTP_is_global', false);
1137
-
1138
-        /** @var RequestInterface $request */
1139
-        $request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1140
-        $template_name = $request->isAjax() && $request->requestParamIsSet('templateName')
1141
-            ? $request->getRequestParam('templateName')
1142
-            : esc_html__('New Custom Template', 'event_espresso');
1143
-        $template_description = $request->isAjax() && $request->requestParamIsSet('templateDescription')
1144
-            ? $request->getRequestParam('templateDescription')
1145
-            : sprintf(
1146
-                esc_html__(
1147
-                    'This is a custom template that was created for the %s messenger and %s message type.',
1148
-                    'event_espresso'
1149
-                ),
1150
-                $new_mtg->messenger_obj()->label['singular'],
1151
-                $new_mtg->message_type_obj()->label['singular']
1152
-            );
1153
-        $new_mtg->set('MTP_name', $template_name);
1154
-        $new_mtg->set('MTP_description', $template_description);
1155
-        // remove ALL relations on this template group so they don't get saved!
1156
-        $new_mtg->_remove_relations('Message_Template');
1157
-        $new_mtg->save();
1158
-        $success['GRP_ID'] = $new_mtg->ID();
1159
-        $success['template_name'] = $template_name;
1160
-        // add new message templates and add relation to.
1161
-        foreach ($message_templates as $message_template) {
1162
-            if (! $message_template instanceof EE_Message_Template) {
1163
-                continue;
1164
-            }
1165
-            $new_message_template = clone $message_template;
1166
-            $new_message_template->set('MTP_ID', 0);
1167
-            $new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1168
-            $new_message_template->save();
1169
-            if (empty($success['MTP_context']) && $new_message_template->get('MTP_context') !== 'admin') {
1170
-                $success['MTP_context'] = $new_message_template->get('MTP_context');
1171
-            }
1172
-        }
1173
-        return $success;
1174
-    }
1175
-
1176
-
1177
-    /**
1178
-     * message_type_has_active_templates_for_messenger
1179
-     *
1180
-     * @param EE_messenger    $messenger
1181
-     * @param EE_message_type $message_type
1182
-     * @param bool            $global
1183
-     * @return bool
1184
-     * @throws EE_Error
1185
-     */
1186
-    public static function message_type_has_active_templates_for_messenger(
1187
-        EE_messenger $messenger,
1188
-        EE_message_type $message_type,
1189
-        $global = false
1190
-    ) {
1191
-        // is given message_type valid for given messenger (if this is not a global save)
1192
-        if ($global) {
1193
-            return true;
1194
-        }
1195
-        $active_templates = EEM_Message_Template_Group::instance()->count(
1196
-            array(
1197
-                array(
1198
-                    'MTP_is_active'    => true,
1199
-                    'MTP_messenger'    => $messenger->name,
1200
-                    'MTP_message_type' => $message_type->name
1201
-                )
1202
-            )
1203
-        );
1204
-        if ($active_templates > 0) {
1205
-            return true;
1206
-        }
1207
-        EE_Error::add_error(
1208
-            sprintf(
1209
-                esc_html__(
1210
-                    'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1211
-                    'event_espresso'
1212
-                ),
1213
-                $message_type->name,
1214
-                $messenger->name
1215
-            ),
1216
-            __FILE__,
1217
-            __FUNCTION__,
1218
-            __LINE__
1219
-        );
1220
-        return false;
1221
-    }
1222
-
1223
-
1224
-    /**
1225
-     * get_fields
1226
-     * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1227
-     *
1228
-     * @param string $messenger_name    name of EE_messenger
1229
-     * @param string $message_type_name name of EE_message_type
1230
-     * @return array
1231
-     * @throws EE_Error
1232
-     * @throws ReflectionException
1233
-     */
1234
-    public static function get_fields($messenger_name, $message_type_name)
1235
-    {
1236
-        $template_fields = array();
1237
-        /** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1238
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1239
-        $messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1240
-        $message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1241
-        if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1242
-            return array();
1243
-        }
1244
-
1245
-        $excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1246
-
1247
-        // okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1248
-        foreach ($message_type->get_contexts() as $context => $details) {
1249
-            foreach ($messenger->get_template_fields() as $field => $value) {
1250
-                if (in_array($field, $excluded_fields_for_messenger, true)) {
1251
-                    continue;
1252
-                }
1253
-                $template_fields[ $context ][ $field ] = $value;
1254
-            }
1255
-        }
1256
-        if (empty($template_fields)) {
1257
-            EE_Error::add_error(
1258
-                esc_html__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1259
-                __FILE__,
1260
-                __FUNCTION__,
1261
-                __LINE__
1262
-            );
1263
-            return array();
1264
-        }
1265
-        return $template_fields;
1266
-    }
18
+	/**
19
+	 * Holds a collection of EE_Message_Template_Pack objects.
20
+	 * @type EE_Messages_Template_Pack_Collection
21
+	 */
22
+	protected static $_template_pack_collection;
23
+
24
+
25
+	/**
26
+	 * @throws EE_Error
27
+	 */
28
+	private static function _set_autoloader()
29
+	{
30
+		EED_Messages::set_autoloaders();
31
+	}
32
+
33
+
34
+	/**
35
+	 * generate_new_templates
36
+	 * This will handle the messenger, message_type selection when "adding a new custom template" for an event and will
37
+	 * automatically create the defaults for the event.  The user would then be redirected to edit the default context
38
+	 * for the event.
39
+	 *
40
+	 * @access protected
41
+	 * @param string $messenger     the messenger we are generating templates for
42
+	 * @param array  $message_types array of message types that the templates are generated for.
43
+	 * @param int    $GRP_ID        If a non global template is being generated then it is expected we'll have a GRP_ID
44
+	 *                              to use as the base for the new generated template.
45
+	 * @param bool   $global        true indicates generating templates on messenger activation. false requires GRP_ID
46
+	 *                              for event specific template generation.
47
+	 * @return array  @see EEH_MSG_Template::_create_new_templates for the return value of each element in the array
48
+	 *                for templates that are generated.  If this is an empty array then it means no templates were
49
+	 *                generated which usually means there was an error.  Anything in the array with an empty value for
50
+	 *                `MTP_context` means that it was not a new generated template but just reactivated (which only
51
+	 *                happens for global templates that already exist in the database.
52
+	 * @throws EE_Error
53
+	 * @throws ReflectionException
54
+	 */
55
+	public static function generate_new_templates($messenger, $message_types, $GRP_ID = 0, $global = false)
56
+	{
57
+		// make sure message_type is an array.
58
+		$message_types = (array) $message_types;
59
+		$templates = array();
60
+
61
+		if (empty($messenger)) {
62
+			throw new EE_Error(esc_html__('We need a messenger to generate templates!', 'event_espresso'));
63
+		}
64
+
65
+		// if we STILL have empty $message_types then we need to generate an error message b/c we NEED message types to do the template files.
66
+		if (empty($message_types)) {
67
+			throw new EE_Error(esc_html__('We need at least one message type to generate templates!', 'event_espresso'));
68
+		}
69
+
70
+		EEH_MSG_Template::_set_autoloader();
71
+		foreach ($message_types as $message_type) {
72
+			// if this is global template generation.
73
+			if ($global) {
74
+				// let's attempt to get the GRP_ID for this combo IF GRP_ID is empty.
75
+				if (empty($GRP_ID)) {
76
+					$GRP_ID = EEM_Message_Template_Group::instance()->get_one(
77
+						array(
78
+							array(
79
+								'MTP_messenger'    => $messenger,
80
+								'MTP_message_type' => $message_type,
81
+								'MTP_is_global'    => true,
82
+							),
83
+						)
84
+					);
85
+					$GRP_ID = $GRP_ID instanceof EE_Message_Template_Group ? $GRP_ID->ID() : 0;
86
+				}
87
+				// First let's determine if we already HAVE global templates for this messenger and message_type combination.
88
+				//  If we do then NO generation!!
89
+				if (EEH_MSG_Template::already_generated($messenger, $message_type, $GRP_ID)) {
90
+					$templates[] = array(
91
+						'GRP_ID' => $GRP_ID,
92
+						'MTP_context' => '',
93
+					);
94
+					// we already have generated templates for this so let's go to the next message type.
95
+					continue;
96
+				}
97
+			}
98
+			$new_message_template_group = EEH_MSG_Template::create_new_templates($messenger, $message_type, $GRP_ID, $global);
99
+
100
+			if (! $new_message_template_group) {
101
+				continue;
102
+			}
103
+			$templates[] = $new_message_template_group;
104
+		}
105
+
106
+		return $templates;
107
+	}
108
+
109
+
110
+	/**
111
+	 * The purpose of this method is to determine if there are already generated templates in the database for the
112
+	 * given variables.
113
+	 *
114
+	 * @param string $messenger    messenger
115
+	 * @param string $message_type message type
116
+	 * @param int    $GRP_ID       GRP ID ( if a custom template) (if not provided then we're just doing global
117
+	 *                             template check)
118
+	 * @return bool                true = generated, false = hasn't been generated.
119
+	 * @throws EE_Error
120
+	 */
121
+	public static function already_generated($messenger, $message_type, $GRP_ID = 0)
122
+	{
123
+		EEH_MSG_Template::_set_autoloader();
124
+		// what method we use depends on whether we have an GRP_ID or not
125
+		$count = empty($GRP_ID)
126
+			? EEM_Message_Template::instance()->count(
127
+				array(
128
+					array(
129
+						'Message_Template_Group.MTP_messenger'    => $messenger,
130
+						'Message_Template_Group.MTP_message_type' => $message_type,
131
+						'Message_Template_Group.MTP_is_global'    => true
132
+					)
133
+				)
134
+			)
135
+			: EEM_Message_Template::instance()->count(array( array( 'GRP_ID' => $GRP_ID ) ));
136
+
137
+		return $count > 0;
138
+	}
139
+
140
+
141
+	/**
142
+	 * Updates all message templates matching the incoming messengers and message types to active status.
143
+	 *
144
+	 * @static
145
+	 * @param array $messenger_names    Messenger slug
146
+	 * @param array $message_type_names Message type slug
147
+	 * @return  int                         count of updated records.
148
+	 * @throws EE_Error
149
+	 */
150
+	public static function update_to_active($messenger_names, $message_type_names)
151
+	{
152
+		$messenger_names = is_array($messenger_names) ? $messenger_names : array( $messenger_names );
153
+		$message_type_names = is_array($message_type_names) ? $message_type_names : array( $message_type_names );
154
+		return EEM_Message_Template_Group::instance()->update(
155
+			array( 'MTP_is_active' => 1 ),
156
+			array(
157
+				array(
158
+					'MTP_messenger'     => array( 'IN', $messenger_names ),
159
+					'MTP_message_type'  => array( 'IN', $message_type_names )
160
+				)
161
+			)
162
+		);
163
+	}
164
+
165
+
166
+	/**
167
+	 * Updates all message template groups matching the incoming arguments to inactive status.
168
+	 *
169
+	 * @static
170
+	 * @param array $messenger_names    The messenger slugs.
171
+	 *                                  If empty then all templates matching the message types are marked inactive.
172
+	 *                                  Otherwise only templates matching the messengers and message types.
173
+	 * @param array $message_type_names The message type slugs.
174
+	 *                                  If empty then all templates matching the messengers are marked inactive.
175
+	 *                                  Otherwise only templates matching the messengers and message types.
176
+	 *
177
+	 * @return int  count of updated records.
178
+	 * @throws EE_Error
179
+	 */
180
+	public static function update_to_inactive($messenger_names = array(), $message_type_names = array())
181
+	{
182
+		return EEM_Message_Template_Group::instance()->deactivate_message_template_groups_for(
183
+			$messenger_names,
184
+			$message_type_names
185
+		);
186
+	}
187
+
188
+
189
+	/**
190
+	 * The purpose of this function is to return all installed message objects
191
+	 * (messengers and message type regardless of whether they are ACTIVE or not)
192
+	 *
193
+	 * @param string $type
194
+	 * @return array array consisting of installed messenger objects and installed message type objects.
195
+	 * @throws EE_Error
196
+	 * @throws ReflectionException
197
+	 * @deprecated 4.9.0
198
+	 * @static
199
+	 */
200
+	public static function get_installed_message_objects($type = 'all')
201
+	{
202
+		self::_set_autoloader();
203
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
204
+		return array(
205
+			'messenger' => $message_resource_manager->installed_messengers(),
206
+			'message_type' => $message_resource_manager->installed_message_types()
207
+		);
208
+	}
209
+
210
+
211
+	/**
212
+	 * This will return an array of shortcodes => labels from the
213
+	 * messenger and message_type objects associated with this
214
+	 * template.
215
+	 *
216
+	 * @param string $message_type
217
+	 * @param string $messenger
218
+	 * @param array  $fields                        What fields we're returning valid shortcodes for.
219
+	 *                                              If empty then we assume all fields are to be returned. Optional.
220
+	 * @param string $context                       What context we're going to return shortcodes for. Optional.
221
+	 * @param bool   $merged                        If TRUE then we don't return shortcodes indexed by field,
222
+	 *                                              but instead an array of the unique shortcodes for all the given (
223
+	 *                                              or all) fields. Optional.
224
+	 * @return array                                an array of shortcodes in the format
225
+	 *                                              array( '[shortcode] => 'label')
226
+	 *                                              OR
227
+	 *                                              FALSE if no shortcodes found.
228
+	 * @throws ReflectionException
229
+	 * @throws EE_Error*@since 4.3.0
230
+	 *
231
+	 */
232
+	public static function get_shortcodes(
233
+		$message_type,
234
+		$messenger,
235
+		$fields = array(),
236
+		$context = 'admin',
237
+		$merged = false
238
+	) {
239
+		$messenger_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $messenger)));
240
+		$mt_name = str_replace(' ', '_', ucwords(str_replace('_', ' ', $message_type)));
241
+		/** @var EE_Message_Resource_Manager $message_resource_manager */
242
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
243
+		// convert slug to object
244
+		$messenger = $message_resource_manager->get_messenger($messenger);
245
+
246
+		// if messenger isn't a EE_messenger resource then bail.
247
+		if (! $messenger instanceof EE_messenger) {
248
+			return array();
249
+		}
250
+
251
+		// validate class for getting our list of shortcodes
252
+		$classname = 'EE_Messages_' . $messenger_name . '_' . $mt_name . '_Validator';
253
+		if (! class_exists($classname)) {
254
+			$msg[] = esc_html__('The Validator class was unable to load', 'event_espresso');
255
+			$msg[] = sprintf(
256
+				esc_html__('The class name compiled was %s. Please check and make sure the spelling and case is correct for the class name and that there is an autoloader in place for this class', 'event_espresso'),
257
+				$classname
258
+			);
259
+			throw new EE_Error(implode('||', $msg));
260
+		}
261
+
262
+		/** @type EE_Messages_Validator $_VLD */
263
+		$_VLD = new $classname(array(), $context);
264
+		$valid_shortcodes = $_VLD->get_validators();
265
+
266
+		// let's make sure we're only getting the shortcode part of the validators
267
+		$shortcodes = array();
268
+		foreach ($valid_shortcodes as $field => $validators) {
269
+			$shortcodes[ $field ] = $validators['shortcodes'];
270
+		}
271
+		$valid_shortcodes = $shortcodes;
272
+
273
+		// if not all fields let's make sure we ONLY include the shortcodes for the specified fields.
274
+		if (! empty($fields)) {
275
+			$specified_shortcodes = array();
276
+			foreach ($fields as $field) {
277
+				if (isset($valid_shortcodes[ $field ])) {
278
+					$specified_shortcodes[ $field ] = $valid_shortcodes[ $field ];
279
+				}
280
+			}
281
+			$valid_shortcodes = $specified_shortcodes;
282
+		}
283
+
284
+		// if not merged then let's replace the fields with the localized fields
285
+		if (! $merged) {
286
+			// let's get all the fields for the set messenger so that we can get the localized label and use that in the returned array.
287
+			$field_settings = $messenger->get_template_fields();
288
+			$localized = array();
289
+			foreach ($valid_shortcodes as $field => $shortcodes) {
290
+				// get localized field label
291
+				if (isset($field_settings[ $field ])) {
292
+					// possible that this is used as a main field.
293
+					if (empty($field_settings[ $field ])) {
294
+						if (isset($field_settings['extra'][ $field ])) {
295
+							$_field = $field_settings['extra'][ $field ]['main']['label'];
296
+						} else {
297
+							$_field = $field;
298
+						}
299
+					} else {
300
+						$_field = $field_settings[ $field ]['label'];
301
+					}
302
+				} elseif (isset($field_settings['extra'])) {
303
+					// loop through extra "main fields" and see if any of their children have our field
304
+					foreach ($field_settings['extra'] as $fields) {
305
+						if (isset($fields[ $field ])) {
306
+							$_field = $fields[ $field ]['label'];
307
+						} else {
308
+							$_field = $field;
309
+						}
310
+					}
311
+				} else {
312
+					$_field = $field;
313
+				}
314
+				if (isset($_field)) {
315
+					$localized[ (string) $_field ] = $shortcodes;
316
+				}
317
+			}
318
+			$valid_shortcodes = $localized;
319
+		}
320
+
321
+		// if $merged then let's merge all the shortcodes into one list NOT indexed by field.
322
+		if ($merged) {
323
+			$merged_codes = array();
324
+			foreach ($valid_shortcodes as $shortcode) {
325
+				foreach ($shortcode as $code => $label) {
326
+					if (isset($merged_codes[ $code ])) {
327
+						continue;
328
+					} else {
329
+						$merged_codes[ $code ] = $label;
330
+					}
331
+				}
332
+			}
333
+			$valid_shortcodes = $merged_codes;
334
+		}
335
+
336
+		return $valid_shortcodes;
337
+	}
338
+
339
+
340
+	/**
341
+	 * Get Messenger object.
342
+	 *
343
+	 * @param string $messenger messenger slug for the messenger object we want to retrieve.
344
+	 * @return EE_messenger
345
+	 * @throws ReflectionException
346
+	 * @throws EE_Error*@since 4.3.0
347
+	 * @deprecated 4.9.0
348
+	 */
349
+	public static function messenger_obj($messenger)
350
+	{
351
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
352
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
353
+		return $Message_Resource_Manager->get_messenger($messenger);
354
+	}
355
+
356
+
357
+	/**
358
+	 * get Message type object
359
+	 *
360
+	 * @param string $message_type the slug for the message type object to retrieve
361
+	 * @return EE_message_type
362
+	 * @throws ReflectionException
363
+	 * @throws EE_Error*@since 4.3.0
364
+	 * @deprecated 4.9.0
365
+	 */
366
+	public static function message_type_obj($message_type)
367
+	{
368
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
369
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
370
+		return $Message_Resource_Manager->get_message_type($message_type);
371
+	}
372
+
373
+
374
+	/**
375
+	 * Given a message_type slug, will return whether that message type is active in the system or not.
376
+	 *
377
+	 * @since    4.3.0
378
+	 * @param string $message_type message type to check for.
379
+	 * @return boolean
380
+	 * @throws EE_Error
381
+	 * @throws ReflectionException
382
+	 */
383
+	public static function is_mt_active($message_type)
384
+	{
385
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
386
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
387
+		$active_mts = $Message_Resource_Manager->list_of_active_message_types();
388
+		return in_array($message_type, $active_mts);
389
+	}
390
+
391
+
392
+	/**
393
+	 * Given a messenger slug, will return whether that messenger is active in the system or not.
394
+	 *
395
+	 * @since    4.3.0
396
+	 *
397
+	 * @param string $messenger slug for messenger to check.
398
+	 * @return boolean
399
+	 * @throws EE_Error
400
+	 * @throws ReflectionException
401
+	 */
402
+	public static function is_messenger_active($messenger)
403
+	{
404
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
405
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
406
+		$active_messenger = $Message_Resource_Manager->get_active_messenger($messenger);
407
+		return $active_messenger instanceof EE_messenger;
408
+	}
409
+
410
+
411
+	/**
412
+	 * Used to return active messengers array stored in the wp options table.
413
+	 * If no value is present in the option then an empty array is returned.
414
+	 *
415
+	 * @deprecated 4.9
416
+	 * @since      4.3.1
417
+	 *
418
+	 * @return array
419
+	 * @throws EE_Error
420
+	 * @throws ReflectionException
421
+	 */
422
+	public static function get_active_messengers_in_db()
423
+	{
424
+		EE_Error::doing_it_wrong(
425
+			__METHOD__,
426
+			esc_html__('Please use EE_Message_Resource_Manager::get_active_messengers_option() instead.', 'event_espresso'),
427
+			'4.9.0'
428
+		);
429
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
430
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
431
+		return $Message_Resource_Manager->get_active_messengers_option();
432
+	}
433
+
434
+
435
+	/**
436
+	 * Used to update the active messengers array stored in the wp options table.
437
+	 *
438
+	 * @since      4.3.1
439
+	 * @deprecated 4.9.0
440
+	 *
441
+	 * @param array $data_to_save Incoming data to save.
442
+	 *
443
+	 * @return bool FALSE if not updated, TRUE if updated.
444
+	 * @throws EE_Error
445
+	 * @throws ReflectionException
446
+	 */
447
+	public static function update_active_messengers_in_db($data_to_save)
448
+	{
449
+		EE_Error::doing_it_wrong(
450
+			__METHOD__,
451
+			esc_html__('Please use EE_Message_Resource_Manager::update_active_messengers_option() instead.', 'event_espresso'),
452
+			'4.9.0'
453
+		);
454
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
455
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
456
+		return $Message_Resource_Manager->update_active_messengers_option($data_to_save);
457
+	}
458
+
459
+
460
+	/**
461
+	 * This does some validation of incoming params, determines what type of url is being prepped and returns the
462
+	 * appropriate url trigger
463
+	 *
464
+	 * @param EE_message_type $message_type
465
+	 * @param EE_Message $message
466
+	 * @param EE_Registration | null $registration  The registration object must be included if this
467
+	 *                                              is going to be a registration trigger url.
468
+	 * @param string $sending_messenger             The (optional) sending messenger for the url.
469
+	 *
470
+	 * @return string
471
+	 * @throws EE_Error
472
+	 */
473
+	public static function get_url_trigger(
474
+		EE_message_type $message_type,
475
+		EE_Message $message,
476
+		$registration = null,
477
+		$sending_messenger = ''
478
+	) {
479
+		// first determine if the url can be to the EE_Message object.
480
+		if (! $message_type->always_generate()) {
481
+			return EEH_MSG_Template::generate_browser_trigger($message);
482
+		}
483
+
484
+		// if $registration object is not valid then exit early because there's nothing that can be generated.
485
+		if (! $registration instanceof EE_Registration) {
486
+			throw new EE_Error(
487
+				esc_html__('Incoming value for registration is not a valid EE_Registration object.', 'event_espresso')
488
+			);
489
+		}
490
+
491
+		// validate given context
492
+		$contexts = $message_type->get_contexts();
493
+		if ($message->context() !== '' && ! isset($contexts[ $message->context() ])) {
494
+			throw new EE_Error(
495
+				sprintf(
496
+					esc_html__('The context %s is not a valid context for %s.', 'event_espresso'),
497
+					$message->context(),
498
+					get_class($message_type)
499
+				)
500
+			);
501
+		}
502
+
503
+		// valid sending messenger but only if sending messenger set.  Otherwise generating messenger is used.
504
+		if (! empty($sending_messenger)) {
505
+			$with_messengers = $message_type->with_messengers();
506
+			if (
507
+				! isset($with_messengers[ $message->messenger() ])
508
+				 || ! in_array($sending_messenger, $with_messengers[ $message->messenger() ])
509
+			) {
510
+				throw new EE_Error(
511
+					sprintf(
512
+						esc_html__(
513
+							'The given sending messenger string (%1$s) does not match a valid sending messenger with the %2$s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
514
+							'event_espresso'
515
+						),
516
+						$sending_messenger,
517
+						get_class($message_type)
518
+					)
519
+				);
520
+			}
521
+		} else {
522
+			$sending_messenger = $message->messenger();
523
+		}
524
+		return EEH_MSG_Template::generate_url_trigger(
525
+			$sending_messenger,
526
+			$message->messenger(),
527
+			$message->context(),
528
+			$message->message_type(),
529
+			$registration,
530
+			$message->GRP_ID()
531
+		);
532
+	}
533
+
534
+
535
+	/**
536
+	 * This returns the url for triggering a in browser view of a specific EE_Message object.
537
+	 * @param EE_Message $message
538
+	 * @return string.
539
+	 */
540
+	public static function generate_browser_trigger(EE_Message $message)
541
+	{
542
+		$query_args = array(
543
+			'ee' => 'msg_browser_trigger',
544
+			'token' => $message->MSG_token()
545
+		);
546
+		return apply_filters(
547
+			'FHEE__EEH_MSG_Template__generate_browser_trigger',
548
+			add_query_arg($query_args, site_url()),
549
+			$message
550
+		);
551
+	}
552
+
553
+
554
+
555
+
556
+
557
+
558
+	/**
559
+	 * This returns the url for triggering an in browser view of the error saved on the incoming message object.
560
+	 * @param EE_Message $message
561
+	 * @return string
562
+	 */
563
+	public static function generate_error_display_trigger(EE_Message $message)
564
+	{
565
+		return apply_filters(
566
+			'FHEE__EEH_MSG_Template__generate_error_display_trigger',
567
+			add_query_arg(
568
+				array(
569
+					'ee' => 'msg_browser_error_trigger',
570
+					'token' => $message->MSG_token()
571
+				),
572
+				site_url()
573
+			),
574
+			$message
575
+		);
576
+	}
577
+
578
+
579
+	/**
580
+	 * This generates a url trigger for the msg_url_trigger route using the given arguments
581
+	 *
582
+	 * @param string          $sending_messenger      The sending messenger slug.
583
+	 * @param string          $generating_messenger   The generating messenger slug.
584
+	 * @param string          $context                The context for the template.
585
+	 * @param string          $message_type           The message type slug
586
+	 * @param EE_Registration $registration
587
+	 * @param integer         $message_template_group id   The EE_Message_Template_Group ID for the template.
588
+	 * @param integer         $data_id                The id to the EE_Base_Class for getting the data used by the
589
+	 *                                                trigger.
590
+	 * @return string          The generated url.
591
+	 * @throws EE_Error
592
+	 */
593
+	public static function generate_url_trigger(
594
+		$sending_messenger,
595
+		$generating_messenger,
596
+		$context,
597
+		$message_type,
598
+		EE_Registration $registration,
599
+		$message_template_group,
600
+		$data_id = 0
601
+	) {
602
+		$query_args = array(
603
+			'ee' => 'msg_url_trigger',
604
+			'snd_msgr' => $sending_messenger,
605
+			'gen_msgr' => $generating_messenger,
606
+			'message_type' => $message_type,
607
+			'context' => $context,
608
+			'token' => $registration->reg_url_link(),
609
+			'GRP_ID' => $message_template_group,
610
+			'id' => $data_id
611
+			);
612
+		$url = add_query_arg($query_args, get_home_url());
613
+
614
+		// made it here so now we can just get the url and filter it.  Filtered globally and by message type.
615
+		return apply_filters(
616
+			'FHEE__EEH_MSG_Template__generate_url_trigger',
617
+			$url,
618
+			$sending_messenger,
619
+			$generating_messenger,
620
+			$context,
621
+			$message_type,
622
+			$registration,
623
+			$message_template_group,
624
+			$data_id
625
+		);
626
+	}
627
+
628
+
629
+
630
+
631
+	/**
632
+	 * Return the specific css for the action icon given.
633
+	 *
634
+	 * @param string $type  What action to return.
635
+	 * @return string[]
636
+	 * @since 4.9.0
637
+	 */
638
+	public static function get_message_action_icon($type)
639
+	{
640
+		$action_icons = self::get_message_action_icons();
641
+		return isset($action_icons[ $type ]) ? $action_icons[ $type ] : [];
642
+	}
643
+
644
+
645
+	/**
646
+	 * This is used for retrieving the css classes used for the icons representing message actions.
647
+	 *
648
+	 * @since 4.9.0
649
+	 *
650
+	 * @return array
651
+	 */
652
+	public static function get_message_action_icons()
653
+	{
654
+		return apply_filters(
655
+			'FHEE__EEH_MSG_Template__message_action_icons',
656
+			array(
657
+				'view' => array(
658
+					'label' => esc_html__('View Message', 'event_espresso'),
659
+					'css_class' => 'dashicons dashicons-welcome-view-site',
660
+				),
661
+				'error' => array(
662
+					'label' => esc_html__('View Error Message', 'event_espresso'),
663
+					'css_class' => 'dashicons dashicons-info',
664
+				),
665
+				'see_notifications_for' => array(
666
+					'label' => esc_html__('View Related Messages', 'event_espresso'),
667
+					'css_class' => 'dashicons dashicons-megaphone',
668
+				),
669
+				'generate_now' => array(
670
+					'label' => esc_html__('Generate the message now.', 'event_espresso'),
671
+					'css_class' => 'dashicons dashicons-admin-tools',
672
+				),
673
+				'send_now' => array(
674
+					'label' => esc_html__('Send Immediately', 'event_espresso'),
675
+					'css_class' => 'dashicons dashicons-controls-forward',
676
+				),
677
+				'queue_for_resending' => array(
678
+					'label' => esc_html__('Queue for Resending', 'event_espresso'),
679
+					'css_class' => 'dashicons dashicons-controls-repeat',
680
+				),
681
+				'view_transaction' => array(
682
+					'label' => esc_html__('View related Transaction', 'event_espresso'),
683
+					'css_class' => 'dashicons dashicons-cart',
684
+				)
685
+			)
686
+		);
687
+	}
688
+
689
+
690
+	/**
691
+	 * This returns the url for a given action related to EE_Message.
692
+	 *
693
+	 * @param string     $type         What type of action to return the url for.
694
+	 * @param EE_Message $message      Required for generating the correct url for some types.
695
+	 * @param array      $query_params Any additional query params to be included with the generated url.
696
+	 *
697
+	 * @return string
698
+	 * @throws EE_Error
699
+	 * @throws ReflectionException
700
+	 * @since 4.9.0
701
+	 *
702
+	 */
703
+	public static function get_message_action_url($type, EE_Message $message = null, $query_params = array())
704
+	{
705
+		$action_urls = self::get_message_action_urls($message, $query_params);
706
+		return isset($action_urls[ $type ])  ? $action_urls[ $type ] : '';
707
+	}
708
+
709
+
710
+	/**
711
+	 * This returns all the current urls for EE_Message actions.
712
+	 *
713
+	 * @since 4.9.0
714
+	 *
715
+	 * @param EE_Message $message      The EE_Message object required to generate correct urls for some types.
716
+	 * @param array      $query_params Any additional query_params to be included with the generated url.
717
+	 *
718
+	 * @return array
719
+	 * @throws EE_Error
720
+	 * @throws ReflectionException
721
+	 */
722
+	public static function get_message_action_urls(EE_Message $message = null, $query_params = array())
723
+	{
724
+		EE_Registry::instance()->load_helper('URL');
725
+		// if $message is not an instance of EE_Message then let's just do a dummy.
726
+		$message = empty($message) ? EE_Message_Factory::create() : $message;
727
+		$action_urls =  apply_filters(
728
+			'FHEE__EEH_MSG_Template__get_message_action_url',
729
+			array(
730
+				'view' => EEH_MSG_Template::generate_browser_trigger($message),
731
+				'error' => EEH_MSG_Template::generate_error_display_trigger($message),
732
+				'see_notifications_for' => EEH_URL::add_query_args_and_nonce(
733
+					array_merge(
734
+						array(
735
+							'page' => 'espresso_messages',
736
+							'action' => 'default',
737
+							'filterby' => 1,
738
+						),
739
+						$query_params
740
+					),
741
+					admin_url('admin.php')
742
+				),
743
+				'generate_now' => EEH_URL::add_query_args_and_nonce(
744
+					array(
745
+						'page' => 'espresso_messages',
746
+						'action' => 'generate_now',
747
+						'MSG_ID' => $message->ID()
748
+					),
749
+					admin_url('admin.php')
750
+				),
751
+				'send_now' => EEH_URL::add_query_args_and_nonce(
752
+					array(
753
+						'page' => 'espresso_messages',
754
+						'action' => 'send_now',
755
+						'MSG_ID' => $message->ID()
756
+					),
757
+					admin_url('admin.php')
758
+				),
759
+				'queue_for_resending' => EEH_URL::add_query_args_and_nonce(
760
+					array(
761
+						'page' => 'espresso_messages',
762
+						'action' => 'queue_for_resending',
763
+						'MSG_ID' => $message->ID()
764
+					),
765
+					admin_url('admin.php')
766
+				),
767
+			)
768
+		);
769
+		if (
770
+			$message->TXN_ID() > 0
771
+			&& EE_Registry::instance()->CAP->current_user_can(
772
+				'ee_read_transaction',
773
+				'espresso_transactions_default',
774
+				$message->TXN_ID()
775
+			)
776
+		) {
777
+			$action_urls['view_transaction'] = EEH_URL::add_query_args_and_nonce(
778
+				array(
779
+					'page' => 'espresso_transactions',
780
+					'action' => 'view_transaction',
781
+					'TXN_ID' => $message->TXN_ID()
782
+				),
783
+				admin_url('admin.php')
784
+			);
785
+		} else {
786
+			$action_urls['view_transaction'] = '';
787
+		}
788
+		return $action_urls;
789
+	}
790
+
791
+
792
+	/**
793
+	 * This returns a generated link html including the icon used for the action link for EE_Message actions.
794
+	 *
795
+	 * @param string          $type         What type of action the link is for (if invalid type is passed in then an
796
+	 *                                      empty string is returned)
797
+	 * @param EE_Message|null $message      The EE_Message object (required for some actions to generate correctly)
798
+	 * @param array           $query_params Any extra query params to include in the generated link.
799
+	 *
800
+	 * @return string
801
+	 * @throws EE_Error
802
+	 * @throws ReflectionException
803
+	 * @since 4.9.0
804
+	 *
805
+	 */
806
+	public static function get_message_action_link($type, EE_Message $message = null, $query_params = array())
807
+	{
808
+		$url = EEH_MSG_Template::get_message_action_url($type, $message, $query_params);
809
+		$icon_css = EEH_MSG_Template::get_message_action_icon($type);
810
+		$title = isset($icon_css['label']) ? 'title="' . $icon_css['label'] . '"' : '';
811
+
812
+		if (empty($url) || empty($icon_css) || ! isset($icon_css['css_class'])) {
813
+			return '';
814
+		}
815
+
816
+		$icon_css['css_class'] .= esc_attr(
817
+			apply_filters(
818
+				'FHEE__EEH_MSG_Template__get_message_action_link__icon_css_class',
819
+				' js-ee-message-action-link ee-message-action-link-' . $type,
820
+				$type,
821
+				$message,
822
+				$query_params
823
+			)
824
+		);
825
+
826
+		return '<a href="' . $url . '" ' . $title . '><span class="' . esc_attr($icon_css['css_class']) . '"></span></a>';
827
+	}
828
+
829
+
830
+
831
+
832
+
833
+	/**
834
+	 * This returns an array with keys as reg statuses and values as the corresponding message type slug (filtered).
835
+	 *
836
+	 * @since 4.9.0
837
+	 * @return array
838
+	 */
839
+	public static function reg_status_to_message_type_array()
840
+	{
841
+		return (array) apply_filters(
842
+			'FHEE__EEH_MSG_Template__reg_status_to_message_type_array',
843
+			array(
844
+				EEM_Registration::status_id_approved => 'registration',
845
+				EEM_Registration::status_id_pending_payment => 'pending_approval',
846
+				EEM_Registration::status_id_not_approved => 'not_approved_registration',
847
+				EEM_Registration::status_id_cancelled => 'cancelled_registration',
848
+				EEM_Registration::status_id_declined => 'declined_registration'
849
+			)
850
+		);
851
+	}
852
+
853
+
854
+
855
+
856
+	/**
857
+	 * This returns the corresponding registration message type slug to the given reg status. If there isn't a
858
+	 * match, then returns an empty string.
859
+	 *
860
+	 * @since 4.9.0
861
+	 * @param $reg_status
862
+	 * @return string
863
+	 */
864
+	public static function convert_reg_status_to_message_type($reg_status)
865
+	{
866
+		$reg_status_array = self::reg_status_to_message_type_array();
867
+		return isset($reg_status_array[ $reg_status ]) ? $reg_status_array[ $reg_status ] : '';
868
+	}
869
+
870
+
871
+	/**
872
+	 * This returns an array with keys as payment stati and values as the corresponding message type slug (filtered).
873
+	 *
874
+	 * @since 4.9.0
875
+	 * @return array
876
+	 */
877
+	public static function payment_status_to_message_type_array()
878
+	{
879
+		return (array) apply_filters(
880
+			'FHEE__EEH_MSG_Template__payment_status_to_message_type_array',
881
+			array(
882
+				EEM_Payment::status_id_approved => 'payment',
883
+				EEM_Payment::status_id_pending => 'payment_pending',
884
+				EEM_Payment::status_id_cancelled => 'payment_cancelled',
885
+				EEM_Payment::status_id_declined => 'payment_declined',
886
+				EEM_Payment::status_id_failed => 'payment_failed'
887
+			)
888
+		);
889
+	}
890
+
891
+
892
+
893
+
894
+	/**
895
+	 * This returns the corresponding payment message type slug to the given payment status. If there isn't a match then
896
+	 * an empty string is returned
897
+	 *
898
+	 * @since 4.9.0
899
+	 * @param $payment_status
900
+	 * @return string
901
+	 */
902
+	public static function convert_payment_status_to_message_type($payment_status)
903
+	{
904
+		$payment_status_array = self::payment_status_to_message_type_array();
905
+		return isset($payment_status_array[ $payment_status ]) ? $payment_status_array[ $payment_status ] : '';
906
+	}
907
+
908
+
909
+	/**
910
+	 * This is used to retrieve the template pack for the given name.
911
+	 *
912
+	 * @param string $template_pack_name  should match the set `dbref` property value on the EE_Messages_Template_Pack.
913
+	 *
914
+	 * @return EE_Messages_Template_Pack
915
+	 */
916
+	public static function get_template_pack($template_pack_name)
917
+	{
918
+		if (! self::$_template_pack_collection instanceof EE_Object_Collection) {
919
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
920
+		}
921
+
922
+		// first see if in collection already
923
+		$template_pack = self::$_template_pack_collection->get_by_name($template_pack_name);
924
+
925
+		if ($template_pack instanceof EE_Messages_Template_Pack) {
926
+			return $template_pack;
927
+		}
928
+
929
+		// nope...let's get it.
930
+		// not set yet so let's attempt to get it.
931
+		$pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
932
+			' ',
933
+			'_',
934
+			ucwords(
935
+				str_replace('_', ' ', $template_pack_name)
936
+			)
937
+		);
938
+		if (! class_exists($pack_class_name) && $template_pack_name !== 'default') {
939
+			return self::get_template_pack('default');
940
+		} else {
941
+			$template_pack = new $pack_class_name();
942
+			self::$_template_pack_collection->add($template_pack);
943
+			return $template_pack;
944
+		}
945
+	}
946
+
947
+
948
+
949
+
950
+	/**
951
+	 * Globs template packs installed in core and returns the template pack collection with all installed template packs
952
+	 * in it.
953
+	 *
954
+	 * @since 4.9.0
955
+	 *
956
+	 * @return EE_Messages_Template_Pack_Collection
957
+	 */
958
+	public static function get_template_pack_collection()
959
+	{
960
+		$new_collection = false;
961
+		if (! self::$_template_pack_collection instanceof EE_Messages_Template_Pack_Collection) {
962
+			self::$_template_pack_collection = new EE_Messages_Template_Pack_Collection();
963
+			$new_collection = true;
964
+		}
965
+
966
+		// glob the defaults directory for messages
967
+		$templates = glob(EE_LIBRARIES . 'messages/defaults/*', GLOB_ONLYDIR);
968
+		foreach ($templates as $template_path) {
969
+			// grab folder name
970
+			$template = basename($template_path);
971
+
972
+			if (! $new_collection) {
973
+				// already have it?
974
+				if (self::$_template_pack_collection->get_by_name($template) instanceof EE_Messages_Template_Pack) {
975
+					continue;
976
+				}
977
+			}
978
+
979
+			// setup classname.
980
+			$template_pack_class_name = 'EE_Messages_Template_Pack_' . str_replace(
981
+				' ',
982
+				'_',
983
+				ucwords(
984
+					str_replace(
985
+						'_',
986
+						' ',
987
+						$template
988
+					)
989
+				)
990
+			);
991
+			if (! class_exists($template_pack_class_name)) {
992
+				continue;
993
+			}
994
+			self::$_template_pack_collection->add(new $template_pack_class_name());
995
+		}
996
+
997
+		/**
998
+		 * Filter for plugins to add in any additional template packs
999
+		 * Note the filter name here is for backward compat, this used to be found in EED_Messages.
1000
+		 */
1001
+		$additional_template_packs = apply_filters('FHEE__EED_Messages__get_template_packs__template_packs', array());
1002
+		foreach ((array) $additional_template_packs as $template_pack) {
1003
+			if (
1004
+				self::$_template_pack_collection->get_by_name(
1005
+					$template_pack->dbref
1006
+				) instanceof EE_Messages_Template_Pack
1007
+			) {
1008
+				continue;
1009
+			}
1010
+			self::$_template_pack_collection->add($template_pack);
1011
+		}
1012
+		return self::$_template_pack_collection;
1013
+	}
1014
+
1015
+
1016
+	/**
1017
+	 * This is a wrapper for the protected _create_new_templates function
1018
+	 *
1019
+	 * @param string $messenger_name
1020
+	 * @param string $message_type_name message type that the templates are being created for
1021
+	 * @param int    $GRP_ID
1022
+	 * @param bool   $global
1023
+	 * @return array
1024
+	 * @throws EE_Error
1025
+	 * @throws ReflectionException
1026
+	 */
1027
+	public static function create_new_templates($messenger_name, $message_type_name, $GRP_ID = 0, $global = false)
1028
+	{
1029
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1030
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1031
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1032
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1033
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type, $global)) {
1034
+			return array();
1035
+		}
1036
+		// whew made it this far!  Okay, let's go ahead and create the templates then
1037
+		return EEH_MSG_Template::_create_new_templates($messenger, $message_type, $GRP_ID, $global);
1038
+	}
1039
+
1040
+
1041
+	/**
1042
+	 * @param EE_messenger     $messenger
1043
+	 * @param EE_message_type  $message_type
1044
+	 * @param                  $GRP_ID
1045
+	 * @param                  $global
1046
+	 * @return array|mixed
1047
+	 * @throws EE_Error
1048
+	 * @throws ReflectionException
1049
+	 */
1050
+	protected static function _create_new_templates(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID, $global)
1051
+	{
1052
+		// if we're creating a custom template then we don't need to use the defaults class
1053
+		if (! $global) {
1054
+			return EEH_MSG_Template::_create_custom_template_group($messenger, $message_type, $GRP_ID);
1055
+		}
1056
+		/** @type EE_Messages_Template_Defaults $Message_Template_Defaults */
1057
+		$Message_Template_Defaults = EE_Registry::factory(
1058
+			'EE_Messages_Template_Defaults',
1059
+			array( $messenger, $message_type, $GRP_ID )
1060
+		);
1061
+		// generate templates
1062
+		$success = $Message_Template_Defaults->create_new_templates();
1063
+
1064
+		// if creating the template failed.  Then we should deactivate the related message_type for the messenger because
1065
+		// its not active if it doesn't have a template.  Note this is only happening for GLOBAL template creation
1066
+		// attempts.
1067
+		if (! $success) {
1068
+			/** @var EE_Message_Resource_Manager $message_resource_manager */
1069
+			$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1070
+			$message_resource_manager->deactivate_message_type_for_messenger($message_type->name, $messenger->name);
1071
+		}
1072
+
1073
+		/**
1074
+		 * $success is in an array in the following format
1075
+		 * array(
1076
+		 *    'GRP_ID' => $new_grp_id,
1077
+		 *    'MTP_context' => $first_context_in_new_templates,
1078
+		 * )
1079
+		 */
1080
+		return $success;
1081
+	}
1082
+
1083
+
1084
+	/**
1085
+	 * This creates a custom template using the incoming GRP_ID
1086
+	 *
1087
+	 * @param EE_messenger    $messenger
1088
+	 * @param EE_message_type $message_type
1089
+	 * @param int             $GRP_ID           GRP_ID for the template_group being used as the base
1090
+	 * @return  array $success              This will be an array in the format:
1091
+	 *                                          array(
1092
+	 *                                          'GRP_ID' => $new_grp_id,
1093
+	 *                                          'MTP_context' => $first_context_in_created_template
1094
+	 *                                          )
1095
+	 * @throws EE_Error
1096
+	 * @throws ReflectionException
1097
+	 * @access private
1098
+	 */
1099
+	private static function _create_custom_template_group(EE_messenger $messenger, EE_message_type $message_type, $GRP_ID)
1100
+	{
1101
+		// defaults
1102
+		$success = array( 'GRP_ID' => null, 'MTP_context' => '' );
1103
+		// get the template group to use as a template from the db.  If $GRP_ID is empty then we'll assume the base will be the global template matching the messenger and message type.
1104
+		$Message_Template_Group = empty($GRP_ID)
1105
+			? EEM_Message_Template_Group::instance()->get_one(
1106
+				array(
1107
+					array(
1108
+						'MTP_messenger'    => $messenger->name,
1109
+						'MTP_message_type' => $message_type->name,
1110
+						'MTP_is_global'    => true
1111
+					)
1112
+				)
1113
+			)
1114
+			: EEM_Message_Template_Group::instance()->get_one_by_ID($GRP_ID);
1115
+		// if we don't have a mtg at this point then we need to bail.
1116
+		if (! $Message_Template_Group instanceof EE_Message_Template_Group) {
1117
+			EE_Error::add_error(
1118
+				sprintf(
1119
+					esc_html__(
1120
+						'Something went wrong with generating the custom template from this group id: %s.  This usually happens when there is no matching message template group in the db.',
1121
+						'event_espresso'
1122
+					),
1123
+					$GRP_ID
1124
+				),
1125
+				__FILE__,
1126
+				__FUNCTION__,
1127
+				__LINE__
1128
+			);
1129
+			return $success;
1130
+		}
1131
+		// let's get all the related message_template objects for this group.
1132
+		$message_templates = $Message_Template_Group->message_templates();
1133
+		// now we have what we need to setup the new template
1134
+		$new_mtg = clone $Message_Template_Group;
1135
+		$new_mtg->set('GRP_ID', 0);
1136
+		$new_mtg->set('MTP_is_global', false);
1137
+
1138
+		/** @var RequestInterface $request */
1139
+		$request = LoaderFactory::getLoader()->getShared(RequestInterface::class);
1140
+		$template_name = $request->isAjax() && $request->requestParamIsSet('templateName')
1141
+			? $request->getRequestParam('templateName')
1142
+			: esc_html__('New Custom Template', 'event_espresso');
1143
+		$template_description = $request->isAjax() && $request->requestParamIsSet('templateDescription')
1144
+			? $request->getRequestParam('templateDescription')
1145
+			: sprintf(
1146
+				esc_html__(
1147
+					'This is a custom template that was created for the %s messenger and %s message type.',
1148
+					'event_espresso'
1149
+				),
1150
+				$new_mtg->messenger_obj()->label['singular'],
1151
+				$new_mtg->message_type_obj()->label['singular']
1152
+			);
1153
+		$new_mtg->set('MTP_name', $template_name);
1154
+		$new_mtg->set('MTP_description', $template_description);
1155
+		// remove ALL relations on this template group so they don't get saved!
1156
+		$new_mtg->_remove_relations('Message_Template');
1157
+		$new_mtg->save();
1158
+		$success['GRP_ID'] = $new_mtg->ID();
1159
+		$success['template_name'] = $template_name;
1160
+		// add new message templates and add relation to.
1161
+		foreach ($message_templates as $message_template) {
1162
+			if (! $message_template instanceof EE_Message_Template) {
1163
+				continue;
1164
+			}
1165
+			$new_message_template = clone $message_template;
1166
+			$new_message_template->set('MTP_ID', 0);
1167
+			$new_message_template->set('GRP_ID', $new_mtg->ID()); // relation
1168
+			$new_message_template->save();
1169
+			if (empty($success['MTP_context']) && $new_message_template->get('MTP_context') !== 'admin') {
1170
+				$success['MTP_context'] = $new_message_template->get('MTP_context');
1171
+			}
1172
+		}
1173
+		return $success;
1174
+	}
1175
+
1176
+
1177
+	/**
1178
+	 * message_type_has_active_templates_for_messenger
1179
+	 *
1180
+	 * @param EE_messenger    $messenger
1181
+	 * @param EE_message_type $message_type
1182
+	 * @param bool            $global
1183
+	 * @return bool
1184
+	 * @throws EE_Error
1185
+	 */
1186
+	public static function message_type_has_active_templates_for_messenger(
1187
+		EE_messenger $messenger,
1188
+		EE_message_type $message_type,
1189
+		$global = false
1190
+	) {
1191
+		// is given message_type valid for given messenger (if this is not a global save)
1192
+		if ($global) {
1193
+			return true;
1194
+		}
1195
+		$active_templates = EEM_Message_Template_Group::instance()->count(
1196
+			array(
1197
+				array(
1198
+					'MTP_is_active'    => true,
1199
+					'MTP_messenger'    => $messenger->name,
1200
+					'MTP_message_type' => $message_type->name
1201
+				)
1202
+			)
1203
+		);
1204
+		if ($active_templates > 0) {
1205
+			return true;
1206
+		}
1207
+		EE_Error::add_error(
1208
+			sprintf(
1209
+				esc_html__(
1210
+					'The %1$s message type is not registered with the %2$s messenger. Please visit the Messenger activation page to assign this message type first if you want to use it.',
1211
+					'event_espresso'
1212
+				),
1213
+				$message_type->name,
1214
+				$messenger->name
1215
+			),
1216
+			__FILE__,
1217
+			__FUNCTION__,
1218
+			__LINE__
1219
+		);
1220
+		return false;
1221
+	}
1222
+
1223
+
1224
+	/**
1225
+	 * get_fields
1226
+	 * This takes a given messenger and message type and returns all the template fields indexed by context (and with field type).
1227
+	 *
1228
+	 * @param string $messenger_name    name of EE_messenger
1229
+	 * @param string $message_type_name name of EE_message_type
1230
+	 * @return array
1231
+	 * @throws EE_Error
1232
+	 * @throws ReflectionException
1233
+	 */
1234
+	public static function get_fields($messenger_name, $message_type_name)
1235
+	{
1236
+		$template_fields = array();
1237
+		/** @type EE_Message_Resource_Manager $Message_Resource_Manager */
1238
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1239
+		$messenger = $Message_Resource_Manager->valid_messenger($messenger_name);
1240
+		$message_type = $Message_Resource_Manager->valid_message_type($message_type_name);
1241
+		if (! EEH_MSG_Template::message_type_has_active_templates_for_messenger($messenger, $message_type)) {
1242
+			return array();
1243
+		}
1244
+
1245
+		$excluded_fields_for_messenger = $message_type->excludedFieldsForMessenger($messenger_name);
1246
+
1247
+		// okay now let's assemble an array with the messenger template fields added to the message_type contexts.
1248
+		foreach ($message_type->get_contexts() as $context => $details) {
1249
+			foreach ($messenger->get_template_fields() as $field => $value) {
1250
+				if (in_array($field, $excluded_fields_for_messenger, true)) {
1251
+					continue;
1252
+				}
1253
+				$template_fields[ $context ][ $field ] = $value;
1254
+			}
1255
+		}
1256
+		if (empty($template_fields)) {
1257
+			EE_Error::add_error(
1258
+				esc_html__('Something went wrong and we couldn\'t get any templates assembled', 'event_espresso'),
1259
+				__FILE__,
1260
+				__FUNCTION__,
1261
+				__LINE__
1262
+			);
1263
+			return array();
1264
+		}
1265
+		return $template_fields;
1266
+	}
1267 1267
 }
Please login to merge, or discard this patch.
core/services/request/sanitizers/AllowedTags.php 1 patch
Indentation   +280 added lines, -280 removed lines patch added patch discarded remove patch
@@ -13,284 +13,284 @@
 block discarded – undo
13 13
 class AllowedTags
14 14
 {
15 15
 
16
-    /**
17
-     * @var array[]
18
-     */
19
-    private static $attributes = [
20
-        'accept-charset'    => 1,
21
-        'action'            => 1,
22
-        'alt'               => 1,
23
-        'allow'             => 1,
24
-        'allowfullscreen'   => 1,
25
-        'align'             => 1,
26
-        'aria-*'            => 1,
27
-        'autocomplete'      => 1,
28
-        'bgcolor'           => 1,
29
-        'border'            => 1,
30
-        'cellpadding'       => 1,
31
-        'cellspacing'       => 1,
32
-        'checked'           => 1,
33
-        'class'             => 1,
34
-        'cols'              => 1,
35
-        'content'           => 1,
36
-        'data-*'            => 1,
37
-        'dir'               => 1,
38
-        'disabled'          => 1,
39
-        'enctype'           => 1,
40
-        'for'               => 1,
41
-        'frameborder'       => 1,
42
-        'height'            => 1,
43
-        'href'              => 1,
44
-        'id'                => 1,
45
-        'itemprop'          => 1,
46
-        'itemscope'         => 1,
47
-        'itemtype'          => 1,
48
-        'label'             => 1,
49
-        'lang'              => 1,
50
-        'leftmargin'        => 1,
51
-        'marginheight'      => 1,
52
-        'marginwidth'       => 1,
53
-        'max'               => 1,
54
-        'maxlength'         => 1,
55
-        'media'             => 1,
56
-        'method'            => 1,
57
-        'min'               => 1,
58
-        'multiple'          => 1,
59
-        'name'              => 1,
60
-        'novalidate'        => 1,
61
-        'placeholder'       => 1,
62
-        'property'          => 1,
63
-        'readonly'          => 1,
64
-        'rel'               => 1,
65
-        'required'          => 1,
66
-        'rows'              => 1,
67
-        'selected'          => 1,
68
-        'src'               => 1,
69
-        'size'              => 1,
70
-        'style'             => 1,
71
-        'step'              => 1,
72
-        'tabindex'          => 1,
73
-        'target'            => 1,
74
-        'title'             => 1,
75
-        'topmargin'         => 1,
76
-        'type'              => 1,
77
-        'value'             => 1,
78
-        'width'             => 1,
79
-    ];
80
-
81
-
82
-    /**
83
-     * @var array
84
-     */
85
-    private static $tags = [
86
-        'a',
87
-        'abbr',
88
-        'b',
89
-        'br',
90
-        'code',
91
-        'div',
92
-        'em',
93
-        'h1',
94
-        'h2',
95
-        'h3',
96
-        'h4',
97
-        'h5',
98
-        'h6',
99
-        'hr',
100
-        'i',
101
-        'img',
102
-        'li',
103
-        'ol',
104
-        'p',
105
-        'pre',
106
-        'small',
107
-        'span',
108
-        'strong',
109
-        'table',
110
-        'td',
111
-        'tr',
112
-        'ul',
113
-    ];
114
-
115
-
116
-    /**
117
-     * @var array
118
-     */
119
-    private static $allowed_tags;
120
-
121
-
122
-    /**
123
-     * @var array
124
-     */
125
-    private static $allowed_with_embed_tags;
126
-
127
-
128
-    /**
129
-     * @var array
130
-     */
131
-    private static $allowed_with_form_tags;
132
-
133
-
134
-    /**
135
-     * @var array
136
-     */
137
-    private static $allowed_with_script_and_style_tags;
138
-
139
-    /**
140
-     * @var array
141
-     */
142
-    private static $allowed_with_full_tags;
143
-
144
-
145
-    /**
146
-     * merges additional tags and attributes into the WP post tags
147
-     */
148
-    private static function initializeAllowedTags()
149
-    {
150
-        $allowed_post_tags = wp_kses_allowed_html('post');
151
-        $allowed_tags = [];
152
-        foreach (AllowedTags::$tags as $tag) {
153
-            $allowed_tags[ $tag ] = AllowedTags::$attributes;
154
-        }
155
-        AllowedTags::$allowed_tags = array_merge_recursive($allowed_post_tags, $allowed_tags);
156
-    }
157
-
158
-
159
-    /**
160
-     * merges embed tags and attributes into the EE all tags
161
-     */
162
-    private static function initializeWithEmbedTags()
163
-    {
164
-        $all_tags = AllowedTags::getAllowedTags();
165
-        $embed_tags = [
166
-            'iframe' => AllowedTags::$attributes
167
-        ];
168
-        AllowedTags::$allowed_with_embed_tags = array_merge_recursive($all_tags, $embed_tags);
169
-    }
170
-
171
-
172
-    /**
173
-     * merges form tags and attributes into the EE all tags
174
-     */
175
-    private static function initializeWithFormTags()
176
-    {
177
-        $all_tags = AllowedTags::getAllowedTags();
178
-        $form_tags = [
179
-            'form'     => AllowedTags::$attributes,
180
-            'label'    => AllowedTags::$attributes,
181
-            'input'    => AllowedTags::$attributes,
182
-            'select'   => AllowedTags::$attributes,
183
-            'option'   => AllowedTags::$attributes,
184
-            'optgroup' => AllowedTags::$attributes,
185
-            'textarea' => AllowedTags::$attributes,
186
-            'button'   => AllowedTags::$attributes,
187
-            'fieldset' => AllowedTags::$attributes,
188
-            'output'   => AllowedTags::$attributes,
189
-        ];
190
-        AllowedTags::$allowed_with_form_tags = array_merge_recursive($all_tags, $form_tags);
191
-    }
192
-
193
-
194
-    /**
195
-     * merges form script and style tags and attributes into the EE all tags
196
-     */
197
-    private static function initializeWithScriptAndStyleTags()
198
-    {
199
-        $all_tags = AllowedTags::getAllowedTags();
200
-        $script_and_style_tags = [
201
-            'script'   => AllowedTags::$attributes,
202
-            'style'    => AllowedTags::$attributes,
203
-            'link'     => AllowedTags::$attributes,
204
-            'noscript' => AllowedTags::$attributes,
205
-        ];
206
-        AllowedTags::$allowed_with_script_and_style_tags = array_merge_recursive($all_tags, $script_and_style_tags);
207
-    }
208
-
209
-    /**
210
-     * merges all head and body tags and attributes into the EE all tags
211
-     */
212
-    private static function initializeWithFullTags()
213
-    {
214
-        $all_tags = AllowedTags::getAllowedTags();
215
-        $full_tags = [
216
-            'script'    => AllowedTags::$attributes,
217
-            'style'     => AllowedTags::$attributes,
218
-            'link'      => AllowedTags::$attributes,
219
-            'title'     => AllowedTags::$attributes,
220
-            'meta'      => AllowedTags::$attributes,
221
-            'iframe'    => AllowedTags::$attributes,
222
-            'form'      => AllowedTags::$attributes,
223
-            'label'     => AllowedTags::$attributes,
224
-            'input'     => AllowedTags::$attributes,
225
-            'select'    => AllowedTags::$attributes,
226
-            'option'    => AllowedTags::$attributes,
227
-            'optgroup'  => AllowedTags::$attributes,
228
-            'textarea'  => AllowedTags::$attributes,
229
-            'button'    => AllowedTags::$attributes,
230
-            'fieldset'  => AllowedTags::$attributes,
231
-            'output'    => AllowedTags::$attributes,
232
-            'noscript'  => AllowedTags::$attributes,
233
-        ];
234
-        AllowedTags::$allowed_with_full_tags = array_merge_recursive($all_tags, $full_tags);
235
-    }
236
-
237
-
238
-    /**
239
-     * @return array[]
240
-     */
241
-    public static function getAllowedTags()
242
-    {
243
-        if (empty(AllowedTags::$allowed_tags)) {
244
-            AllowedTags::initializeAllowedTags();
245
-        }
246
-        return AllowedTags::$allowed_tags;
247
-    }
248
-
249
-
250
-    /**
251
-     * @return array[]
252
-     */
253
-    public static function getWithEmbedTags()
254
-    {
255
-        if (empty(AllowedTags::$allowed_with_embed_tags)) {
256
-            AllowedTags::initializeWithEmbedTags();
257
-        }
258
-        return AllowedTags::$allowed_with_embed_tags;
259
-    }
260
-
261
-
262
-    /**
263
-     * @return array[]
264
-     */
265
-    public static function getWithFormTags()
266
-    {
267
-        if (empty(AllowedTags::$allowed_with_form_tags)) {
268
-            AllowedTags::initializeWithFormTags();
269
-        }
270
-        return AllowedTags::$allowed_with_form_tags;
271
-    }
272
-
273
-
274
-    /**
275
-     * @return array[]
276
-     */
277
-    public static function getWithScriptAndStyleTags()
278
-    {
279
-        if (empty(AllowedTags::$allowed_with_script_and_style_tags)) {
280
-            AllowedTags::initializeWithScriptAndStyleTags();
281
-        }
282
-        return AllowedTags::$allowed_with_script_and_style_tags;
283
-    }
284
-
285
-
286
-    /**
287
-     * @return array[]
288
-     */
289
-    public static function getWithFullTags()
290
-    {
291
-        if (empty(AllowedTags::$allowed_with_full_tags)) {
292
-            AllowedTags::initializeWithFullTags();
293
-        }
294
-        return AllowedTags::$allowed_with_full_tags;
295
-    }
16
+	/**
17
+	 * @var array[]
18
+	 */
19
+	private static $attributes = [
20
+		'accept-charset'    => 1,
21
+		'action'            => 1,
22
+		'alt'               => 1,
23
+		'allow'             => 1,
24
+		'allowfullscreen'   => 1,
25
+		'align'             => 1,
26
+		'aria-*'            => 1,
27
+		'autocomplete'      => 1,
28
+		'bgcolor'           => 1,
29
+		'border'            => 1,
30
+		'cellpadding'       => 1,
31
+		'cellspacing'       => 1,
32
+		'checked'           => 1,
33
+		'class'             => 1,
34
+		'cols'              => 1,
35
+		'content'           => 1,
36
+		'data-*'            => 1,
37
+		'dir'               => 1,
38
+		'disabled'          => 1,
39
+		'enctype'           => 1,
40
+		'for'               => 1,
41
+		'frameborder'       => 1,
42
+		'height'            => 1,
43
+		'href'              => 1,
44
+		'id'                => 1,
45
+		'itemprop'          => 1,
46
+		'itemscope'         => 1,
47
+		'itemtype'          => 1,
48
+		'label'             => 1,
49
+		'lang'              => 1,
50
+		'leftmargin'        => 1,
51
+		'marginheight'      => 1,
52
+		'marginwidth'       => 1,
53
+		'max'               => 1,
54
+		'maxlength'         => 1,
55
+		'media'             => 1,
56
+		'method'            => 1,
57
+		'min'               => 1,
58
+		'multiple'          => 1,
59
+		'name'              => 1,
60
+		'novalidate'        => 1,
61
+		'placeholder'       => 1,
62
+		'property'          => 1,
63
+		'readonly'          => 1,
64
+		'rel'               => 1,
65
+		'required'          => 1,
66
+		'rows'              => 1,
67
+		'selected'          => 1,
68
+		'src'               => 1,
69
+		'size'              => 1,
70
+		'style'             => 1,
71
+		'step'              => 1,
72
+		'tabindex'          => 1,
73
+		'target'            => 1,
74
+		'title'             => 1,
75
+		'topmargin'         => 1,
76
+		'type'              => 1,
77
+		'value'             => 1,
78
+		'width'             => 1,
79
+	];
80
+
81
+
82
+	/**
83
+	 * @var array
84
+	 */
85
+	private static $tags = [
86
+		'a',
87
+		'abbr',
88
+		'b',
89
+		'br',
90
+		'code',
91
+		'div',
92
+		'em',
93
+		'h1',
94
+		'h2',
95
+		'h3',
96
+		'h4',
97
+		'h5',
98
+		'h6',
99
+		'hr',
100
+		'i',
101
+		'img',
102
+		'li',
103
+		'ol',
104
+		'p',
105
+		'pre',
106
+		'small',
107
+		'span',
108
+		'strong',
109
+		'table',
110
+		'td',
111
+		'tr',
112
+		'ul',
113
+	];
114
+
115
+
116
+	/**
117
+	 * @var array
118
+	 */
119
+	private static $allowed_tags;
120
+
121
+
122
+	/**
123
+	 * @var array
124
+	 */
125
+	private static $allowed_with_embed_tags;
126
+
127
+
128
+	/**
129
+	 * @var array
130
+	 */
131
+	private static $allowed_with_form_tags;
132
+
133
+
134
+	/**
135
+	 * @var array
136
+	 */
137
+	private static $allowed_with_script_and_style_tags;
138
+
139
+	/**
140
+	 * @var array
141
+	 */
142
+	private static $allowed_with_full_tags;
143
+
144
+
145
+	/**
146
+	 * merges additional tags and attributes into the WP post tags
147
+	 */
148
+	private static function initializeAllowedTags()
149
+	{
150
+		$allowed_post_tags = wp_kses_allowed_html('post');
151
+		$allowed_tags = [];
152
+		foreach (AllowedTags::$tags as $tag) {
153
+			$allowed_tags[ $tag ] = AllowedTags::$attributes;
154
+		}
155
+		AllowedTags::$allowed_tags = array_merge_recursive($allowed_post_tags, $allowed_tags);
156
+	}
157
+
158
+
159
+	/**
160
+	 * merges embed tags and attributes into the EE all tags
161
+	 */
162
+	private static function initializeWithEmbedTags()
163
+	{
164
+		$all_tags = AllowedTags::getAllowedTags();
165
+		$embed_tags = [
166
+			'iframe' => AllowedTags::$attributes
167
+		];
168
+		AllowedTags::$allowed_with_embed_tags = array_merge_recursive($all_tags, $embed_tags);
169
+	}
170
+
171
+
172
+	/**
173
+	 * merges form tags and attributes into the EE all tags
174
+	 */
175
+	private static function initializeWithFormTags()
176
+	{
177
+		$all_tags = AllowedTags::getAllowedTags();
178
+		$form_tags = [
179
+			'form'     => AllowedTags::$attributes,
180
+			'label'    => AllowedTags::$attributes,
181
+			'input'    => AllowedTags::$attributes,
182
+			'select'   => AllowedTags::$attributes,
183
+			'option'   => AllowedTags::$attributes,
184
+			'optgroup' => AllowedTags::$attributes,
185
+			'textarea' => AllowedTags::$attributes,
186
+			'button'   => AllowedTags::$attributes,
187
+			'fieldset' => AllowedTags::$attributes,
188
+			'output'   => AllowedTags::$attributes,
189
+		];
190
+		AllowedTags::$allowed_with_form_tags = array_merge_recursive($all_tags, $form_tags);
191
+	}
192
+
193
+
194
+	/**
195
+	 * merges form script and style tags and attributes into the EE all tags
196
+	 */
197
+	private static function initializeWithScriptAndStyleTags()
198
+	{
199
+		$all_tags = AllowedTags::getAllowedTags();
200
+		$script_and_style_tags = [
201
+			'script'   => AllowedTags::$attributes,
202
+			'style'    => AllowedTags::$attributes,
203
+			'link'     => AllowedTags::$attributes,
204
+			'noscript' => AllowedTags::$attributes,
205
+		];
206
+		AllowedTags::$allowed_with_script_and_style_tags = array_merge_recursive($all_tags, $script_and_style_tags);
207
+	}
208
+
209
+	/**
210
+	 * merges all head and body tags and attributes into the EE all tags
211
+	 */
212
+	private static function initializeWithFullTags()
213
+	{
214
+		$all_tags = AllowedTags::getAllowedTags();
215
+		$full_tags = [
216
+			'script'    => AllowedTags::$attributes,
217
+			'style'     => AllowedTags::$attributes,
218
+			'link'      => AllowedTags::$attributes,
219
+			'title'     => AllowedTags::$attributes,
220
+			'meta'      => AllowedTags::$attributes,
221
+			'iframe'    => AllowedTags::$attributes,
222
+			'form'      => AllowedTags::$attributes,
223
+			'label'     => AllowedTags::$attributes,
224
+			'input'     => AllowedTags::$attributes,
225
+			'select'    => AllowedTags::$attributes,
226
+			'option'    => AllowedTags::$attributes,
227
+			'optgroup'  => AllowedTags::$attributes,
228
+			'textarea'  => AllowedTags::$attributes,
229
+			'button'    => AllowedTags::$attributes,
230
+			'fieldset'  => AllowedTags::$attributes,
231
+			'output'    => AllowedTags::$attributes,
232
+			'noscript'  => AllowedTags::$attributes,
233
+		];
234
+		AllowedTags::$allowed_with_full_tags = array_merge_recursive($all_tags, $full_tags);
235
+	}
236
+
237
+
238
+	/**
239
+	 * @return array[]
240
+	 */
241
+	public static function getAllowedTags()
242
+	{
243
+		if (empty(AllowedTags::$allowed_tags)) {
244
+			AllowedTags::initializeAllowedTags();
245
+		}
246
+		return AllowedTags::$allowed_tags;
247
+	}
248
+
249
+
250
+	/**
251
+	 * @return array[]
252
+	 */
253
+	public static function getWithEmbedTags()
254
+	{
255
+		if (empty(AllowedTags::$allowed_with_embed_tags)) {
256
+			AllowedTags::initializeWithEmbedTags();
257
+		}
258
+		return AllowedTags::$allowed_with_embed_tags;
259
+	}
260
+
261
+
262
+	/**
263
+	 * @return array[]
264
+	 */
265
+	public static function getWithFormTags()
266
+	{
267
+		if (empty(AllowedTags::$allowed_with_form_tags)) {
268
+			AllowedTags::initializeWithFormTags();
269
+		}
270
+		return AllowedTags::$allowed_with_form_tags;
271
+	}
272
+
273
+
274
+	/**
275
+	 * @return array[]
276
+	 */
277
+	public static function getWithScriptAndStyleTags()
278
+	{
279
+		if (empty(AllowedTags::$allowed_with_script_and_style_tags)) {
280
+			AllowedTags::initializeWithScriptAndStyleTags();
281
+		}
282
+		return AllowedTags::$allowed_with_script_and_style_tags;
283
+	}
284
+
285
+
286
+	/**
287
+	 * @return array[]
288
+	 */
289
+	public static function getWithFullTags()
290
+	{
291
+		if (empty(AllowedTags::$allowed_with_full_tags)) {
292
+			AllowedTags::initializeWithFullTags();
293
+		}
294
+		return AllowedTags::$allowed_with_full_tags;
295
+	}
296 296
 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since           4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.10.33.rc.010');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.10.33.rc.010');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
120
-        bootstrap_espresso();
121
-    }
119
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
120
+		bootstrap_espresso();
121
+	}
122 122
 }
123 123
 if (! function_exists('espresso_deactivate_plugin')) {
124
-    /**
125
-     *    deactivate_plugin
126
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
-     *
128
-     * @access public
129
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
-     * @return    void
131
-     */
132
-    function espresso_deactivate_plugin($plugin_basename = '')
133
-    {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
-        }
137
-        unset($_GET['activate'], $_REQUEST['activate']);
138
-        deactivate_plugins($plugin_basename);
139
-    }
124
+	/**
125
+	 *    deactivate_plugin
126
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
+	 *
128
+	 * @access public
129
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
+	 * @return    void
131
+	 */
132
+	function espresso_deactivate_plugin($plugin_basename = '')
133
+	{
134
+		if (! function_exists('deactivate_plugins')) {
135
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
+		}
137
+		unset($_GET['activate'], $_REQUEST['activate']);
138
+		deactivate_plugins($plugin_basename);
139
+	}
140 140
 }
141 141
\ No newline at end of file
Please login to merge, or discard this patch.
core/libraries/messages/EE_messenger.lib.php 1 patch
Indentation   +740 added lines, -740 removed lines patch added patch discarded remove patch
@@ -19,182 +19,182 @@  discard block
 block discarded – undo
19 19
 
20 20
 
21 21
 
22
-    /**
23
-     * This property holds the default message types associated with this messenger when it is activated. The values of the array must match a valid message type.
24
-     * This property gets set by the _set_default_message_types() method.
25
-     *
26
-     * @var array
27
-     */
28
-    protected $_default_message_types = array();
22
+	/**
23
+	 * This property holds the default message types associated with this messenger when it is activated. The values of the array must match a valid message type.
24
+	 * This property gets set by the _set_default_message_types() method.
25
+	 *
26
+	 * @var array
27
+	 */
28
+	protected $_default_message_types = array();
29 29
 
30 30
 
31 31
 
32 32
 
33
-    /**
34
-     * This property holds the message types that are valid for use with this messenger.
35
-     * It gets set by the _set_valid_message_types() method.
36
-     *
37
-     * @var array
38
-     */
39
-    protected $_valid_message_types = array();
33
+	/**
34
+	 * This property holds the message types that are valid for use with this messenger.
35
+	 * It gets set by the _set_valid_message_types() method.
36
+	 *
37
+	 * @var array
38
+	 */
39
+	protected $_valid_message_types = array();
40 40
 
41 41
 
42 42
 
43
-    /**
44
-     * Holds the configuration for the EE_Messages_Validator class to know how to validated the different fields. Note that the Validator will match each field here with the allowed shortcodes set in the "valid_shortcodes" array for the matched message type context.  So message types don't need to set a $_validator_config property.
45
-     *
46
-     * Remember, ALL fields must be declared in this array.  However, an empty value for the field means that the field will accept all valid shortcodes set for the given context in the message type (by default).
47
-     *
48
-     * Array should be in this format:
49
-     *
50
-     * array(
51
-     *  'field_name(i.e.to)' => array(
52
-     *      'shortcodes' => array('email'), //an array of shortcode groups (correspond to EE_Shortcodes library class) that are allowed in the field. Typically you can just include $this->_valid_shortcodes['field_name'] as the value here (because they will match).
53
-     *      'specific_shortcodes' => array( array('[EVENT_AUTHOR_EMAIL]' => esc_html__('Admin Email', 'event_espresso')), //if this index is present you can further restrict the field to ONLY specific shortcodes if an entire group isn't sufficient. Specific shortcodes need to be listed as an array with the index the shortcode and the value = the label.
54
-     *      'type' => 'email' //this is the field type and should match one of the validator types (see EE_Messages_Validator::validator() for all the possible types).  If not required you can just leave empty.,
55
-     *      'required' => array'[SHORTCODE]') //this is used to indicate the shortcodes that MUST be in the assembled array of shortcodes by the validator in order for this field to be included in validation.  Otherwise the validator will always assign shortcodes for this field (regardless of whether the field settings for the given messenger/message_type/context use the field or not.).. please note, this does NOT mean that the shortcodes listed here MUST be in the given field.
56
-     *  )
57
-     * )
58
-     *
59
-     * @var array
60
-     */
61
-    protected $_validator_config = array();
43
+	/**
44
+	 * Holds the configuration for the EE_Messages_Validator class to know how to validated the different fields. Note that the Validator will match each field here with the allowed shortcodes set in the "valid_shortcodes" array for the matched message type context.  So message types don't need to set a $_validator_config property.
45
+	 *
46
+	 * Remember, ALL fields must be declared in this array.  However, an empty value for the field means that the field will accept all valid shortcodes set for the given context in the message type (by default).
47
+	 *
48
+	 * Array should be in this format:
49
+	 *
50
+	 * array(
51
+	 *  'field_name(i.e.to)' => array(
52
+	 *      'shortcodes' => array('email'), //an array of shortcode groups (correspond to EE_Shortcodes library class) that are allowed in the field. Typically you can just include $this->_valid_shortcodes['field_name'] as the value here (because they will match).
53
+	 *      'specific_shortcodes' => array( array('[EVENT_AUTHOR_EMAIL]' => esc_html__('Admin Email', 'event_espresso')), //if this index is present you can further restrict the field to ONLY specific shortcodes if an entire group isn't sufficient. Specific shortcodes need to be listed as an array with the index the shortcode and the value = the label.
54
+	 *      'type' => 'email' //this is the field type and should match one of the validator types (see EE_Messages_Validator::validator() for all the possible types).  If not required you can just leave empty.,
55
+	 *      'required' => array'[SHORTCODE]') //this is used to indicate the shortcodes that MUST be in the assembled array of shortcodes by the validator in order for this field to be included in validation.  Otherwise the validator will always assign shortcodes for this field (regardless of whether the field settings for the given messenger/message_type/context use the field or not.).. please note, this does NOT mean that the shortcodes listed here MUST be in the given field.
56
+	 *  )
57
+	 * )
58
+	 *
59
+	 * @var array
60
+	 */
61
+	protected $_validator_config = array();
62 62
 
63 63
 
64 64
 
65
-    /**
66
-     * This will hold the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
67
-     * @var object
68
-     */
69
-    protected $_EEM_data;
65
+	/**
66
+	 * This will hold the EEM_message_templates model for interacting with the database and retrieving active templates for the messenger
67
+	 * @var object
68
+	 */
69
+	protected $_EEM_data;
70 70
 
71 71
 
72 72
 
73
-    /**
74
-     * this property just holds an array of the various template refs.
75
-     * @var array
76
-     */
77
-    protected $_template_fields = array();
73
+	/**
74
+	 * this property just holds an array of the various template refs.
75
+	 * @var array
76
+	 */
77
+	protected $_template_fields = array();
78 78
 
79 79
 
80 80
 
81 81
 
82
-    /**
83
-     * This holds an array of the arguments used in parsing a template for the sender.
84
-     * @var array
85
-     */
86
-    protected $_template_args = array();
82
+	/**
83
+	 * This holds an array of the arguments used in parsing a template for the sender.
84
+	 * @var array
85
+	 */
86
+	protected $_template_args = array();
87 87
 
88 88
 
89 89
 
90 90
 
91 91
 
92 92
 
93
-    /**
94
-     * This property will hold the configuration for any test settings fields that are required for the "test" button that is used to trigger an actual test of this messenger
95
-     *
96
-     * @protected
97
-     * @var array
98
-     */
99
-    protected $_test_settings_fields = array();
93
+	/**
94
+	 * This property will hold the configuration for any test settings fields that are required for the "test" button that is used to trigger an actual test of this messenger
95
+	 *
96
+	 * @protected
97
+	 * @var array
98
+	 */
99
+	protected $_test_settings_fields = array();
100 100
 
101 101
 
102 102
 
103 103
 
104 104
 
105 105
 
106
-    /**
107
-     * This will hold the EE_Messages_Template_Pack object when set on the messenger.  This is set via the validate and setup method which grabs the template pack from the incoming messages object.
108
-     *
109
-     * @since 4.5.0
110
-     *
111
-     * @var EE_Messages_Template_Pack
112
-     */
113
-    protected $_tmp_pack;
106
+	/**
107
+	 * This will hold the EE_Messages_Template_Pack object when set on the messenger.  This is set via the validate and setup method which grabs the template pack from the incoming messages object.
108
+	 *
109
+	 * @since 4.5.0
110
+	 *
111
+	 * @var EE_Messages_Template_Pack
112
+	 */
113
+	protected $_tmp_pack;
114 114
 
115 115
 
116 116
 
117 117
 
118
-    /**
119
-     * This will hold the variation to use when performing a send.  It is set via the validate and setup method which grabs the variation from the incoming messages object on the send method.
120
-     *
121
-     * @since 4.5.0
122
-     *
123
-     * @var string
124
-     */
125
-    protected $_variation;
118
+	/**
119
+	 * This will hold the variation to use when performing a send.  It is set via the validate and setup method which grabs the variation from the incoming messages object on the send method.
120
+	 *
121
+	 * @since 4.5.0
122
+	 *
123
+	 * @var string
124
+	 */
125
+	protected $_variation;
126 126
 
127 127
 
128 128
 
129 129
 
130 130
 
131
-    /**
132
-     * This property is a stdClass that holds labels for all the various supporting properties for this messenger.  These labels are set via the _set_supports_labels() method in children classes. Initially this will include the label for:
133
-     *
134
-     *  - template pack
135
-     *  - template variation
136
-     *
137
-     * @since 4.5.0
138
-     *
139
-     * @var stdClass
140
-     */
141
-    protected $_supports_labels;
131
+	/**
132
+	 * This property is a stdClass that holds labels for all the various supporting properties for this messenger.  These labels are set via the _set_supports_labels() method in children classes. Initially this will include the label for:
133
+	 *
134
+	 *  - template pack
135
+	 *  - template variation
136
+	 *
137
+	 * @since 4.5.0
138
+	 *
139
+	 * @var stdClass
140
+	 */
141
+	protected $_supports_labels;
142 142
 
143 143
 
144 144
 
145 145
 
146 146
 
147
-    /**
148
-     * This property is set when the send_message() method is called and holds the Message Type used to generate templates with this messenger for the messages.
149
-     *
150
-     * @var EE_message_type
151
-     */
152
-    protected $_incoming_message_type;
147
+	/**
148
+	 * This property is set when the send_message() method is called and holds the Message Type used to generate templates with this messenger for the messages.
149
+	 *
150
+	 * @var EE_message_type
151
+	 */
152
+	protected $_incoming_message_type;
153 153
 
154 154
 
155 155
 
156
-    /**
157
-     * This flag sets whether a messenger is activated by default  on installation (or reactivation) of EE core or not.
158
-     *
159
-     * @var bool
160
-     */
161
-    public $activate_on_install = false;
156
+	/**
157
+	 * This flag sets whether a messenger is activated by default  on installation (or reactivation) of EE core or not.
158
+	 *
159
+	 * @var bool
160
+	 */
161
+	public $activate_on_install = false;
162 162
 
163 163
 
164 164
 
165 165
 
166 166
 
167
-    public function __construct()
168
-    {
169
-        $this->_EEM_data = EEM_Message_Template_Group::instance();
170
-        $this->_messages_item_type = 'messenger';
167
+	public function __construct()
168
+	{
169
+		$this->_EEM_data = EEM_Message_Template_Group::instance();
170
+		$this->_messages_item_type = 'messenger';
171 171
 
172
-        parent::__construct();
172
+		parent::__construct();
173 173
 
174
-        $this->_set_test_settings_fields();
175
-        $this->_set_template_fields();
176
-        $this->_set_default_message_types();
177
-        $this->_set_valid_message_types();
178
-        $this->_set_validator_config();
174
+		$this->_set_test_settings_fields();
175
+		$this->_set_template_fields();
176
+		$this->_set_default_message_types();
177
+		$this->_set_valid_message_types();
178
+		$this->_set_validator_config();
179 179
 
180 180
 
181
-        $this->_supports_labels = new stdClass();
182
-        $this->_set_supports_labels();
183
-    }
181
+		$this->_supports_labels = new stdClass();
182
+		$this->_set_supports_labels();
183
+	}
184 184
 
185 185
 
186 186
 
187 187
 
188 188
 
189
-    /**
190
-     * _set_template_fields
191
-     * This sets up the fields that a messenger requires for the message to go out.
192
-     *
193
-     * @abstract
194
-     * @access  protected
195
-     * @return void
196
-     */
197
-    abstract protected function _set_template_fields();
189
+	/**
190
+	 * _set_template_fields
191
+	 * This sets up the fields that a messenger requires for the message to go out.
192
+	 *
193
+	 * @abstract
194
+	 * @access  protected
195
+	 * @return void
196
+	 */
197
+	abstract protected function _set_template_fields();
198 198
 
199 199
 
200 200
 
@@ -204,14 +204,14 @@  discard block
 block discarded – undo
204 204
 
205 205
 
206 206
 
207
-    /**
208
-     * This method sets the _default_message_type property (see definition in docs attached to property)
209
-     *
210
-     * @abstract
211
-     * @access protected
212
-     * @return void
213
-     */
214
-    abstract protected function _set_default_message_types();
207
+	/**
208
+	 * This method sets the _default_message_type property (see definition in docs attached to property)
209
+	 *
210
+	 * @abstract
211
+	 * @access protected
212
+	 * @return void
213
+	 */
214
+	abstract protected function _set_default_message_types();
215 215
 
216 216
 
217 217
 
@@ -219,15 +219,15 @@  discard block
 block discarded – undo
219 219
 
220 220
 
221 221
 
222
-    /**
223
-     * Sets the _valid_message_types property (see definition in cods attached to property)
224
-     *
225
-     * @since 4.5.0
226
-     *
227
-     * @abstract
228
-     * @return void
229
-     */
230
-    abstract protected function _set_valid_message_types();
222
+	/**
223
+	 * Sets the _valid_message_types property (see definition in cods attached to property)
224
+	 *
225
+	 * @since 4.5.0
226
+	 *
227
+	 * @abstract
228
+	 * @return void
229
+	 */
230
+	abstract protected function _set_valid_message_types();
231 231
 
232 232
 
233 233
 
@@ -235,171 +235,171 @@  discard block
 block discarded – undo
235 235
 
236 236
 
237 237
 
238
-    /**
239
-     * Child classes must declare the $_validator_config property using this method.
240
-     * See comments for $_validator_config for details on what it is used for.
241
-     *
242
-     * NOTE:  messengers should set an array of valid shortcodes for ALL scenarios.  The corresponding validator class (validators/{messenger}) can be used to restrict only certain shortcodes per template so users cannot add certain shortcodes.
243
-     *
244
-     * @access protected
245
-     * @return void
246
-     */
247
-    abstract protected function _set_validator_config();
238
+	/**
239
+	 * Child classes must declare the $_validator_config property using this method.
240
+	 * See comments for $_validator_config for details on what it is used for.
241
+	 *
242
+	 * NOTE:  messengers should set an array of valid shortcodes for ALL scenarios.  The corresponding validator class (validators/{messenger}) can be used to restrict only certain shortcodes per template so users cannot add certain shortcodes.
243
+	 *
244
+	 * @access protected
245
+	 * @return void
246
+	 */
247
+	abstract protected function _set_validator_config();
248 248
 
249 249
 
250 250
 
251 251
 
252 252
 
253 253
 
254
-    /**
255
-     * We just deliver the messages don't kill us!!  This method will need to be modified by child classes for whatever action is taken to actually send a message.
256
-     *
257
-     * @return bool|WP_Error
258
-     * @throw \Exception
259
-     */
260
-    abstract protected function _send_message();
254
+	/**
255
+	 * We just deliver the messages don't kill us!!  This method will need to be modified by child classes for whatever action is taken to actually send a message.
256
+	 *
257
+	 * @return bool|WP_Error
258
+	 * @throw \Exception
259
+	 */
260
+	abstract protected function _send_message();
261 261
 
262 262
 
263 263
 
264 264
 
265
-    /**
266
-     * We give you pretty previews of the messages!
267
-     * @return string html body for message content.
268
-     */
269
-    abstract protected function _preview();
265
+	/**
266
+	 * We give you pretty previews of the messages!
267
+	 * @return string html body for message content.
268
+	 */
269
+	abstract protected function _preview();
270 270
 
271 271
 
272 272
 
273 273
 
274
-    /**
275
-     * Used by messengers (or preview) for enqueueing any scripts or styles need in message generation.
276
-     *
277
-     * @since 4.5.0
278
-     *
279
-     * @return void
280
-     */
281
-    public function enqueue_scripts_styles()
282
-    {
283
-        do_action('AHEE__EE_messenger__enqueue_scripts_styles');
284
-    }
274
+	/**
275
+	 * Used by messengers (or preview) for enqueueing any scripts or styles need in message generation.
276
+	 *
277
+	 * @since 4.5.0
278
+	 *
279
+	 * @return void
280
+	 */
281
+	public function enqueue_scripts_styles()
282
+	{
283
+		do_action('AHEE__EE_messenger__enqueue_scripts_styles');
284
+	}
285 285
 
286 286
 
287 287
 
288 288
 
289 289
 
290
-    /**
291
-     * This is used to indicate whether a messenger must be sent immediately or not.
292
-     * eg. The HTML messenger will override this to return true because it should be displayed in user's browser right
293
-     * away.  The PDF messenger is similar.
294
-     *
295
-     * This flag thus overrides any priorities that may be set on the message type used to generate the message.
296
-     *
297
-     * Default for this is false.  So children classes must override this if they want a message to be executed immediately.
298
-     *
299
-     * @since  4.9.0
300
-     * @return bool
301
-     */
302
-    public function send_now()
303
-    {
304
-        return false;
305
-    }
290
+	/**
291
+	 * This is used to indicate whether a messenger must be sent immediately or not.
292
+	 * eg. The HTML messenger will override this to return true because it should be displayed in user's browser right
293
+	 * away.  The PDF messenger is similar.
294
+	 *
295
+	 * This flag thus overrides any priorities that may be set on the message type used to generate the message.
296
+	 *
297
+	 * Default for this is false.  So children classes must override this if they want a message to be executed immediately.
298
+	 *
299
+	 * @since  4.9.0
300
+	 * @return bool
301
+	 */
302
+	public function send_now()
303
+	{
304
+		return false;
305
+	}
306 306
 
307 307
 
308 308
 
309 309
 
310 310
 
311
-    /**
312
-     * This is a way for a messenger to indicate whether it allows an empty to field or not.
313
-     * Note: If the generated message is a for a preview, this value is ignored.
314
-     * @since 4.9.0
315
-     * @return bool
316
-     */
317
-    public function allow_empty_to_field()
318
-    {
319
-        return false;
320
-    }
311
+	/**
312
+	 * This is a way for a messenger to indicate whether it allows an empty to field or not.
313
+	 * Note: If the generated message is a for a preview, this value is ignored.
314
+	 * @since 4.9.0
315
+	 * @return bool
316
+	 */
317
+	public function allow_empty_to_field()
318
+	{
319
+		return false;
320
+	}
321 321
 
322 322
 
323 323
 
324 324
 
325 325
 
326
-    /**
327
-     * Sets the defaults for the _supports_labels property.  Can be overridden by child classes.
328
-     * @see property definition for info on how its formatted.
329
-     *
330
-     * @since 4.5.0;
331
-     * @return void
332
-     */
333
-    protected function _set_supports_labels()
334
-    {
335
-        $this->_set_supports_labels_defaults();
336
-    }
326
+	/**
327
+	 * Sets the defaults for the _supports_labels property.  Can be overridden by child classes.
328
+	 * @see property definition for info on how its formatted.
329
+	 *
330
+	 * @since 4.5.0;
331
+	 * @return void
332
+	 */
333
+	protected function _set_supports_labels()
334
+	{
335
+		$this->_set_supports_labels_defaults();
336
+	}
337 337
 
338 338
 
339 339
 
340 340
 
341 341
 
342
-    /**
343
-     * Sets the defaults for the _supports_labels property.
344
-     *
345
-     * @since 4.5.0
346
-     *
347
-     * @return void
348
-     */
349
-    private function _set_supports_labels_defaults()
350
-    {
351
-        $this->_supports_labels->template_pack = esc_html__('Template Structure', 'event_espresso');
352
-        $this->_supports_labels->template_variation = esc_html__('Template Style', 'event_espresso');
353
-        $this->_supports_labels->template_pack_description = esc_html__('Template Structure options are bundled structural changes for templates.', 'event_espresso');
342
+	/**
343
+	 * Sets the defaults for the _supports_labels property.
344
+	 *
345
+	 * @since 4.5.0
346
+	 *
347
+	 * @return void
348
+	 */
349
+	private function _set_supports_labels_defaults()
350
+	{
351
+		$this->_supports_labels->template_pack = esc_html__('Template Structure', 'event_espresso');
352
+		$this->_supports_labels->template_variation = esc_html__('Template Style', 'event_espresso');
353
+		$this->_supports_labels->template_pack_description = esc_html__('Template Structure options are bundled structural changes for templates.', 'event_espresso');
354 354
 
355
-        $this->_supports_labels->template_variation_description = esc_html__('These are different styles to choose from for the selected template structure.  Usually these affect things like font style, color, borders etc.  In some cases the styles will also make minor layout changes.', 'event_espresso');
355
+		$this->_supports_labels->template_variation_description = esc_html__('These are different styles to choose from for the selected template structure.  Usually these affect things like font style, color, borders etc.  In some cases the styles will also make minor layout changes.', 'event_espresso');
356 356
 
357
-        $this->_supports_labels = apply_filters('FHEE__EE_messenger___set_supports_labels_defaults___supports_labels', $this->_supports_labels, $this);
358
-    }
357
+		$this->_supports_labels = apply_filters('FHEE__EE_messenger___set_supports_labels_defaults___supports_labels', $this->_supports_labels, $this);
358
+	}
359 359
 
360 360
 
361 361
 
362 362
 
363 363
 
364
-    /**
365
-     * This returns the _supports_labels property.
366
-     *
367
-     * @since 4.5.0
368
-     *
369
-     * @return stdClass
370
-     */
371
-    public function get_supports_labels()
372
-    {
373
-        if (empty($this->_supports_labels->template_pack) || empty($this->_supports_labels->template_variation)) {
374
-            $this->_set_supports_labels_defaults();
375
-        }
376
-        return apply_filters('FHEE__EE_messenger__get_supports_labels', $this->_supports_labels, $this);
377
-    }
364
+	/**
365
+	 * This returns the _supports_labels property.
366
+	 *
367
+	 * @since 4.5.0
368
+	 *
369
+	 * @return stdClass
370
+	 */
371
+	public function get_supports_labels()
372
+	{
373
+		if (empty($this->_supports_labels->template_pack) || empty($this->_supports_labels->template_variation)) {
374
+			$this->_set_supports_labels_defaults();
375
+		}
376
+		return apply_filters('FHEE__EE_messenger__get_supports_labels', $this->_supports_labels, $this);
377
+	}
378 378
 
379 379
 
380 380
 
381 381
 
382
-    /**
383
-     * Used to retrieve a variation (typically the path/url to a css file)
384
-     *
385
-     * @since 4.5.0
386
-     *
387
-     * @param EE_Messages_Template_Pack $pack   The template pack used for retrieving the variation.
388
-     * @param string                    $message_type_name The name property of the message type that we need the variation for.
389
-     * @param bool                      $url   Whether to return url (true) or path (false). Default is false.
390
-     * @param string                    $type What variation type to return. Default is 'main'.
391
-     * @param string               $variation What variation for the template pack
392
-     * @param bool             $skip_filters This allows messengers to add a filter for another messengers get_variation but call skip filters on the callback so there is no recursion on apply_filters.
393
-     *
394
-     * @return string                    path or url for the requested variation.
395
-     */
396
-    public function get_variation(EE_Messages_Template_Pack $pack, $message_type_name, $url = false, $type = 'main', $variation = 'default', $skip_filters = false)
397
-    {
398
-        $this->_tmp_pack = $pack;
399
-        $variation_path = apply_filters('EE_messenger__get_variation__variation', false, $pack, $this->name, $message_type_name, $url, $type, $variation, $skip_filters);
400
-        $variation_path = empty($variation_path) ? $this->_tmp_pack->get_variation($this->name, $message_type_name, $type, $variation, $url, '.css', $skip_filters) : $variation_path;
401
-        return $variation_path;
402
-    }
382
+	/**
383
+	 * Used to retrieve a variation (typically the path/url to a css file)
384
+	 *
385
+	 * @since 4.5.0
386
+	 *
387
+	 * @param EE_Messages_Template_Pack $pack   The template pack used for retrieving the variation.
388
+	 * @param string                    $message_type_name The name property of the message type that we need the variation for.
389
+	 * @param bool                      $url   Whether to return url (true) or path (false). Default is false.
390
+	 * @param string                    $type What variation type to return. Default is 'main'.
391
+	 * @param string               $variation What variation for the template pack
392
+	 * @param bool             $skip_filters This allows messengers to add a filter for another messengers get_variation but call skip filters on the callback so there is no recursion on apply_filters.
393
+	 *
394
+	 * @return string                    path or url for the requested variation.
395
+	 */
396
+	public function get_variation(EE_Messages_Template_Pack $pack, $message_type_name, $url = false, $type = 'main', $variation = 'default', $skip_filters = false)
397
+	{
398
+		$this->_tmp_pack = $pack;
399
+		$variation_path = apply_filters('EE_messenger__get_variation__variation', false, $pack, $this->name, $message_type_name, $url, $type, $variation, $skip_filters);
400
+		$variation_path = empty($variation_path) ? $this->_tmp_pack->get_variation($this->name, $message_type_name, $type, $variation, $url, '.css', $skip_filters) : $variation_path;
401
+		return $variation_path;
402
+	}
403 403
 
404 404
 
405 405
 
@@ -407,497 +407,497 @@  discard block
 block discarded – undo
407 407
 
408 408
 
409 409
 
410
-    /**
411
-     * This just returns the default message types associated with this messenger when it is first activated.
412
-     *
413
-     * @access public
414
-     * @return array
415
-     */
416
-    public function get_default_message_types()
417
-    {
418
-        $class = get_class($this);
410
+	/**
411
+	 * This just returns the default message types associated with this messenger when it is first activated.
412
+	 *
413
+	 * @access public
414
+	 * @return array
415
+	 */
416
+	public function get_default_message_types()
417
+	{
418
+		$class = get_class($this);
419 419
 
420
-        // messenger specific filter
421
-        $default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
420
+		// messenger specific filter
421
+		$default_types = apply_filters('FHEE__' . $class . '__get_default_message_types__default_types', $this->_default_message_types, $this);
422 422
 
423
-        // all messengers filter
424
-        $default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
425
-        return $default_types;
426
-    }
423
+		// all messengers filter
424
+		$default_types = apply_filters('FHEE__EE_messenger__get_default_message_types__default_types', $default_types, $this);
425
+		return $default_types;
426
+	}
427 427
 
428 428
 
429 429
 
430 430
 
431
-    /**
432
-     * Returns the valid message types associated with this messenger.
433
-     *
434
-     * @since 4.5.0
435
-     *
436
-     * @return array
437
-     */
438
-    public function get_valid_message_types()
439
-    {
440
-        $class = get_class($this);
441
-
442
-        // messenger specific filter
443
-        // messenger specific filter
444
-        $valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
445
-
446
-        // all messengers filter
447
-        $valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
448
-        return $valid_types;
449
-    }
450
-
451
-
452
-
453
-
454
-
455
-    /**
456
-     * this is just used by the custom validators (EE_Messages_Validator classes) to modify the _validator_config for certain message_type/messenger combos where a context may only use certain shortcodes etc.
457
-     *
458
-     * @access public
459
-     * @param array $new_config Whatever is put in here will reset the _validator_config property
460
-     */
461
-    public function set_validator_config($new_config)
462
-    {
463
-        $this->_validator_config = $new_config;
464
-    }
465
-
466
-
467
-
468
-
469
-    /**
470
-     * This returns the _validator_config property
471
-     *
472
-     * @access public
473
-     * @return array
474
-     */
475
-    public function get_validator_config()
476
-    {
477
-        $class = get_class($this);
478
-
479
-        $config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
480
-        $config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
481
-        return $config;
482
-    }
483
-
484
-
485
-
486
-
487
-    /**
488
-     * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class callback function if that page is registered via the `_admin_registered_page` property set by the child class.
489
-     *
490
-     * @param string $page the slug of the EE admin page
491
-     * @param array $message_types an array of active message type objects
492
-     * @param string $action the page action (to allow for more specific handling - i.e. edit vs. add pages)
493
-     * @param array $extra  This is just an extra argument that can be used to pass additional data for setting up page content.
494
-     * @access public
495
-     * @return string content for page
496
-     */
497
-    public function get_messenger_admin_page_content($page, $action = null, $extra = array(), $message_types = array())
498
-    {
499
-        return $this->_get_admin_page_content($page, $action, $extra, $message_types);
500
-    }
501
-
502
-
503
-
504
-    /**
505
-     * @param $message_types
506
-     * @param array $extra
507
-     * @return mixed|string
508
-     */
509
-    protected function _get_admin_content_events_edit($message_types, $extra)
510
-    {
511
-        // defaults
512
-        $template_args = array();
513
-        $selector_rows = '';
514
-
515
-        // we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
516
-        $event_id = isset($extra['event']) ? $extra['event'] : null;
517
-
518
-        $template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
519
-        $template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
520
-
521
-        // array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
522
-        $global_templates = EEM_Message_Template_Group::instance()->get_all(
523
-            array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
524
-        );
525
-        $templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
526
-            $event_id,
527
-            array(
528
-                'MTP_messenger' => $this->name,
529
-                'MTP_is_active' => true
530
-            )
531
-        );
532
-        $templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
533
-
534
-        // so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
535
-        foreach ($global_templates as $mtpgID => $mtpg) {
536
-            if ($mtpg instanceof EE_Message_Template_Group) {
537
-                // verify this message type is supposed to show on this page
538
-                $mtp_obj = $mtpg->message_type_obj();
539
-                if (! $mtp_obj instanceof EE_message_type) {
540
-                    continue;
541
-                }
542
-                $mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
543
-                if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
544
-                    continue;
545
-                }
546
-                $select_values = array();
547
-                $select_values[ $mtpgID ] = esc_html__('Global', 'event_espresso');
548
-                $default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
549
-                // if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
550
-                if (! $mtpg->get('MTP_is_override')) {
551
-                    // any custom templates for this message type?
552
-                    $custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
553
-                    foreach ($custom_templates as $cmtpgID => $cmtpg) {
554
-                        $select_values[ $cmtpgID ] = $cmtpg->name();
555
-                        $default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
556
-                    }
557
-                }
558
-                // if there is no $default_value then we set it as the global
559
-                $default_value = empty($default_value) ? $mtpgID : $default_value;
560
-                $c_config = $mtpg->contexts_config();
561
-                $edit_context = key(array_slice($c_config, -1));
562
-                $edit_url_query_args = [
563
-                    'page' => 'espresso_messages',
564
-                    'action' => 'edit_message_template',
565
-                    'id' => $default_value,
566
-                    'evt_id' => $event_id,
567
-                    'context' => $edit_context,
568
-                ];
569
-                $edit_url = EEH_URL::add_query_args_and_nonce($edit_url_query_args, admin_url('admin.php'));
570
-                $create_url_query_args = [
571
-                    'page' => 'espresso_messages',
572
-                    'action' => 'add_new_message_template',
573
-                    'GRP_ID' => $default_value,
574
-                    'message_type' => $mtpg->message_type(),
575
-                    'messenger' => $this->name
576
-                ];
577
-                $create_url = EEH_URL::add_query_args_and_nonce($create_url_query_args, admin_url('admin.php'));
578
-                $st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
579
-                $st_args['mt_slug'] = $mtpg->message_type();
580
-                $st_args['messenger_slug'] = $this->name;
581
-                $st_args['selector'] = EEH_Form_Fields::select_input('event_message_templates_relation[' . $mtpgID . ']', $select_values, $default_value, 'data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '"', 'message-template-selector');
582
-                // note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
583
-                $st_args['create_button'] = $mtpg->get('MTP_is_override') ? '' : '<a data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $create_url . '" class="button button-small create-mtpg-button">' . esc_html__('Create New Custom', 'event_espresso') . '</a>';
584
-                $st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'espresso_messages_add_new_message_template') ? $st_args['create_button'] : '';
585
-                $st_args['edit_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_message', 'espresso_messages_edit_message_template', $mtpgID) ? '<a data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $edit_url . '" class="button button-small edit-mtpg-button">' . esc_html__('Edit', 'event_espresso') . '</a>' : '';
586
-                $selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
587
-            }
588
-        }
589
-
590
-        // if no selectors present then get out.
591
-        if (empty($selector_rows)) {
592
-            return '';
593
-        }
594
-
595
-        $template_args['selector_rows'] = $selector_rows;
596
-        return EEH_Template::display_template($template_wrapper_path, $template_args, true);
597
-    }
598
-
599
-
600
-
601
-
602
-
603
-
604
-    /**
605
-     * get_template_fields
606
-     *
607
-     * @access public
608
-     * @return array $this->_template_fields
609
-     */
610
-    public function get_template_fields()
611
-    {
612
-        $template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
613
-        $template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
614
-        return $template_fields;
615
-    }
616
-
617
-
618
-
619
-
620
-    /** SETUP METHODS **/
621
-    /**
622
-     * The following method doesn't NEED to be used by child classes but might be modified by the specific messenger
623
-     * @param string $item
624
-     * @param mixed $value
625
-     */
626
-    protected function _set_template_value($item, $value)
627
-    {
628
-        if (array_key_exists($item, $this->_template_fields)) {
629
-            $prop = '_' . $item;
630
-            $this->{$prop} = $value;
631
-        }
632
-    }
633
-
634
-    /**
635
-     * Sets up the message for sending.
636
-     *
637
-     * @param  EE_message $message the message object that contains details about the message.
638
-     * @param EE_message_type $message_type The message type object used in combination with this messenger to generate the provided message.
639
-     *
640
-     * @return bool Very important that all messengers return bool for successful send or not.  Error messages can be
641
-     *              added to EE_Error.
642
-     *              true = message sent successfully
643
-     *              false = message not sent but can be retried (i.e. the failure might be just due to communication issues at the time of send).
644
-     *              Throwing a SendMessageException means the message failed sending and cannot be retried.
645
-     *
646
-     * @throws SendMessageException
647
-     */
648
-    final public function send_message($message, EE_message_type $message_type)
649
-    {
650
-        try {
651
-            $this->_validate_and_setup($message);
652
-            $this->_incoming_message_type = $message_type;
653
-            $response = $this->_send_message();
654
-            if ($response instanceof WP_Error) {
655
-                EE_Error::add_error($response->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
656
-                $response = false;
657
-            }
658
-        } catch (\Exception $e) {
659
-            // convert to an instance of SendMessageException
660
-            throw new SendMessageException($e->getMessage());
661
-        }
662
-        return $response;
663
-    }
664
-
665
-
666
-
667
-    /**
668
-     * Sets up and returns message preview
669
-     * @param  EE_Message $message incoming message object
670
-     * @param EE_message_type $message_type This is whatever message type was used in combination with this messenger to generate the message.
671
-     * @param  bool   $send    true we will actually use the _send method (for test sends). FALSE we just return preview
672
-     * @return string          return the message html content
673
-     */
674
-    public function get_preview(EE_Message $message, EE_message_type $message_type, $send = false)
675
-    {
676
-        $this->_validate_and_setup($message);
677
-
678
-        $this->_incoming_message_type = $message_type;
679
-
680
-        if ($send) {
681
-            // are we overriding any existing template fields?
682
-            $settings = apply_filters(
683
-                'FHEE__EE_messenger__get_preview__messenger_test_settings',
684
-                $this->get_existing_test_settings(),
685
-                $this,
686
-                $send,
687
-                $message,
688
-                $message_type
689
-            );
690
-            if (! empty($settings)) {
691
-                foreach ($settings as $field => $value) {
692
-                    $this->_set_template_value($field, $value);
693
-                }
694
-            }
695
-        }
696
-
697
-        // enqueue preview js so that any links/buttons on the page are disabled.
698
-        if (! $send) {
699
-            // the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
700
-            // it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
701
-            add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
702
-            add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
703
-            add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
704
-        }
705
-
706
-        return $send ? $this->_send_message() : $this->_preview();
707
-    }
708
-
709
-
710
-
711
-
712
-    /**
713
-     * Callback for enqueue_scripts so that we setup the preview script for all previews.
714
-     *
715
-     * @since 4.5.0
716
-     *
717
-     * @return void
718
-     */
719
-    public function add_preview_script()
720
-    {
721
-        // error message
722
-        EE_Registry::$i18n_js_strings['links_disabled'] = wp_strip_all_tags(
723
-            __('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso')
724
-        );
725
-        wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
726
-        wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
727
-        wp_enqueue_script('ee-messages-preview-js');
728
-    }
729
-
730
-
731
-
732
-
733
-    /**
734
-     * simply validates the incoming message object and then sets up the properties for the messenger
735
-     * @param  EE_Message $message
736
-     * @throws EE_Error
737
-     */
738
-    protected function _validate_and_setup(EE_Message $message)
739
-    {
740
-        $template_pack = $message->get_template_pack();
741
-        $variation = $message->get_template_pack_variation();
742
-
743
-        // verify we have the required template pack value on the $message object.
744
-        if (! $template_pack instanceof EE_Messages_Template_Pack) {
745
-            throw new EE_Error(esc_html__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
746
-        }
747
-
748
-        $this->_tmp_pack = $template_pack;
749
-
750
-        $this->_variation = $variation ? $variation : 'default';
751
-
752
-        $template_fields = $this->get_template_fields();
753
-
754
-        foreach ($template_fields as $template => $value) {
755
-            if ($template !== 'extra') {
756
-                $column_value = $message->get_field_or_extra_meta('MSG_' . $template);
757
-                $message_template_value = $column_value ? $column_value : null;
758
-                $this->_set_template_value($template, $message_template_value);
759
-            }
760
-        }
761
-    }
762
-
763
-
764
-
765
-    /**
766
-     * Utility method for child classes to get the contents of a template file and return
767
-     *
768
-     * We're assuming the child messenger class has already setup template args!
769
-     * @param  bool $preview if true we use the preview wrapper otherwise we use main wrapper.
770
-     * @return string
771
-     * @throws \EE_Error
772
-     */
773
-    protected function _get_main_template($preview = false)
774
-    {
775
-        $type = $preview ? 'preview' : 'main';
776
-
777
-        $wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
778
-
779
-        // check file exists and is readable
780
-        if (!is_readable($wrapper_template)) {
781
-            throw new EE_Error(sprintf(esc_html__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
782
-        }
783
-
784
-        // add message type to template args
785
-        $this->_template_args['message_type'] = $this->_incoming_message_type;
786
-
787
-        return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
788
-    }
789
-
790
-
791
-
792
-    /**
793
-     * set the _test_settings_fields property
794
-     *
795
-     * @access protected
796
-     * @return void
797
-     */
798
-    protected function _set_test_settings_fields()
799
-    {
800
-        $this->_test_settings_fields = array();
801
-    }
802
-
803
-
804
-
805
-    /**
806
-     * return the _test_settings_fields property
807
-     * @return array
808
-     */
809
-    public function get_test_settings_fields()
810
-    {
811
-        return $this->_test_settings_fields;
812
-    }
813
-
814
-
815
-
816
-
817
-    /**
818
-     * This just returns any existing test settings that might be saved in the database
819
-     *
820
-     * @access public
821
-     * @return array
822
-     */
823
-    public function get_existing_test_settings()
824
-    {
825
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
826
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
827
-        $settings = $Message_Resource_Manager->get_active_messengers_option();
828
-        return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
829
-    }
830
-
831
-
832
-
833
-    /**
834
-     * All this does is set the existing test settings (in the db) for the messenger
835
-     *
836
-     * @access public
837
-     * @param $settings
838
-     * @return bool success/fail
839
-     */
840
-    public function set_existing_test_settings($settings)
841
-    {
842
-        /** @var EE_Message_Resource_Manager $Message_Resource_Manager */
843
-        $Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
844
-        $existing = $Message_Resource_Manager->get_active_messengers_option();
845
-        $existing[ $this->name ]['test_settings'] = $settings;
846
-        return $Message_Resource_Manager->update_active_messengers_option($existing);
847
-    }
848
-
849
-
850
-
851
-    /**
852
-     * This just returns the field label for a given field setup in the _template_fields property.
853
-     *
854
-     * @since   4.3.0
855
-     *
856
-     * @param string $field The field to retrieve the label for
857
-     * @return string             The label
858
-     */
859
-    public function get_field_label($field)
860
-    {
861
-        // first let's see if the field requests is in the top level array.
862
-        if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
863
-            return $this->_template[ $field ]['label'];
864
-        }
865
-
866
-        // nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
867
-        if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
868
-            return $this->_template_fields['extra'][ $field ]['main']['label'];
869
-        }
870
-
871
-        // now it's possible this field may just be existing in any of the extra array items.
872
-        if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
873
-            foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
874
-                if (!is_array($subfields)) {
875
-                    continue;
876
-                }
877
-                if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
878
-                    return $subfields[ $field ]['label'];
879
-                }
880
-            }
881
-        }
882
-
883
-        // if we made it here then there's no label set so let's just return the $field.
884
-        return $field;
885
-    }
886
-
887
-
888
-
889
-
890
-    /**
891
-     * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary (i.e. swap out css files or something else).
892
-     *
893
-     * @since 4.5.0
894
-     *
895
-     * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
896
-     *
897
-     * @return void
898
-     */
899
-    public function do_secondary_messenger_hooks($sending_messenger_name)
900
-    {
901
-        return;
902
-    }
431
+	/**
432
+	 * Returns the valid message types associated with this messenger.
433
+	 *
434
+	 * @since 4.5.0
435
+	 *
436
+	 * @return array
437
+	 */
438
+	public function get_valid_message_types()
439
+	{
440
+		$class = get_class($this);
441
+
442
+		// messenger specific filter
443
+		// messenger specific filter
444
+		$valid_types = apply_filters('FHEE__' . $class . '__get_valid_message_types__valid_types', $this->_valid_message_types, $this);
445
+
446
+		// all messengers filter
447
+		$valid_types = apply_filters('FHEE__EE_messenger__get_valid_message_types__valid_types', $valid_types, $this);
448
+		return $valid_types;
449
+	}
450
+
451
+
452
+
453
+
454
+
455
+	/**
456
+	 * this is just used by the custom validators (EE_Messages_Validator classes) to modify the _validator_config for certain message_type/messenger combos where a context may only use certain shortcodes etc.
457
+	 *
458
+	 * @access public
459
+	 * @param array $new_config Whatever is put in here will reset the _validator_config property
460
+	 */
461
+	public function set_validator_config($new_config)
462
+	{
463
+		$this->_validator_config = $new_config;
464
+	}
465
+
466
+
467
+
468
+
469
+	/**
470
+	 * This returns the _validator_config property
471
+	 *
472
+	 * @access public
473
+	 * @return array
474
+	 */
475
+	public function get_validator_config()
476
+	{
477
+		$class = get_class($this);
478
+
479
+		$config = apply_filters('FHEE__' . $class . '__get_validator_config', $this->_validator_config, $this);
480
+		$config = apply_filters('FHEE__EE_messenger__get_validator_config', $config, $this);
481
+		return $config;
482
+	}
483
+
484
+
485
+
486
+
487
+	/**
488
+	 * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class callback function if that page is registered via the `_admin_registered_page` property set by the child class.
489
+	 *
490
+	 * @param string $page the slug of the EE admin page
491
+	 * @param array $message_types an array of active message type objects
492
+	 * @param string $action the page action (to allow for more specific handling - i.e. edit vs. add pages)
493
+	 * @param array $extra  This is just an extra argument that can be used to pass additional data for setting up page content.
494
+	 * @access public
495
+	 * @return string content for page
496
+	 */
497
+	public function get_messenger_admin_page_content($page, $action = null, $extra = array(), $message_types = array())
498
+	{
499
+		return $this->_get_admin_page_content($page, $action, $extra, $message_types);
500
+	}
501
+
502
+
503
+
504
+	/**
505
+	 * @param $message_types
506
+	 * @param array $extra
507
+	 * @return mixed|string
508
+	 */
509
+	protected function _get_admin_content_events_edit($message_types, $extra)
510
+	{
511
+		// defaults
512
+		$template_args = array();
513
+		$selector_rows = '';
514
+
515
+		// we don't need message types here so we're just going to ignore. we do, however, expect the event id here. The event id is needed to provide a link to setup a custom template for this event.
516
+		$event_id = isset($extra['event']) ? $extra['event'] : null;
517
+
518
+		$template_wrapper_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_wrapper.template.php';
519
+		$template_row_path = EE_LIBRARIES . 'messages/messenger/admin_templates/event_switcher_row.template.php';
520
+
521
+		// array of template objects for global and custom (non-trashed) (but remember just for this messenger!)
522
+		$global_templates = EEM_Message_Template_Group::instance()->get_all(
523
+			array( array( 'MTP_messenger' => $this->name, 'MTP_is_global' => true, 'MTP_is_active' => true ) )
524
+		);
525
+		$templates_for_event = EEM_Message_Template_Group::instance()->get_all_custom_templates_by_event(
526
+			$event_id,
527
+			array(
528
+				'MTP_messenger' => $this->name,
529
+				'MTP_is_active' => true
530
+			)
531
+		);
532
+		$templates_for_event = !empty($templates_for_event) ? $templates_for_event : array();
533
+
534
+		// so we need to setup the rows for the selectors and we use the global mtpgs (cause those will the active message template groups)
535
+		foreach ($global_templates as $mtpgID => $mtpg) {
536
+			if ($mtpg instanceof EE_Message_Template_Group) {
537
+				// verify this message type is supposed to show on this page
538
+				$mtp_obj = $mtpg->message_type_obj();
539
+				if (! $mtp_obj instanceof EE_message_type) {
540
+					continue;
541
+				}
542
+				$mtp_obj->admin_registered_pages = (array) $mtp_obj->admin_registered_pages;
543
+				if (! in_array('events_edit', $mtp_obj->admin_registered_pages)) {
544
+					continue;
545
+				}
546
+				$select_values = array();
547
+				$select_values[ $mtpgID ] = esc_html__('Global', 'event_espresso');
548
+				$default_value = array_key_exists($mtpgID, $templates_for_event) && ! $mtpg->get('MTP_is_override') ? $mtpgID : null;
549
+				// if the override has been set for the global template, then that means even if there are custom templates already created we ignore them because of the set override.
550
+				if (! $mtpg->get('MTP_is_override')) {
551
+					// any custom templates for this message type?
552
+					$custom_templates = EEM_Message_Template_Group::instance()->get_custom_message_template_by_m_and_mt($this->name, $mtpg->message_type());
553
+					foreach ($custom_templates as $cmtpgID => $cmtpg) {
554
+						$select_values[ $cmtpgID ] = $cmtpg->name();
555
+						$default_value = array_key_exists($cmtpgID, $templates_for_event) ? $cmtpgID : $default_value;
556
+					}
557
+				}
558
+				// if there is no $default_value then we set it as the global
559
+				$default_value = empty($default_value) ? $mtpgID : $default_value;
560
+				$c_config = $mtpg->contexts_config();
561
+				$edit_context = key(array_slice($c_config, -1));
562
+				$edit_url_query_args = [
563
+					'page' => 'espresso_messages',
564
+					'action' => 'edit_message_template',
565
+					'id' => $default_value,
566
+					'evt_id' => $event_id,
567
+					'context' => $edit_context,
568
+				];
569
+				$edit_url = EEH_URL::add_query_args_and_nonce($edit_url_query_args, admin_url('admin.php'));
570
+				$create_url_query_args = [
571
+					'page' => 'espresso_messages',
572
+					'action' => 'add_new_message_template',
573
+					'GRP_ID' => $default_value,
574
+					'message_type' => $mtpg->message_type(),
575
+					'messenger' => $this->name
576
+				];
577
+				$create_url = EEH_URL::add_query_args_and_nonce($create_url_query_args, admin_url('admin.php'));
578
+				$st_args['mt_name'] = ucwords($mtp_obj->label['singular']);
579
+				$st_args['mt_slug'] = $mtpg->message_type();
580
+				$st_args['messenger_slug'] = $this->name;
581
+				$st_args['selector'] = EEH_Form_Fields::select_input('event_message_templates_relation[' . $mtpgID . ']', $select_values, $default_value, 'data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '"', 'message-template-selector');
582
+				// note that  message template group that has override_all_custom set will remove the ability to set a custom message template based off of the global (and that also in turn overrides any other custom templates).
583
+				$st_args['create_button'] = $mtpg->get('MTP_is_override') ? '' : '<a data-messenger="' . $this->name . '" data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $create_url . '" class="button button-small create-mtpg-button">' . esc_html__('Create New Custom', 'event_espresso') . '</a>';
584
+				$st_args['create_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_messages', 'espresso_messages_add_new_message_template') ? $st_args['create_button'] : '';
585
+				$st_args['edit_button'] = EE_Registry::instance()->CAP->current_user_can('ee_edit_message', 'espresso_messages_edit_message_template', $mtpgID) ? '<a data-messagetype="' . $mtpg->message_type() . '" data-grpid="' . $default_value . '" target="_blank" href="' . $edit_url . '" class="button button-small edit-mtpg-button">' . esc_html__('Edit', 'event_espresso') . '</a>' : '';
586
+				$selector_rows .= EEH_Template::display_template($template_row_path, $st_args, true);
587
+			}
588
+		}
589
+
590
+		// if no selectors present then get out.
591
+		if (empty($selector_rows)) {
592
+			return '';
593
+		}
594
+
595
+		$template_args['selector_rows'] = $selector_rows;
596
+		return EEH_Template::display_template($template_wrapper_path, $template_args, true);
597
+	}
598
+
599
+
600
+
601
+
602
+
603
+
604
+	/**
605
+	 * get_template_fields
606
+	 *
607
+	 * @access public
608
+	 * @return array $this->_template_fields
609
+	 */
610
+	public function get_template_fields()
611
+	{
612
+		$template_fields = apply_filters('FHEE__' . get_class($this) . '__get_template_fields', $this->_template_fields, $this);
613
+		$template_fields = apply_filters('FHEE__EE_messenger__get_template_fields', $template_fields, $this);
614
+		return $template_fields;
615
+	}
616
+
617
+
618
+
619
+
620
+	/** SETUP METHODS **/
621
+	/**
622
+	 * The following method doesn't NEED to be used by child classes but might be modified by the specific messenger
623
+	 * @param string $item
624
+	 * @param mixed $value
625
+	 */
626
+	protected function _set_template_value($item, $value)
627
+	{
628
+		if (array_key_exists($item, $this->_template_fields)) {
629
+			$prop = '_' . $item;
630
+			$this->{$prop} = $value;
631
+		}
632
+	}
633
+
634
+	/**
635
+	 * Sets up the message for sending.
636
+	 *
637
+	 * @param  EE_message $message the message object that contains details about the message.
638
+	 * @param EE_message_type $message_type The message type object used in combination with this messenger to generate the provided message.
639
+	 *
640
+	 * @return bool Very important that all messengers return bool for successful send or not.  Error messages can be
641
+	 *              added to EE_Error.
642
+	 *              true = message sent successfully
643
+	 *              false = message not sent but can be retried (i.e. the failure might be just due to communication issues at the time of send).
644
+	 *              Throwing a SendMessageException means the message failed sending and cannot be retried.
645
+	 *
646
+	 * @throws SendMessageException
647
+	 */
648
+	final public function send_message($message, EE_message_type $message_type)
649
+	{
650
+		try {
651
+			$this->_validate_and_setup($message);
652
+			$this->_incoming_message_type = $message_type;
653
+			$response = $this->_send_message();
654
+			if ($response instanceof WP_Error) {
655
+				EE_Error::add_error($response->get_error_message(), __FILE__, __FUNCTION__, __LINE__);
656
+				$response = false;
657
+			}
658
+		} catch (\Exception $e) {
659
+			// convert to an instance of SendMessageException
660
+			throw new SendMessageException($e->getMessage());
661
+		}
662
+		return $response;
663
+	}
664
+
665
+
666
+
667
+	/**
668
+	 * Sets up and returns message preview
669
+	 * @param  EE_Message $message incoming message object
670
+	 * @param EE_message_type $message_type This is whatever message type was used in combination with this messenger to generate the message.
671
+	 * @param  bool   $send    true we will actually use the _send method (for test sends). FALSE we just return preview
672
+	 * @return string          return the message html content
673
+	 */
674
+	public function get_preview(EE_Message $message, EE_message_type $message_type, $send = false)
675
+	{
676
+		$this->_validate_and_setup($message);
677
+
678
+		$this->_incoming_message_type = $message_type;
679
+
680
+		if ($send) {
681
+			// are we overriding any existing template fields?
682
+			$settings = apply_filters(
683
+				'FHEE__EE_messenger__get_preview__messenger_test_settings',
684
+				$this->get_existing_test_settings(),
685
+				$this,
686
+				$send,
687
+				$message,
688
+				$message_type
689
+			);
690
+			if (! empty($settings)) {
691
+				foreach ($settings as $field => $value) {
692
+					$this->_set_template_value($field, $value);
693
+				}
694
+			}
695
+		}
696
+
697
+		// enqueue preview js so that any links/buttons on the page are disabled.
698
+		if (! $send) {
699
+			// the below may seem like duplication.  However, typically if a messenger enqueues scripts/styles,
700
+			// it deregisters all existing wp scripts and styles first.  So the second hook ensures our previewer still gets setup.
701
+			add_action('admin_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
702
+			add_action('wp_enqueue_scripts', array( $this, 'add_preview_script' ), 10);
703
+			add_action('AHEE__EE_messenger__enqueue_scripts_styles', array( $this, 'add_preview_script' ), 10);
704
+		}
705
+
706
+		return $send ? $this->_send_message() : $this->_preview();
707
+	}
708
+
709
+
710
+
711
+
712
+	/**
713
+	 * Callback for enqueue_scripts so that we setup the preview script for all previews.
714
+	 *
715
+	 * @since 4.5.0
716
+	 *
717
+	 * @return void
718
+	 */
719
+	public function add_preview_script()
720
+	{
721
+		// error message
722
+		EE_Registry::$i18n_js_strings['links_disabled'] = wp_strip_all_tags(
723
+			__('All the links on this page have been disabled because this is a generated preview message for the purpose of ensuring layout, style, and content setup.  To test generated links, you must trigger an actual message notification.', 'event_espresso')
724
+		);
725
+		wp_register_script('ee-messages-preview-js', EE_LIBRARIES_URL . 'messages/messenger/assets/js/ee-messages-preview.js', array( 'jquery' ), EVENT_ESPRESSO_VERSION, true);
726
+		wp_localize_script('ee-messages-preview-js', 'eei18n', EE_Registry::$i18n_js_strings);
727
+		wp_enqueue_script('ee-messages-preview-js');
728
+	}
729
+
730
+
731
+
732
+
733
+	/**
734
+	 * simply validates the incoming message object and then sets up the properties for the messenger
735
+	 * @param  EE_Message $message
736
+	 * @throws EE_Error
737
+	 */
738
+	protected function _validate_and_setup(EE_Message $message)
739
+	{
740
+		$template_pack = $message->get_template_pack();
741
+		$variation = $message->get_template_pack_variation();
742
+
743
+		// verify we have the required template pack value on the $message object.
744
+		if (! $template_pack instanceof EE_Messages_Template_Pack) {
745
+			throw new EE_Error(esc_html__('Incoming $message object must have an EE_Messages_Template_Pack object available.', 'event_espresso'));
746
+		}
747
+
748
+		$this->_tmp_pack = $template_pack;
749
+
750
+		$this->_variation = $variation ? $variation : 'default';
751
+
752
+		$template_fields = $this->get_template_fields();
753
+
754
+		foreach ($template_fields as $template => $value) {
755
+			if ($template !== 'extra') {
756
+				$column_value = $message->get_field_or_extra_meta('MSG_' . $template);
757
+				$message_template_value = $column_value ? $column_value : null;
758
+				$this->_set_template_value($template, $message_template_value);
759
+			}
760
+		}
761
+	}
762
+
763
+
764
+
765
+	/**
766
+	 * Utility method for child classes to get the contents of a template file and return
767
+	 *
768
+	 * We're assuming the child messenger class has already setup template args!
769
+	 * @param  bool $preview if true we use the preview wrapper otherwise we use main wrapper.
770
+	 * @return string
771
+	 * @throws \EE_Error
772
+	 */
773
+	protected function _get_main_template($preview = false)
774
+	{
775
+		$type = $preview ? 'preview' : 'main';
776
+
777
+		$wrapper_template = $this->_tmp_pack->get_wrapper($this->name, $type);
778
+
779
+		// check file exists and is readable
780
+		if (!is_readable($wrapper_template)) {
781
+			throw new EE_Error(sprintf(esc_html__('Unable to access the template file for the %s messenger main content wrapper.  The location being attempted is %s.', 'event_espresso'), ucwords($this->label['singular']), $wrapper_template));
782
+		}
783
+
784
+		// add message type to template args
785
+		$this->_template_args['message_type'] = $this->_incoming_message_type;
786
+
787
+		return EEH_Template::display_template($wrapper_template, $this->_template_args, true);
788
+	}
789
+
790
+
791
+
792
+	/**
793
+	 * set the _test_settings_fields property
794
+	 *
795
+	 * @access protected
796
+	 * @return void
797
+	 */
798
+	protected function _set_test_settings_fields()
799
+	{
800
+		$this->_test_settings_fields = array();
801
+	}
802
+
803
+
804
+
805
+	/**
806
+	 * return the _test_settings_fields property
807
+	 * @return array
808
+	 */
809
+	public function get_test_settings_fields()
810
+	{
811
+		return $this->_test_settings_fields;
812
+	}
813
+
814
+
815
+
816
+
817
+	/**
818
+	 * This just returns any existing test settings that might be saved in the database
819
+	 *
820
+	 * @access public
821
+	 * @return array
822
+	 */
823
+	public function get_existing_test_settings()
824
+	{
825
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
826
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
827
+		$settings = $Message_Resource_Manager->get_active_messengers_option();
828
+		return isset($settings[ $this->name ]['test_settings']) ? $settings[ $this->name ]['test_settings'] : array();
829
+	}
830
+
831
+
832
+
833
+	/**
834
+	 * All this does is set the existing test settings (in the db) for the messenger
835
+	 *
836
+	 * @access public
837
+	 * @param $settings
838
+	 * @return bool success/fail
839
+	 */
840
+	public function set_existing_test_settings($settings)
841
+	{
842
+		/** @var EE_Message_Resource_Manager $Message_Resource_Manager */
843
+		$Message_Resource_Manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
844
+		$existing = $Message_Resource_Manager->get_active_messengers_option();
845
+		$existing[ $this->name ]['test_settings'] = $settings;
846
+		return $Message_Resource_Manager->update_active_messengers_option($existing);
847
+	}
848
+
849
+
850
+
851
+	/**
852
+	 * This just returns the field label for a given field setup in the _template_fields property.
853
+	 *
854
+	 * @since   4.3.0
855
+	 *
856
+	 * @param string $field The field to retrieve the label for
857
+	 * @return string             The label
858
+	 */
859
+	public function get_field_label($field)
860
+	{
861
+		// first let's see if the field requests is in the top level array.
862
+		if (isset($this->_template_fields[ $field ]) && !empty($this->_template_fields[ $field ]['label'])) {
863
+			return $this->_template[ $field ]['label'];
864
+		}
865
+
866
+		// nope so let's look in the extra array to see if it's there HOWEVER if the field exists as a top level index in the extra array then we know the label is in the 'main' index.
867
+		if (isset($this->_template_fields['extra']) && !empty($this->_template_fields['extra'][ $field ]) && !empty($this->_template_fields['extra'][ $field ]['main']['label'])) {
868
+			return $this->_template_fields['extra'][ $field ]['main']['label'];
869
+		}
870
+
871
+		// now it's possible this field may just be existing in any of the extra array items.
872
+		if (!empty($this->_template_fields['extra']) && is_array($this->_template_fields['extra'])) {
873
+			foreach ($this->_template_fields['extra'] as $main_field => $subfields) {
874
+				if (!is_array($subfields)) {
875
+					continue;
876
+				}
877
+				if (isset($subfields[ $field ]) && !empty($subfields[ $field ]['label'])) {
878
+					return $subfields[ $field ]['label'];
879
+				}
880
+			}
881
+		}
882
+
883
+		// if we made it here then there's no label set so let's just return the $field.
884
+		return $field;
885
+	}
886
+
887
+
888
+
889
+
890
+	/**
891
+	 * This is a method called from EE_messages when this messenger is a generating messenger and the sending messenger is a different messenger.  Child messengers can set hooks for the sending messenger to callback on if necessary (i.e. swap out css files or something else).
892
+	 *
893
+	 * @since 4.5.0
894
+	 *
895
+	 * @param string $sending_messenger_name the name of the sending messenger so we only set the hooks needed.
896
+	 *
897
+	 * @return void
898
+	 */
899
+	public function do_secondary_messenger_hooks($sending_messenger_name)
900
+	{
901
+		return;
902
+	}
903 903
 }
Please login to merge, or discard this patch.