Completed
Branch BUG/batch-strings-overridden (415991)
by
unknown
09:29 queued 38s
created
core/EE_Data_Migration_Manager.core.php 2 patches
Indentation   +1234 added lines, -1234 removed lines patch added patch discarded remove patch
@@ -32,1238 +32,1238 @@
 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
-     * string indicating the migration should continue
63
-     */
64
-    const status_continue = 'status_continue';
65
-    /**
66
-     * string indicating the migration has completed and should be ended
67
-     */
68
-    const status_completed = 'status_completed';
69
-    /**
70
-     * string indicating a fatal error occurred and the data migration should be completely aborted
71
-     */
72
-    const status_fatal_error = 'status_fatal_error';
73
-
74
-    /**
75
-     * the number of 'items' (usually DB rows) to migrate on each 'step' (ajax request sent
76
-     * during migration)
77
-     */
78
-    const step_size = 50;
79
-
80
-    /**
81
-     * option name that stores the queue of ee plugins needing to have
82
-     * their data initialized (or re-initialized) once we are done migrations
83
-     */
84
-    const db_init_queue_option_name = 'ee_db_init_queue';
85
-    /**
86
-     * Array of information concerning data migrations that have ran in the history
87
-     * of this EE installation. Keys should be the name of the version the script upgraded to
88
-     *
89
-     * @var EE_Data_Migration_Script_Base[]
90
-     */
91
-    private $_data_migrations_ran = null;
92
-    /**
93
-     * The last ran script. It's nice to store this somewhere accessible, as its easiest
94
-     * to know which was the last run by which is the newest wp option; but in most of the code
95
-     * we just use the local $_data_migration_ran array, which organized the scripts differently
96
-     *
97
-     * @var EE_Data_Migration_Script_Base
98
-     */
99
-    private $_last_ran_script = null;
100
-
101
-    /**
102
-     * Similarly to _last_ran_script, but this is the last INCOMPLETE migration script.
103
-     *
104
-     * @var EE_Data_Migration_Script_Base
105
-     */
106
-    private $_last_ran_incomplete_script = null;
107
-    /**
108
-     * array where keys are classnames, and values are filepaths of all the known migration scripts
109
-     *
110
-     * @var array
111
-     */
112
-    private $_data_migration_class_to_filepath_map;
113
-
114
-    /**
115
-     * the following 4 properties are fully set on construction.
116
-     * Note: the first two apply to whether to continue running ALL migration scripts (ie, even though we're finished
117
-     * one, we may want to start the next one); whereas the last two indicate whether to continue running a single
118
-     * data migration script
119
-     *
120
-     * @var array
121
-     */
122
-    public $stati_that_indicate_to_continue_migrations = array();
123
-
124
-    public $stati_that_indicate_to_stop_migrations = array();
125
-
126
-    public $stati_that_indicate_to_continue_single_migration_script = array();
127
-
128
-    public $stati_that_indicate_to_stop_single_migration_script = array();
129
-
130
-    /**
131
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
132
-     */
133
-    protected $_table_manager;
134
-
135
-    /**
136
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
137
-     */
138
-    protected $_table_analysis;
139
-
140
-    /**
141
-     * @var array $script_migration_versions
142
-     */
143
-    protected $script_migration_versions;
144
-
145
-    /**
146
-     * @var EE_Data_Migration_Manager $_instance
147
-     * @access    private
148
-     */
149
-    private static $_instance = null;
150
-
151
-
152
-    /**
153
-     * @singleton method used to instantiate class object
154
-     * @access    public
155
-     * @return EE_Data_Migration_Manager instance
156
-     */
157
-    public static function instance()
158
-    {
159
-        // check if class object is instantiated
160
-        if (! self::$_instance instanceof EE_Data_Migration_Manager) {
161
-            self::$_instance = new self();
162
-        }
163
-        return self::$_instance;
164
-    }
165
-
166
-    /**
167
-     * resets the singleton to its brand-new state (but does NOT delete old references to the old singleton. Meaning,
168
-     * all new usages of the singleton should be made with Classname::instance()) and returns it
169
-     *
170
-     * @return EE_Data_Migration_Manager
171
-     */
172
-    public static function reset()
173
-    {
174
-        self::$_instance = null;
175
-        return self::instance();
176
-    }
177
-
178
-
179
-    /**
180
-     * constructor
181
-     */
182
-    private function __construct()
183
-    {
184
-        $this->stati_that_indicate_to_continue_migrations = array(
185
-            self::status_continue,
186
-            self::status_completed,
187
-        );
188
-        $this->stati_that_indicate_to_stop_migrations = array(
189
-            self::status_fatal_error,
190
-            self::status_no_more_migration_scripts,
191
-        );
192
-        $this->stati_that_indicate_to_continue_single_migration_script = array(
193
-            self::status_continue,
194
-        );
195
-        $this->stati_that_indicate_to_stop_single_migration_script = array(
196
-            self::status_completed,
197
-            self::status_fatal_error
198
-            // note: status_no_more_migration_scripts doesn't apply
199
-        );
200
-        // make sure we've included the base migration script, because we may need the EE_DMS_Unknown_1_0_0 class
201
-        // to be defined, because right now it doesn't get autoloaded on its own
202
-        EE_Registry::instance()->load_core('Data_Migration_Class_Base', array(), true);
203
-        EE_Registry::instance()->load_core('Data_Migration_Script_Base', array(), true);
204
-        EE_Registry::instance()->load_core('DMS_Unknown_1_0_0', array(), true);
205
-        EE_Registry::instance()->load_core('Data_Migration_Script_Stage', array(), true);
206
-        EE_Registry::instance()->load_core('Data_Migration_Script_Stage_Table', array(), true);
207
-        $this->_table_manager = EE_Registry::instance()->create('TableManager', array(), true);
208
-        $this->_table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
209
-    }
210
-
211
-
212
-    /**
213
-     * Deciphers, from an option's name, what plugin and version it relates to (see _save_migrations_ran to see what
214
-     * the option names are like, but generally they're like
215
-     * 'ee_data_migration_script_Core.4.1.0' in 4.2 or 'ee_data_migration_script_4.1.0' before that).
216
-     * The option name shouldn't ever be like 'ee_data_migration_script_Core.4.1.0.reg' because it's derived,
217
-     * indirectly, from the data migration's classname, which should always be like EE_DMS_%s_%d_%d_%d.dms.php (eg
218
-     * EE_DMS_Core_4_1_0.dms.php)
219
-     *
220
-     * @param string $option_name (see EE_Data_Migration_Manage::_save_migrations_ran() where the option name is set)
221
-     * @return array where the first item is the plugin slug (eg 'Core','Calendar',etc) and the 2nd is the version of
222
-     *               that plugin (eg '4.1.0')
223
-     */
224
-    private function _get_plugin_slug_and_version_string_from_dms_option_name($option_name)
225
-    {
226
-        $plugin_slug_and_version_string = str_replace(
227
-            EE_Data_Migration_Manager::data_migration_script_option_prefix,
228
-            "",
229
-            $option_name
230
-        );
231
-        // check if $plugin_slug_and_version_string is like '4.1.0' (4.1-style) or 'Core.4.1.0' (4.2-style)
232
-        $parts = explode(".", $plugin_slug_and_version_string);
233
-
234
-        if (count($parts) == 4) {
235
-            // it's 4.2-style.eg Core.4.1.0
236
-            $plugin_slug = $parts[0];// eg Core
237
-            $version_string = $parts[1] . "." . $parts[2] . "." . $parts[3]; // eg 4.1.0
238
-        } else {
239
-            // it's 4.1-style: eg 4.1.0
240
-            $plugin_slug = 'Core';
241
-            $version_string = $plugin_slug_and_version_string;// eg 4.1.0
242
-        }
243
-        return array($plugin_slug, $version_string);
244
-    }
245
-
246
-    /**
247
-     * Gets the DMS class from the wordpress option, otherwise throws an EE_Error if it's not
248
-     * for a known DMS class.
249
-     *
250
-     * @param string $dms_option_name
251
-     * @param string $dms_option_value (serialized)
252
-     * @return EE_Data_Migration_Script_Base
253
-     * @throws EE_Error
254
-     */
255
-    private function _get_dms_class_from_wp_option($dms_option_name, $dms_option_value)
256
-    {
257
-        $data_migration_data = maybe_unserialize($dms_option_value);
258
-        if (isset($data_migration_data['class']) && class_exists($data_migration_data['class'])) {
259
-            $class = new $data_migration_data['class'];
260
-            if ($class instanceof EE_Data_Migration_Script_Base) {
261
-                $class->instantiate_from_array_of_properties($data_migration_data);
262
-                return $class;
263
-            } else {
264
-                // huh, so its an object but not a data migration script?? that shouldn't happen
265
-                // just leave it as an array (which will probably just get ignored)
266
-                throw new EE_Error(
267
-                    sprintf(
268
-                        __(
269
-                            "Trying to retrieve DMS class from wp option. No DMS by the name '%s' exists",
270
-                            'event_espresso'
271
-                        ),
272
-                        $data_migration_data['class']
273
-                    )
274
-                );
275
-            }
276
-        } else {
277
-            // 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
278
-            throw new EE_Error(
279
-                sprintf(__("The wp option  with key '%s' does not represent a DMS", 'event_espresso'), $dms_option_name)
280
-            );
281
-        }
282
-    }
283
-
284
-    /**
285
-     * Gets the array describing what data migrations have run. Also has a side-effect of recording which was the last
286
-     * ran, and which was the last ran which hasn't finished yet
287
-     *
288
-     * @return array where each element should be an array of EE_Data_Migration_Script_Base (but also has a few legacy
289
-     *               arrays in there - which should probably be ignored)
290
-     */
291
-    public function get_data_migrations_ran()
292
-    {
293
-        if (! $this->_data_migrations_ran) {
294
-            // setup autoloaders for each of the scripts in there
295
-            $this->get_all_data_migration_scripts_available();
296
-            $data_migrations_options = $this->get_all_migration_script_options(
297
-            );// get_option(EE_Data_Migration_Manager::data_migrations_option_name,get_option('espresso_data_migrations',array()));
298
-
299
-            $data_migrations_ran = array();
300
-            // convert into data migration script classes where possible
301
-            foreach ($data_migrations_options as $data_migration_option) {
302
-                list($plugin_slug, $version_string) = $this->_get_plugin_slug_and_version_string_from_dms_option_name(
303
-                    $data_migration_option['option_name']
304
-                );
305
-
306
-                try {
307
-                    $class = $this->_get_dms_class_from_wp_option(
308
-                        $data_migration_option['option_name'],
309
-                        $data_migration_option['option_value']
310
-                    );
311
-                    $data_migrations_ran[ $plugin_slug ][ $version_string ] = $class;
312
-                    // ok so far THIS is the 'last-ran-script'... unless we find another on next iteration
313
-                    $this->_last_ran_script = $class;
314
-                    if (! $class->is_completed()) {
315
-                        // sometimes we also like to know which was the last incomplete script (or if there are any at all)
316
-                        $this->_last_ran_incomplete_script = $class;
317
-                    }
318
-                } catch (EE_Error $e) {
319
-                    // ok so its not a DMS. We'll just keep it, although other code will need to expect non-DMSs
320
-                    $data_migrations_ran[ $plugin_slug ][ $version_string ] = maybe_unserialize(
321
-                        $data_migration_option['option_value']
322
-                    );
323
-                }
324
-            }
325
-            // so here the array of $data_migrations_ran is actually a mix of classes and a few legacy arrays
326
-            $this->_data_migrations_ran = $data_migrations_ran;
327
-            if (! $this->_data_migrations_ran || ! is_array($this->_data_migrations_ran)) {
328
-                $this->_data_migrations_ran = array();
329
-            }
330
-        }
331
-        return $this->_data_migrations_ran;
332
-    }
333
-
334
-
335
-    /**
336
-     *
337
-     * @param string $script_name eg 'DMS_Core_4_1_0'
338
-     * @param string $old_table   eg 'wp_events_detail'
339
-     * @param string $old_pk      eg 'wp_esp_posts'
340
-     * @param        $new_table
341
-     * @return mixed string or int
342
-     */
343
-    public function get_mapping_new_pk($script_name, $old_table, $old_pk, $new_table)
344
-    {
345
-        $script = EE_Registry::instance()->load_dms($script_name);
346
-        $mapping = $script->get_mapping_new_pk($old_table, $old_pk, $new_table);
347
-        return $mapping;
348
-    }
349
-
350
-    /**
351
-     * Gets all the options containing migration scripts that have been run. Ordering is important: it's assumed that
352
-     * the last option returned in this array is the most-recently ran DMS option
353
-     *
354
-     * @return array
355
-     */
356
-    public function get_all_migration_script_options()
357
-    {
358
-        global $wpdb;
359
-        return $wpdb->get_results(
360
-            "SELECT * FROM {$wpdb->options} WHERE option_name like '" . EE_Data_Migration_Manager::data_migration_script_option_prefix . "%' ORDER BY option_id ASC",
361
-            ARRAY_A
362
-        );
363
-    }
364
-
365
-    /**
366
-     * Gets the array of folders which contain data migration scripts. Also adds them to be auto-loaded
367
-     *
368
-     * @return array where each value is the full folder path of a folder containing data migration scripts, WITH
369
-     *               slashes at the end of the folder name.
370
-     */
371
-    public function get_data_migration_script_folders()
372
-    {
373
-        return apply_filters(
374
-            'FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',
375
-            array('Core' => EE_CORE . 'data_migration_scripts')
376
-        );
377
-    }
378
-
379
-    /**
380
-     * Gets the version the migration script upgrades to
381
-     *
382
-     * @param string $migration_script_name eg 'EE_DMS_Core_4_1_0'
383
-     * @return array {
384
-     * @type string  $slug                  like 'Core','Calendar',etc
385
-     * @type string  $version               like 4.3.0
386
-     *                                      }
387
-     * @throws EE_Error
388
-     */
389
-    public function script_migrates_to_version($migration_script_name, $eeAddonClass = '')
390
-    {
391
-        if (isset($this->script_migration_versions[ $migration_script_name ])) {
392
-            return $this->script_migration_versions[ $migration_script_name ];
393
-        }
394
-        $dms_info = $this->parse_dms_classname($migration_script_name);
395
-        $this->script_migration_versions[ $migration_script_name ] = array(
396
-            'slug'    => $eeAddonClass !== '' ? $eeAddonClass : $dms_info['slug'],
397
-            'version' => $dms_info['major_version'] . "." . $dms_info['minor_version'] . "." . $dms_info['micro_version'],
398
-        );
399
-        return $this->script_migration_versions[ $migration_script_name ];
400
-    }
401
-
402
-    /**
403
-     * Gets the juicy details out of a dms filename like 'EE_DMS_Core_4_1_0'
404
-     *
405
-     * @param string $classname
406
-     * @return array with keys 'slug','major_version','minor_version', and 'micro_version' (the last 3 are ints)
407
-     * @throws EE_Error
408
-     */
409
-    public function parse_dms_classname($classname)
410
-    {
411
-        $matches = array();
412
-        preg_match('~EE_DMS_(.*)_([0-9]*)_([0-9]*)_([0-9]*)~', $classname, $matches);
413
-        if (! $matches || ! (isset($matches[1]) && isset($matches[2]) && isset($matches[3]))) {
414
-            throw new EE_Error(
415
-                sprintf(
416
-                    __(
417
-                        "%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, ",
418
-                        "event_espresso"
419
-                    ),
420
-                    $classname
421
-                )
422
-            );
423
-        }
424
-        return array(
425
-            'slug'          => $matches[1],
426
-            'major_version' => intval($matches[2]),
427
-            'minor_version' => intval($matches[3]),
428
-            'micro_version' => intval($matches[4]),
429
-        );
430
-    }
431
-
432
-    /**
433
-     * Ensures that the option indicating the current DB version is set. This should only be
434
-     * a concern when activating EE for the first time, THEORETICALLY.
435
-     * 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
436
-     * to 4.1.x.
437
-     *
438
-     * @return string of current db state
439
-     */
440
-    public function ensure_current_database_state_is_set()
441
-    {
442
-        $espresso_db_core_updates = get_option('espresso_db_update', array());
443
-        $db_state = get_option(EE_Data_Migration_Manager::current_database_state);
444
-        if (! $db_state) {
445
-            // mark the DB as being in the state as the last version in there.
446
-            // this is done to trigger maintenance mode and do data migration scripts
447
-            // if the admin installed this version of EE over 3.1.x or 4.0.x
448
-            // otherwise, the normal maintenance mode code is fine
449
-            $previous_versions_installed = array_keys($espresso_db_core_updates);
450
-            $previous_version_installed = end($previous_versions_installed);
451
-            if (version_compare('4.1.0', $previous_version_installed)) {
452
-                // last installed version was less than 4.1
453
-                // so we want the data migrations to happen. SO, we're going to say the DB is at that state
454
-                $db_state = array('Core' => $previous_version_installed);
455
-            } else {
456
-                $db_state = array('Core' => EVENT_ESPRESSO_VERSION);
457
-            }
458
-            update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
459
-        }
460
-        // in 4.1, $db_state would have only been a simple string like '4.1.0',
461
-        // but in 4.2+ it should be an array with at least key 'Core' and the value of that plugin's
462
-        // db, and possibly other keys for other addons like 'Calendar','Permissions',etc
463
-        if (! is_array($db_state)) {
464
-            $db_state = array('Core' => $db_state);
465
-            update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
466
-        }
467
-        return $db_state;
468
-    }
469
-
470
-    /**
471
-     * Checks if there are any data migration scripts that ought to be run. If found,
472
-     * returns the instantiated classes. If none are found (ie, they've all already been run
473
-     * or they don't apply), returns an empty array
474
-     *
475
-     * @return EE_Data_Migration_Script_Base[]
476
-     */
477
-    public function check_for_applicable_data_migration_scripts()
478
-    {
479
-        // get the option describing what options have already run
480
-        $scripts_ran = $this->get_data_migrations_ran();
481
-        // $scripts_ran = array('4.1.0.core'=>array('monkey'=>null));
482
-        $script_class_and_filepaths_available = $this->get_all_data_migration_scripts_available();
483
-
484
-
485
-        $current_database_state = $this->ensure_current_database_state_is_set();
486
-        // determine which have already been run
487
-        $script_classes_that_should_run_per_iteration = array();
488
-        $iteration = 0;
489
-        $next_database_state_to_consider = $current_database_state;
490
-        $theoretical_database_state = null;
491
-        do {
492
-            // the next state after the currently-considered one will start off looking the same as the current, but we may make additions...
493
-            $theoretical_database_state = $next_database_state_to_consider;
494
-            // the next db state to consider is "what would the DB be like had we run all the scripts we found that applied last time?)
495
-            foreach ($script_class_and_filepaths_available as $classname => $filepath) {
496
-                $migrates_to_version = $this->script_migrates_to_version($classname);
497
-                $script_converts_plugin_slug = $migrates_to_version['slug'];
498
-                $script_converts_to_version = $migrates_to_version['version'];
499
-                // check if this version script is DONE or not; or if it's never been ran
500
-                if (! $scripts_ran ||
501
-                    ! isset($scripts_ran[ $script_converts_plugin_slug ]) ||
502
-                    ! isset($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ])) {
503
-                    // we haven't ran this conversion script before
504
-                    // now check if it applies... note that we've added an autoloader for it on get_all_data_migration_scripts_available
505
-                    $script = new $classname($this->_get_table_manager(), $this->_get_table_analysis());
506
-                    /* @var $script EE_Data_Migration_Script_Base */
507
-                    $can_migrate = $script->can_migrate_from_version($theoretical_database_state);
508
-                    if ($can_migrate) {
509
-                        $script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
510
-                        $migrates_to_version = $script->migrates_to_version();
511
-                        $next_database_state_to_consider[ $migrates_to_version['slug'] ] = $migrates_to_version['version'];
512
-                        unset($script_class_and_filepaths_available[ $classname ]);
513
-                    }
514
-                } elseif ($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ] instanceof EE_Data_Migration_Script_Base) {
515
-                    // this script has been ran, or at least started
516
-                    $script = $scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ];
517
-                    if ($script->get_status() != self::status_completed) {
518
-                        // this script is already underway... keep going with it
519
-                        $script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
520
-                        $migrates_to_version = $script->migrates_to_version();
521
-                        $next_database_state_to_consider[ $migrates_to_version['slug'] ] = $migrates_to_version['version'];
522
-                        unset($script_class_and_filepaths_available[ $classname ]);
523
-                    } else {
524
-                        // it must have a status that indicates it has finished, so we don't want to try and run it again
525
-                    }
526
-                } else {
527
-                    // it exists but it's not  a proper data migration script
528
-                    // maybe the script got renamed? or was simply removed from EE?
529
-                    // either way, its certainly not runnable!
530
-                }
531
-            }
532
-            $iteration++;
533
-        } while ($next_database_state_to_consider != $theoretical_database_state && $iteration < 6);
534
-        // ok we have all the scripts that should run, now let's make them into flat array
535
-        $scripts_that_should_run = array();
536
-        foreach ($script_classes_that_should_run_per_iteration as $scripts_at_priority) {
537
-            ksort($scripts_at_priority);
538
-            foreach ($scripts_at_priority as $scripts) {
539
-                foreach ($scripts as $script) {
540
-                    $scripts_that_should_run[ get_class($script) ] = $script;
541
-                }
542
-            }
543
-        }
544
-
545
-        do_action(
546
-            'AHEE__EE_Data_Migration_Manager__check_for_applicable_data_migration_scripts__scripts_that_should_run',
547
-            $scripts_that_should_run
548
-        );
549
-        return $scripts_that_should_run;
550
-    }
551
-
552
-
553
-    /**
554
-     * Gets the script which is currently being ran, if there is one. If $include_completed_scripts is set to TRUE
555
-     * it will return the last ran script even if its complete.
556
-     * This means: if you want to find the currently-executing script, leave it as FALSE.
557
-     * If you really just want to find the script which ran most recently, regardless of status, leave it as TRUE.
558
-     *
559
-     * @param bool $include_completed_scripts
560
-     * @return EE_Data_Migration_Script_Base
561
-     */
562
-    public function get_last_ran_script($include_completed_scripts = false)
563
-    {
564
-        // make sure we've setup the class properties _last_ran_script and _last_ran_incomplete_script
565
-        if (! $this->_data_migrations_ran) {
566
-            $this->get_data_migrations_ran();
567
-        }
568
-        if ($include_completed_scripts) {
569
-            return $this->_last_ran_script;
570
-        } else {
571
-            return $this->_last_ran_incomplete_script;
572
-        }
573
-    }
574
-
575
-
576
-    /**
577
-     * Runs the data migration scripts (well, each request to this method calls one of the
578
-     * data migration scripts' migration_step() functions).
579
-     *
580
-     * @param int   $step_size
581
-     * @throws EE_Error
582
-     * @return array {
583
-     *                                  // where the first item is one EE_Data_Migration_Script_Base's stati,
584
-     *                                  //and the second item is a string describing what was done
585
-     * @type int    $records_to_migrate from the current migration script
586
-     * @type int    $records_migrated
587
-     * @type string $status             one of EE_Data_Migration_Manager::status_*
588
-     * @type string $script             verbose name of the current DMS
589
-     * @type string $message            string describing what was done during this step
590
-     *                                  }
591
-     */
592
-    public function migration_step($step_size = 0)
593
-    {
594
-
595
-        // bandaid fix for issue https://events.codebasehq.com/projects/event-espresso/tickets/7535
596
-        if (class_exists('EE_CPT_Strategy')) {
597
-            remove_action('pre_get_posts', array(EE_CPT_Strategy::instance(), 'pre_get_posts'), 5);
598
-        }
599
-
600
-        try {
601
-            $currently_executing_script = $this->get_last_ran_script();
602
-            if (! $currently_executing_script) {
603
-                // Find the next script that needs to execute
604
-                $scripts = $this->check_for_applicable_data_migration_scripts();
605
-                if (! $scripts) {
606
-                    // huh, no more scripts to run... apparently we're done!
607
-                    // but dont forget to make sure initial data is there
608
-                    // we should be good to allow them to exit maintenance mode now
609
-                    EE_Maintenance_Mode::instance()->set_maintenance_level(
610
-                        intval(EE_Maintenance_Mode::level_0_not_in_maintenance)
611
-                    );
612
-                    // saving migrations ran should actually be unnecessary, but leaving in place just in case
613
-                    // remember this migration was finished (even if we timeout initing db for core and plugins)
614
-                    $this->_save_migrations_ran();
615
-                    // make sure DB was updated AFTER we've recorded the migration was done
616
-                    $this->initialize_db_for_enqueued_ee_plugins();
617
-                    return array(
618
-                        'records_to_migrate' => 1,
619
-                        'records_migrated'   => 1,
620
-                        'status'             => self::status_no_more_migration_scripts,
621
-                        'script'             => __("Data Migration Completed Successfully", "event_espresso"),
622
-                        'message'            => __("All done!", "event_espresso"),
623
-                    );
624
-                }
625
-                $currently_executing_script = array_shift($scripts);
626
-                // and add to the array/wp option showing the scripts ran
627
-
628
-                $migrates_to = $this->script_migrates_to_version(get_class($currently_executing_script));
629
-                $plugin_slug = $migrates_to['slug'];
630
-                $version = $migrates_to['version'];
631
-                $this->_data_migrations_ran[ $plugin_slug ][ $version ] = $currently_executing_script;
632
-            }
633
-            $current_script_name = get_class($currently_executing_script);
634
-        } catch (Exception $e) {
635
-            // an exception occurred while trying to get migration scripts
636
-
637
-            $message = sprintf(
638
-                __("Error Message: %sStack Trace:%s", "event_espresso"),
639
-                $e->getMessage() . '<br>',
640
-                $e->getTraceAsString()
641
-            );
642
-            // record it on the array of data migration scripts ran. This will be overwritten next time we try and try to run data migrations
643
-            // but that's ok-- it's just an FYI to support that we couldn't even run any data migrations
644
-            $this->add_error_to_migrations_ran(
645
-                sprintf(__("Could not run data migrations because: %s", "event_espresso"), $message)
646
-            );
647
-            return array(
648
-                'records_to_migrate' => 1,
649
-                'records_migrated'   => 0,
650
-                'status'             => self::status_fatal_error,
651
-                'script'             => __("Error loading data migration scripts", "event_espresso"),
652
-                'message'            => $message,
653
-            );
654
-        }
655
-        // ok so we definitely have a data migration script
656
-        try {
657
-            // how big of a bite do we want to take? Allow users to easily override via their wp-config
658
-            if (absint($step_size) < 1) {
659
-                $step_size = defined('EE_MIGRATION_STEP_SIZE') && absint(EE_MIGRATION_STEP_SIZE)
660
-                    ? EE_MIGRATION_STEP_SIZE : EE_Data_Migration_Manager::step_size;
661
-            }
662
-            // do what we came to do!
663
-            $currently_executing_script->migration_step($step_size);
664
-            // can we wrap it up and verify default data?
665
-            $init_dbs = false;
666
-            switch ($currently_executing_script->get_status()) {
667
-                case EE_Data_Migration_Manager::status_continue:
668
-                    $response_array = array(
669
-                        'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
670
-                        'records_migrated'   => $currently_executing_script->count_records_migrated(),
671
-                        'status'             => EE_Data_Migration_Manager::status_continue,
672
-                        'message'            => $currently_executing_script->get_feedback_message(),
673
-                        'script'             => $currently_executing_script->pretty_name(),
674
-                    );
675
-                    break;
676
-                case EE_Data_Migration_Manager::status_completed:
677
-                    // ok so THAT script has completed
678
-                    $this->update_current_database_state_to($this->script_migrates_to_version($current_script_name));
679
-                    $response_array = array(
680
-                        'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
681
-                        'records_migrated'   => $currently_executing_script->count_records_migrated(),
682
-                        'status'             => EE_Data_Migration_Manager::status_completed,
683
-                        'message'            => $currently_executing_script->get_feedback_message(),
684
-                        'script'             => sprintf(
685
-                            __("%s Completed", 'event_espresso'),
686
-                            $currently_executing_script->pretty_name()
687
-                        ),
688
-                    );
689
-                    // check if there are any more after this one.
690
-                    $scripts_remaining = $this->check_for_applicable_data_migration_scripts();
691
-                    if (! $scripts_remaining) {
692
-                        // we should be good to allow them to exit maintenance mode now
693
-                        EE_Maintenance_Mode::instance()->set_maintenance_level(
694
-                            intval(EE_Maintenance_Mode::level_0_not_in_maintenance)
695
-                        );
696
-                        // huh, no more scripts to run... apparently we're done!
697
-                        // but dont forget to make sure initial data is there
698
-                        $init_dbs = true;
699
-                        $response_array['status'] = self::status_no_more_migration_scripts;
700
-                    }
701
-                    break;
702
-                default:
703
-                    $response_array = array(
704
-                        'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
705
-                        'records_migrated'   => $currently_executing_script->count_records_migrated(),
706
-                        'status'             => $currently_executing_script->get_status(),
707
-                        'message'            => sprintf(
708
-                            __("Minor errors occurred during %s: %s", "event_espresso"),
709
-                            $currently_executing_script->pretty_name(),
710
-                            implode(", ", $currently_executing_script->get_errors())
711
-                        ),
712
-                        'script'             => $currently_executing_script->pretty_name(),
713
-                    );
714
-                    break;
715
-            }
716
-        } catch (Exception $e) {
717
-            // ok so some exception was thrown which killed the data migration script
718
-            // double-check we have a real script
719
-            if ($currently_executing_script instanceof EE_Data_Migration_Script_Base) {
720
-                $script_name = $currently_executing_script->pretty_name();
721
-                $currently_executing_script->set_broken();
722
-                $currently_executing_script->add_error($e->getMessage());
723
-            } else {
724
-                $script_name = __("Error getting Migration Script", "event_espresso");
725
-            }
726
-            $response_array = array(
727
-                'records_to_migrate' => 1,
728
-                'records_migrated'   => 0,
729
-                'status'             => self::status_fatal_error,
730
-                'message'            => sprintf(
731
-                    __("A fatal error occurred during the migration: %s", "event_espresso"),
732
-                    $e->getMessage()
733
-                ),
734
-                'script'             => $script_name,
735
-            );
736
-        }
737
-        $successful_save = $this->_save_migrations_ran();
738
-        if ($successful_save !== true) {
739
-            // ok so the current wp option didn't save. that's tricky, because we'd like to update it
740
-            // and mark it as having a fatal error, but remember- WE CAN'T SAVE THIS WP OPTION!
741
-            // however, if we throw an exception, and return that, then the next request
742
-            // won't have as much info in it, and it may be able to save
743
-            throw new EE_Error(
744
-                sprintf(
745
-                    __(
746
-                        "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.",
747
-                        "event_espresso"
748
-                    ),
749
-                    $successful_save
750
-                )
751
-            );
752
-        }
753
-        // if we're all done, initialize EE plugins' default data etc.
754
-        if ($init_dbs) {
755
-            $this->initialize_db_for_enqueued_ee_plugins();
756
-        }
757
-        return $response_array;
758
-    }
759
-
760
-
761
-    /**
762
-     * Echo out JSON response to migration script AJAX requests. Takes precautions
763
-     * to buffer output so that we don't throw junk into our json.
764
-     *
765
-     * @return array with keys:
766
-     * 'records_to_migrate' which counts ALL the records for the current migration, and should remain constant. (ie,
767
-     * it's NOT the count of hwo many remain)
768
-     * 'records_migrated' which also counts ALL the records which have been migrated (ie, percent_complete =
769
-     * records_migrated/records_to_migrate)
770
-     * 'status'=>a string, one of EE_Data_migration_Manager::status_*
771
-     * 'message'=>a string, containing any message you want to show to the user. We may decide to split this up into
772
-     * errors, notifications, and successes
773
-     * 'script'=>a pretty name of the script currently running
774
-     */
775
-    public function response_to_migration_ajax_request()
776
-    {
777
-        ob_start();
778
-        try {
779
-            $response = $this->migration_step();
780
-        } catch (Exception $e) {
781
-            $response = array(
782
-                'records_to_migrate' => 0,
783
-                'records_migrated'   => 0,
784
-                'status'             => EE_Data_Migration_Manager::status_fatal_error,
785
-                'message'            => sprintf(
786
-                    __("Unknown fatal error occurred: %s", "event_espresso"),
787
-                    $e->getMessage()
788
-                ),
789
-                'script'             => 'Unknown',
790
-            );
791
-            $this->add_error_to_migrations_ran($e->getMessage() . "; Stack trace:" . $e->getTraceAsString());
792
-        }
793
-        $warnings_etc = @ob_get_contents();
794
-        ob_end_clean();
795
-        $response['message'] .= $warnings_etc;
796
-        return $response;
797
-    }
798
-
799
-    /**
800
-     * Updates the wordpress option that keeps track of which which EE version the database
801
-     * is at (ie, the code may be at 4.1.0, but the database is still at 3.1.35)
802
-     *
803
-     * @param array $slug_and_version {
804
-     * @type string $slug             like 'Core' or 'Calendar',
805
-     * @type string $version          like '4.1.0'
806
-     *                                }
807
-     * @return void
808
-     */
809
-    public function update_current_database_state_to($slug_and_version = null)
810
-    {
811
-        if (! $slug_and_version) {
812
-            // no version was provided, assume it should be at the current code version
813
-            $slug_and_version = array('slug' => 'Core', 'version' => espresso_version());
814
-        }
815
-        $current_database_state = get_option(self::current_database_state);
816
-        $current_database_state[ $slug_and_version['slug'] ] = $slug_and_version['version'];
817
-        update_option(self::current_database_state, $current_database_state);
818
-    }
819
-
820
-    /**
821
-     * Determines if the database is currently at a state matching what's indicated in $slug and $version.
822
-     *
823
-     * @param array $slug_and_version {
824
-     * @type string $slug             like 'Core' or 'Calendar',
825
-     * @type string $version          like '4.1.0'
826
-     *                                }
827
-     * @return boolean
828
-     */
829
-    public function database_needs_updating_to($slug_and_version)
830
-    {
831
-
832
-        $slug = $slug_and_version['slug'];
833
-        $version = $slug_and_version['version'];
834
-        $current_database_state = get_option(self::current_database_state);
835
-        if (! isset($current_database_state[ $slug ])) {
836
-            return true;
837
-        } else {
838
-            // 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
839
-            $version_parts_current_db_state = array_slice(explode('.', $current_database_state[ $slug ]), 0, 3);
840
-            $version_parts_of_provided_db_state = array_slice(explode('.', $version), 0, 3);
841
-            $needs_updating = false;
842
-            foreach ($version_parts_current_db_state as $offset => $version_part_in_current_db_state) {
843
-                if ($version_part_in_current_db_state < $version_parts_of_provided_db_state[ $offset ]) {
844
-                    $needs_updating = true;
845
-                    break;
846
-                }
847
-            }
848
-            return $needs_updating;
849
-        }
850
-    }
851
-
852
-
853
-    /**
854
-     * Gets all the data migration scripts available in the core folder and folders
855
-     * in addons. Has the side effect of adding them for autoloading
856
-     *
857
-     * @return array keys are expected classnames, values are their filepaths
858
-     * @throws InvalidInterfaceException
859
-     * @throws InvalidDataTypeException
860
-     * @throws EE_Error
861
-     * @throws InvalidArgumentException
862
-     */
863
-    public function get_all_data_migration_scripts_available()
864
-    {
865
-        if (! $this->_data_migration_class_to_filepath_map) {
866
-            $this->_data_migration_class_to_filepath_map = array();
867
-            foreach ($this->get_data_migration_script_folders() as $eeAddonClass => $folder_path) {
868
-                // strip any placeholders added to classname to make it a unique array key
869
-                $eeAddonClass = trim($eeAddonClass, '*');
870
-                $eeAddonClass = $eeAddonClass === 'Core' || class_exists($eeAddonClass)
871
-                    ? $eeAddonClass
872
-                    : '';
873
-                $folder_path = EEH_File::end_with_directory_separator($folder_path);
874
-                $files = glob($folder_path . '*.dms.php');
875
-                if (empty($files)) {
876
-                    continue;
877
-                }
878
-                foreach ($files as $file) {
879
-                    $pos_of_last_slash = strrpos($file, DS);
880
-                    $classname = str_replace('.dms.php', '', substr($file, $pos_of_last_slash + 1));
881
-                    $migrates_to = $this->script_migrates_to_version($classname, $eeAddonClass);
882
-                    $slug = $migrates_to['slug'];
883
-                    // check that the slug as contained in the DMS is associated with
884
-                    // the slug of an addon or core
885
-                    if ($slug !== 'Core' && EE_Registry::instance()->get_addon_by_name($slug) === null) {
886
-                        EE_Error::doing_it_wrong(
887
-                            __FUNCTION__,
888
-                            sprintf(
889
-                                esc_html__(
890
-                                    'The data migration script "%s" migrates the "%s" data, but there is no EE addon with that name. There is only: %s. ',
891
-                                    'event_espresso'
892
-                                ),
893
-                                $classname,
894
-                                $slug,
895
-                                implode(', ', array_keys(EE_Registry::instance()->get_addons_by_name()))
896
-                            ),
897
-                            '4.3.0.alpha.019'
898
-                        );
899
-                    }
900
-                    $this->_data_migration_class_to_filepath_map[ $classname ] = $file;
901
-                }
902
-            }
903
-            EEH_Autoloader::register_autoloader($this->_data_migration_class_to_filepath_map);
904
-        }
905
-        return $this->_data_migration_class_to_filepath_map;
906
-    }
907
-
908
-
909
-    /**
910
-     * Once we have an addon that works with EE4.1, we will actually want to fetch the PUE slugs
911
-     * from each addon, and check if they need updating,
912
-     *
913
-     * @return boolean
914
-     */
915
-    public function addons_need_updating()
916
-    {
917
-        return false;
918
-    }
919
-
920
-    /**
921
-     * Adds this error string to the data_migrations_ran array, but we dont necessarily know
922
-     * where to put it, so we just throw it in there... better than nothing...
923
-     *
924
-     * @param string $error_message
925
-     * @throws EE_Error
926
-     */
927
-    public function add_error_to_migrations_ran($error_message)
928
-    {
929
-        // get last-ran migration script
930
-        global $wpdb;
931
-        $last_migration_script_option = $wpdb->get_row(
932
-            "SELECT * FROM $wpdb->options WHERE option_name like '" . EE_Data_Migration_Manager::data_migration_script_option_prefix . "%' ORDER BY option_id DESC LIMIT 1",
933
-            ARRAY_A
934
-        );
935
-
936
-        $last_ran_migration_script_properties = isset($last_migration_script_option['option_value'])
937
-            ? maybe_unserialize($last_migration_script_option['option_value']) : null;
938
-        // now, tread lightly because we're here because a FATAL non-catchable error
939
-        // was thrown last time when we were trying to run a data migration script
940
-        // so the fatal error could have happened while getting the migration script
941
-        // or doing running it...
942
-        $versions_migrated_to = isset($last_migration_script_option['option_name']) ? str_replace(
943
-            EE_Data_Migration_Manager::data_migration_script_option_prefix,
944
-            "",
945
-            $last_migration_script_option['option_name']
946
-        ) : null;
947
-
948
-        // check if it THINKS its a data migration script and especially if it's one that HASN'T finished yet
949
-        // because if it has finished, then it obviously couldn't be the cause of this error, right? (because its all done)
950
-        if (isset($last_ran_migration_script_properties['class']) && isset($last_ran_migration_script_properties['_status']) && $last_ran_migration_script_properties['_status'] != self::status_completed) {
951
-            // ok then just add this error to its list of errors
952
-            $last_ran_migration_script_properties['_errors'][] = $error_message;
953
-            $last_ran_migration_script_properties['_status'] = self::status_fatal_error;
954
-        } else {
955
-            // so we don't even know which script was last running
956
-            // use the data migration error stub, which is designed specifically for this type of thing
957
-            $general_migration_error = new EE_DMS_Unknown_1_0_0();
958
-            $general_migration_error->add_error($error_message);
959
-            $general_migration_error->set_broken();
960
-            $last_ran_migration_script_properties = $general_migration_error->properties_as_array();
961
-            $versions_migrated_to = 'Unknown.1.0.0';
962
-            // now just to make sure appears as last (in case the were previously a fatal error like this)
963
-            // delete the old one
964
-            delete_option(self::data_migration_script_option_prefix . $versions_migrated_to);
965
-        }
966
-        update_option(
967
-            self::data_migration_script_option_prefix . $versions_migrated_to,
968
-            $last_ran_migration_script_properties
969
-        );
970
-    }
971
-
972
-    /**
973
-     * saves what data migrations have ran to the database
974
-     *
975
-     * @return mixed TRUE if successfully saved migrations ran, string if an error occurred
976
-     */
977
-    protected function _save_migrations_ran()
978
-    {
979
-        if ($this->_data_migrations_ran == null) {
980
-            $this->get_data_migrations_ran();
981
-        }
982
-        // now, we don't want to save actual classes to the DB because that's messy
983
-        $successful_updates = true;
984
-        foreach ($this->_data_migrations_ran as $plugin_slug => $migrations_ran_for_plugin) {
985
-            foreach ($migrations_ran_for_plugin as $version_string => $array_or_migration_obj) {
986
-                $plugin_slug_for_use_in_option_name = $plugin_slug . ".";
987
-                $option_name = self::data_migration_script_option_prefix . $plugin_slug_for_use_in_option_name . $version_string;
988
-                $old_option_value = get_option($option_name);
989
-                if ($array_or_migration_obj instanceof EE_Data_Migration_Script_Base) {
990
-                    $script_array_for_saving = $array_or_migration_obj->properties_as_array();
991
-                    if ($old_option_value != $script_array_for_saving) {
992
-                        $successful_updates = update_option($option_name, $script_array_for_saving);
993
-                    }
994
-                } else {// we don't know what this array-thing is. So just save it as-is
995
-                    if ($old_option_value != $array_or_migration_obj) {
996
-                        $successful_updates = update_option($option_name, $array_or_migration_obj);
997
-                    }
998
-                }
999
-                if (! $successful_updates) {
1000
-                    global $wpdb;
1001
-                    return $wpdb->last_error;
1002
-                }
1003
-            }
1004
-        }
1005
-        return true;
1006
-        // $updated = update_option(self::data_migrations_option_name, $array_of_migrations);
1007
-        // if ($updated !== true) {
1008
-        //     global $wpdb;
1009
-        //     return $wpdb->last_error;
1010
-        // } else {
1011
-        //     return true;
1012
-        // }
1013
-        // wp_mail(
1014
-        //     "[email protected]",
1015
-        //     time() . " price debug info",
1016
-        //     "updated: $updated, last error: $last_error, byte length of option: " . strlen(
1017
-        //         serialize($array_of_migrations)
1018
-        //     )
1019
-        // );
1020
-    }
1021
-
1022
-    /**
1023
-     * Takes an array of data migration script properties and re-creates the class from
1024
-     * them. The argument $properties_array is assumed to have been made by
1025
-     * EE_Data_Migration_Script_Base::properties_as_array()
1026
-     *
1027
-     * @param array $properties_array
1028
-     * @return EE_Data_Migration_Script_Base
1029
-     * @throws EE_Error
1030
-     */
1031
-    public function _instantiate_script_from_properties_array($properties_array)
1032
-    {
1033
-        if (! isset($properties_array['class'])) {
1034
-            throw new EE_Error(
1035
-                sprintf(
1036
-                    __("Properties array  has no 'class' properties. Here's what it has: %s", "event_espresso"),
1037
-                    implode(",", $properties_array)
1038
-                )
1039
-            );
1040
-        }
1041
-        $class_name = $properties_array['class'];
1042
-        if (! class_exists($class_name)) {
1043
-            throw new EE_Error(sprintf(__("There is no migration script named %s", "event_espresso"), $class_name));
1044
-        }
1045
-        $class = new $class_name;
1046
-        if (! $class instanceof EE_Data_Migration_Script_Base) {
1047
-            throw new EE_Error(
1048
-                sprintf(
1049
-                    __("Class '%s' is supposed to be a migration script. Its not, its a '%s'", "event_espresso"),
1050
-                    $class_name,
1051
-                    get_class($class)
1052
-                )
1053
-            );
1054
-        }
1055
-        $class->instantiate_from_array_of_properties($properties_array);
1056
-        return $class;
1057
-    }
1058
-
1059
-    /**
1060
-     * Gets the classname for the most up-to-date DMS (ie, the one that will finally
1061
-     * leave the DB in a state usable by the current plugin code).
1062
-     *
1063
-     * @param string $plugin_slug the slug for the ee plugin we are searching for. Default is 'Core'
1064
-     * @return string
1065
-     */
1066
-    public function get_most_up_to_date_dms($plugin_slug = 'Core')
1067
-    {
1068
-        $class_to_filepath_map = $this->get_all_data_migration_scripts_available();
1069
-        $most_up_to_date_dms_classname = null;
1070
-        foreach ($class_to_filepath_map as $classname => $filepath) {
1071
-            if ($most_up_to_date_dms_classname === null) {
1072
-                $migrates_to = $this->script_migrates_to_version($classname);
1073
-                $this_plugin_slug = $migrates_to['slug'];
1074
-                if ($this_plugin_slug == $plugin_slug) {
1075
-                    // if it's for core, it wins
1076
-                    $most_up_to_date_dms_classname = $classname;
1077
-                }
1078
-                // if it wasn't for core, we must keep searching for one that is!
1079
-                continue;
1080
-            } else {
1081
-                $champion_migrates_to = $this->script_migrates_to_version($most_up_to_date_dms_classname);
1082
-                $contender_migrates_to = $this->script_migrates_to_version($classname);
1083
-                if ($contender_migrates_to['slug'] == $plugin_slug
1084
-                    && version_compare(
1085
-                        $champion_migrates_to['version'],
1086
-                        $contender_migrates_to['version'],
1087
-                        '<'
1088
-                    )) {
1089
-                    // so the contenders version is higher and its for Core
1090
-                    $most_up_to_date_dms_classname = $classname;
1091
-                }
1092
-            }
1093
-        }
1094
-        return $most_up_to_date_dms_classname;
1095
-    }
1096
-
1097
-    /**
1098
-     * Gets the migration script specified but ONLY if it has already ran.
1099
-     *
1100
-     * Eg, if you wanted to see if 'EE_DMS_Core_4_1_0' has ran, you would run the following code:
1101
-     * <code> $core_4_1_0_dms_ran = EE_Data_Migration_Manager::instance()->get_migration_ran( '4.1.0', 'Core' ) !==
1102
-     * NULL;</code> This is especially useful in addons' data migration scripts, this way they can tell if a core (or
1103
-     * other addon) DMS has ran, in case the current DMS depends on it.
1104
-     *
1105
-     * @param string $version     the version the DMS searched for migrates to. Usually just the content before the 3rd
1106
-     *                            period. Eg '4.1.0'
1107
-     * @param string $plugin_slug like 'Core', 'Mailchimp', 'Calendar', etc
1108
-     * @return EE_Data_Migration_Script_Base
1109
-     */
1110
-    public function get_migration_ran($version, $plugin_slug = 'Core')
1111
-    {
1112
-        $migrations_ran = $this->get_data_migrations_ran();
1113
-        if (isset($migrations_ran[ $plugin_slug ]) && isset($migrations_ran[ $plugin_slug ][ $version ])) {
1114
-            return $migrations_ran[ $plugin_slug ][ $version ];
1115
-        } else {
1116
-            return null;
1117
-        }
1118
-    }
1119
-
1120
-    /**
1121
-     * Resets the borked data migration scripts so they're no longer borked
1122
-     * so we can again attempt to migrate
1123
-     *
1124
-     * @return bool
1125
-     * @throws EE_Error
1126
-     */
1127
-    public function reattempt()
1128
-    {
1129
-        // find if the last-ran script was borked
1130
-        // set it as being non-borked (we shouldn't ever get DMSs that we don't recognize)
1131
-        // add an 'error' saying that we attempted to reset
1132
-        // does it have a stage that was borked too? if so make it no longer borked
1133
-        // add an 'error' saying we attempted to reset
1134
-        $last_ran_script = $this->get_last_ran_script();
1135
-        if ($last_ran_script instanceof EE_DMS_Unknown_1_0_0) {
1136
-            // if it was an error DMS, just mark it as complete (if another error occurs it will overwrite it)
1137
-            $last_ran_script->set_completed();
1138
-        } elseif ($last_ran_script instanceof EE_Data_Migration_Script_Base) {
1139
-            $last_ran_script->reattempt();
1140
-        } else {
1141
-            throw new EE_Error(
1142
-                sprintf(
1143
-                    __(
1144
-                        'Unable to reattempt the last ran migration script because it was not a valid migration script. || It was %s',
1145
-                        'event_espresso'
1146
-                    ),
1147
-                    print_r($last_ran_script, true)
1148
-                )
1149
-            );
1150
-        }
1151
-        return $this->_save_migrations_ran();
1152
-    }
1153
-
1154
-    /**
1155
-     * Gets whether or not this particular migration has run or not
1156
-     *
1157
-     * @param string $version     the version the DMS searched for migrates to. Usually just the content before the 3rd
1158
-     *                            period. Eg '4.1.0'
1159
-     * @param string $plugin_slug like 'Core', 'Mailchimp', 'Calendar', etc
1160
-     * @return boolean
1161
-     */
1162
-    public function migration_has_ran($version, $plugin_slug = 'Core')
1163
-    {
1164
-        return $this->get_migration_ran($version, $plugin_slug) !== null;
1165
-    }
1166
-
1167
-    /**
1168
-     * Enqueues this ee plugin to have its data initialized
1169
-     *
1170
-     * @param string $plugin_slug either 'Core' or EE_Addon::name()'s return value
1171
-     */
1172
-    public function enqueue_db_initialization_for($plugin_slug)
1173
-    {
1174
-        $queue = $this->get_db_initialization_queue();
1175
-        if (! in_array($plugin_slug, $queue)) {
1176
-            $queue[] = $plugin_slug;
1177
-        }
1178
-        update_option(self::db_init_queue_option_name, $queue);
1179
-    }
1180
-
1181
-    /**
1182
-     * Calls EE_Addon::initialize_db_if_no_migrations_required() on each addon
1183
-     * specified in EE_Data_Migration_Manager::get_db_init_queue(), and if 'Core' is
1184
-     * in the queue, calls EE_System::initialize_db_if_no_migrations_required().
1185
-     */
1186
-    public function initialize_db_for_enqueued_ee_plugins()
1187
-    {
1188
-        $queue = $this->get_db_initialization_queue();
1189
-        foreach ($queue as $plugin_slug) {
1190
-            $most_up_to_date_dms = $this->get_most_up_to_date_dms($plugin_slug);
1191
-            if (! $most_up_to_date_dms) {
1192
-                // if there is NO DMS for this plugin, obviously there's no schema to verify anyways
1193
-                $verify_db = false;
1194
-            } else {
1195
-                $most_up_to_date_dms_migrates_to = $this->script_migrates_to_version($most_up_to_date_dms);
1196
-                $verify_db = $this->database_needs_updating_to($most_up_to_date_dms_migrates_to);
1197
-            }
1198
-            if ($plugin_slug == 'Core') {
1199
-                EE_System::instance()->initialize_db_if_no_migrations_required(
1200
-                    false,
1201
-                    $verify_db
1202
-                );
1203
-            } else {
1204
-                // just loop through the addons to make sure their database is setup
1205
-                foreach (EE_Registry::instance()->addons as $addon) {
1206
-                    if ($addon->name() == $plugin_slug) {
1207
-                        $addon->initialize_db_if_no_migrations_required($verify_db);
1208
-                        break;
1209
-                    }
1210
-                }
1211
-            }
1212
-        }
1213
-        // because we just initialized the DBs for the enqueued ee plugins
1214
-        // we don't need to keep remembering which ones needed to be initialized
1215
-        delete_option(self::db_init_queue_option_name);
1216
-    }
1217
-
1218
-    /**
1219
-     * Gets a numerically-indexed array of plugin slugs that need to have their databases
1220
-     * (re-)initialized after migrations are complete. ie, each element should be either
1221
-     * 'Core', or the return value of EE_Addon::name() for an addon
1222
-     *
1223
-     * @return array
1224
-     */
1225
-    public function get_db_initialization_queue()
1226
-    {
1227
-        return get_option(self::db_init_queue_option_name, array());
1228
-    }
1229
-
1230
-    /**
1231
-     * Gets the injected table analyzer, or throws an exception
1232
-     *
1233
-     * @return TableAnalysis
1234
-     * @throws EE_Error
1235
-     */
1236
-    protected function _get_table_analysis()
1237
-    {
1238
-        if ($this->_table_analysis instanceof TableAnalysis) {
1239
-            return $this->_table_analysis;
1240
-        } else {
1241
-            throw new EE_Error(
1242
-                sprintf(
1243
-                    __('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
1244
-                    get_class($this)
1245
-                )
1246
-            );
1247
-        }
1248
-    }
1249
-
1250
-    /**
1251
-     * Gets the injected table manager, or throws an exception
1252
-     *
1253
-     * @return TableManager
1254
-     * @throws EE_Error
1255
-     */
1256
-    protected function _get_table_manager()
1257
-    {
1258
-        if ($this->_table_manager instanceof TableManager) {
1259
-            return $this->_table_manager;
1260
-        } else {
1261
-            throw new EE_Error(
1262
-                sprintf(
1263
-                    __('Table manager class on class %1$s is not set properly.', 'event_espresso'),
1264
-                    get_class($this)
1265
-                )
1266
-            );
1267
-        }
1268
-    }
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
+	 * string indicating the migration should continue
63
+	 */
64
+	const status_continue = 'status_continue';
65
+	/**
66
+	 * string indicating the migration has completed and should be ended
67
+	 */
68
+	const status_completed = 'status_completed';
69
+	/**
70
+	 * string indicating a fatal error occurred and the data migration should be completely aborted
71
+	 */
72
+	const status_fatal_error = 'status_fatal_error';
73
+
74
+	/**
75
+	 * the number of 'items' (usually DB rows) to migrate on each 'step' (ajax request sent
76
+	 * during migration)
77
+	 */
78
+	const step_size = 50;
79
+
80
+	/**
81
+	 * option name that stores the queue of ee plugins needing to have
82
+	 * their data initialized (or re-initialized) once we are done migrations
83
+	 */
84
+	const db_init_queue_option_name = 'ee_db_init_queue';
85
+	/**
86
+	 * Array of information concerning data migrations that have ran in the history
87
+	 * of this EE installation. Keys should be the name of the version the script upgraded to
88
+	 *
89
+	 * @var EE_Data_Migration_Script_Base[]
90
+	 */
91
+	private $_data_migrations_ran = null;
92
+	/**
93
+	 * The last ran script. It's nice to store this somewhere accessible, as its easiest
94
+	 * to know which was the last run by which is the newest wp option; but in most of the code
95
+	 * we just use the local $_data_migration_ran array, which organized the scripts differently
96
+	 *
97
+	 * @var EE_Data_Migration_Script_Base
98
+	 */
99
+	private $_last_ran_script = null;
100
+
101
+	/**
102
+	 * Similarly to _last_ran_script, but this is the last INCOMPLETE migration script.
103
+	 *
104
+	 * @var EE_Data_Migration_Script_Base
105
+	 */
106
+	private $_last_ran_incomplete_script = null;
107
+	/**
108
+	 * array where keys are classnames, and values are filepaths of all the known migration scripts
109
+	 *
110
+	 * @var array
111
+	 */
112
+	private $_data_migration_class_to_filepath_map;
113
+
114
+	/**
115
+	 * the following 4 properties are fully set on construction.
116
+	 * Note: the first two apply to whether to continue running ALL migration scripts (ie, even though we're finished
117
+	 * one, we may want to start the next one); whereas the last two indicate whether to continue running a single
118
+	 * data migration script
119
+	 *
120
+	 * @var array
121
+	 */
122
+	public $stati_that_indicate_to_continue_migrations = array();
123
+
124
+	public $stati_that_indicate_to_stop_migrations = array();
125
+
126
+	public $stati_that_indicate_to_continue_single_migration_script = array();
127
+
128
+	public $stati_that_indicate_to_stop_single_migration_script = array();
129
+
130
+	/**
131
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
132
+	 */
133
+	protected $_table_manager;
134
+
135
+	/**
136
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
137
+	 */
138
+	protected $_table_analysis;
139
+
140
+	/**
141
+	 * @var array $script_migration_versions
142
+	 */
143
+	protected $script_migration_versions;
144
+
145
+	/**
146
+	 * @var EE_Data_Migration_Manager $_instance
147
+	 * @access    private
148
+	 */
149
+	private static $_instance = null;
150
+
151
+
152
+	/**
153
+	 * @singleton method used to instantiate class object
154
+	 * @access    public
155
+	 * @return EE_Data_Migration_Manager instance
156
+	 */
157
+	public static function instance()
158
+	{
159
+		// check if class object is instantiated
160
+		if (! self::$_instance instanceof EE_Data_Migration_Manager) {
161
+			self::$_instance = new self();
162
+		}
163
+		return self::$_instance;
164
+	}
165
+
166
+	/**
167
+	 * resets the singleton to its brand-new state (but does NOT delete old references to the old singleton. Meaning,
168
+	 * all new usages of the singleton should be made with Classname::instance()) and returns it
169
+	 *
170
+	 * @return EE_Data_Migration_Manager
171
+	 */
172
+	public static function reset()
173
+	{
174
+		self::$_instance = null;
175
+		return self::instance();
176
+	}
177
+
178
+
179
+	/**
180
+	 * constructor
181
+	 */
182
+	private function __construct()
183
+	{
184
+		$this->stati_that_indicate_to_continue_migrations = array(
185
+			self::status_continue,
186
+			self::status_completed,
187
+		);
188
+		$this->stati_that_indicate_to_stop_migrations = array(
189
+			self::status_fatal_error,
190
+			self::status_no_more_migration_scripts,
191
+		);
192
+		$this->stati_that_indicate_to_continue_single_migration_script = array(
193
+			self::status_continue,
194
+		);
195
+		$this->stati_that_indicate_to_stop_single_migration_script = array(
196
+			self::status_completed,
197
+			self::status_fatal_error
198
+			// note: status_no_more_migration_scripts doesn't apply
199
+		);
200
+		// make sure we've included the base migration script, because we may need the EE_DMS_Unknown_1_0_0 class
201
+		// to be defined, because right now it doesn't get autoloaded on its own
202
+		EE_Registry::instance()->load_core('Data_Migration_Class_Base', array(), true);
203
+		EE_Registry::instance()->load_core('Data_Migration_Script_Base', array(), true);
204
+		EE_Registry::instance()->load_core('DMS_Unknown_1_0_0', array(), true);
205
+		EE_Registry::instance()->load_core('Data_Migration_Script_Stage', array(), true);
206
+		EE_Registry::instance()->load_core('Data_Migration_Script_Stage_Table', array(), true);
207
+		$this->_table_manager = EE_Registry::instance()->create('TableManager', array(), true);
208
+		$this->_table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
209
+	}
210
+
211
+
212
+	/**
213
+	 * Deciphers, from an option's name, what plugin and version it relates to (see _save_migrations_ran to see what
214
+	 * the option names are like, but generally they're like
215
+	 * 'ee_data_migration_script_Core.4.1.0' in 4.2 or 'ee_data_migration_script_4.1.0' before that).
216
+	 * The option name shouldn't ever be like 'ee_data_migration_script_Core.4.1.0.reg' because it's derived,
217
+	 * indirectly, from the data migration's classname, which should always be like EE_DMS_%s_%d_%d_%d.dms.php (eg
218
+	 * EE_DMS_Core_4_1_0.dms.php)
219
+	 *
220
+	 * @param string $option_name (see EE_Data_Migration_Manage::_save_migrations_ran() where the option name is set)
221
+	 * @return array where the first item is the plugin slug (eg 'Core','Calendar',etc) and the 2nd is the version of
222
+	 *               that plugin (eg '4.1.0')
223
+	 */
224
+	private function _get_plugin_slug_and_version_string_from_dms_option_name($option_name)
225
+	{
226
+		$plugin_slug_and_version_string = str_replace(
227
+			EE_Data_Migration_Manager::data_migration_script_option_prefix,
228
+			"",
229
+			$option_name
230
+		);
231
+		// check if $plugin_slug_and_version_string is like '4.1.0' (4.1-style) or 'Core.4.1.0' (4.2-style)
232
+		$parts = explode(".", $plugin_slug_and_version_string);
233
+
234
+		if (count($parts) == 4) {
235
+			// it's 4.2-style.eg Core.4.1.0
236
+			$plugin_slug = $parts[0];// eg Core
237
+			$version_string = $parts[1] . "." . $parts[2] . "." . $parts[3]; // eg 4.1.0
238
+		} else {
239
+			// it's 4.1-style: eg 4.1.0
240
+			$plugin_slug = 'Core';
241
+			$version_string = $plugin_slug_and_version_string;// eg 4.1.0
242
+		}
243
+		return array($plugin_slug, $version_string);
244
+	}
245
+
246
+	/**
247
+	 * Gets the DMS class from the wordpress option, otherwise throws an EE_Error if it's not
248
+	 * for a known DMS class.
249
+	 *
250
+	 * @param string $dms_option_name
251
+	 * @param string $dms_option_value (serialized)
252
+	 * @return EE_Data_Migration_Script_Base
253
+	 * @throws EE_Error
254
+	 */
255
+	private function _get_dms_class_from_wp_option($dms_option_name, $dms_option_value)
256
+	{
257
+		$data_migration_data = maybe_unserialize($dms_option_value);
258
+		if (isset($data_migration_data['class']) && class_exists($data_migration_data['class'])) {
259
+			$class = new $data_migration_data['class'];
260
+			if ($class instanceof EE_Data_Migration_Script_Base) {
261
+				$class->instantiate_from_array_of_properties($data_migration_data);
262
+				return $class;
263
+			} else {
264
+				// huh, so its an object but not a data migration script?? that shouldn't happen
265
+				// just leave it as an array (which will probably just get ignored)
266
+				throw new EE_Error(
267
+					sprintf(
268
+						__(
269
+							"Trying to retrieve DMS class from wp option. No DMS by the name '%s' exists",
270
+							'event_espresso'
271
+						),
272
+						$data_migration_data['class']
273
+					)
274
+				);
275
+			}
276
+		} else {
277
+			// 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
278
+			throw new EE_Error(
279
+				sprintf(__("The wp option  with key '%s' does not represent a DMS", 'event_espresso'), $dms_option_name)
280
+			);
281
+		}
282
+	}
283
+
284
+	/**
285
+	 * Gets the array describing what data migrations have run. Also has a side-effect of recording which was the last
286
+	 * ran, and which was the last ran which hasn't finished yet
287
+	 *
288
+	 * @return array where each element should be an array of EE_Data_Migration_Script_Base (but also has a few legacy
289
+	 *               arrays in there - which should probably be ignored)
290
+	 */
291
+	public function get_data_migrations_ran()
292
+	{
293
+		if (! $this->_data_migrations_ran) {
294
+			// setup autoloaders for each of the scripts in there
295
+			$this->get_all_data_migration_scripts_available();
296
+			$data_migrations_options = $this->get_all_migration_script_options(
297
+			);// get_option(EE_Data_Migration_Manager::data_migrations_option_name,get_option('espresso_data_migrations',array()));
298
+
299
+			$data_migrations_ran = array();
300
+			// convert into data migration script classes where possible
301
+			foreach ($data_migrations_options as $data_migration_option) {
302
+				list($plugin_slug, $version_string) = $this->_get_plugin_slug_and_version_string_from_dms_option_name(
303
+					$data_migration_option['option_name']
304
+				);
305
+
306
+				try {
307
+					$class = $this->_get_dms_class_from_wp_option(
308
+						$data_migration_option['option_name'],
309
+						$data_migration_option['option_value']
310
+					);
311
+					$data_migrations_ran[ $plugin_slug ][ $version_string ] = $class;
312
+					// ok so far THIS is the 'last-ran-script'... unless we find another on next iteration
313
+					$this->_last_ran_script = $class;
314
+					if (! $class->is_completed()) {
315
+						// sometimes we also like to know which was the last incomplete script (or if there are any at all)
316
+						$this->_last_ran_incomplete_script = $class;
317
+					}
318
+				} catch (EE_Error $e) {
319
+					// ok so its not a DMS. We'll just keep it, although other code will need to expect non-DMSs
320
+					$data_migrations_ran[ $plugin_slug ][ $version_string ] = maybe_unserialize(
321
+						$data_migration_option['option_value']
322
+					);
323
+				}
324
+			}
325
+			// so here the array of $data_migrations_ran is actually a mix of classes and a few legacy arrays
326
+			$this->_data_migrations_ran = $data_migrations_ran;
327
+			if (! $this->_data_migrations_ran || ! is_array($this->_data_migrations_ran)) {
328
+				$this->_data_migrations_ran = array();
329
+			}
330
+		}
331
+		return $this->_data_migrations_ran;
332
+	}
333
+
334
+
335
+	/**
336
+	 *
337
+	 * @param string $script_name eg 'DMS_Core_4_1_0'
338
+	 * @param string $old_table   eg 'wp_events_detail'
339
+	 * @param string $old_pk      eg 'wp_esp_posts'
340
+	 * @param        $new_table
341
+	 * @return mixed string or int
342
+	 */
343
+	public function get_mapping_new_pk($script_name, $old_table, $old_pk, $new_table)
344
+	{
345
+		$script = EE_Registry::instance()->load_dms($script_name);
346
+		$mapping = $script->get_mapping_new_pk($old_table, $old_pk, $new_table);
347
+		return $mapping;
348
+	}
349
+
350
+	/**
351
+	 * Gets all the options containing migration scripts that have been run. Ordering is important: it's assumed that
352
+	 * the last option returned in this array is the most-recently ran DMS option
353
+	 *
354
+	 * @return array
355
+	 */
356
+	public function get_all_migration_script_options()
357
+	{
358
+		global $wpdb;
359
+		return $wpdb->get_results(
360
+			"SELECT * FROM {$wpdb->options} WHERE option_name like '" . EE_Data_Migration_Manager::data_migration_script_option_prefix . "%' ORDER BY option_id ASC",
361
+			ARRAY_A
362
+		);
363
+	}
364
+
365
+	/**
366
+	 * Gets the array of folders which contain data migration scripts. Also adds them to be auto-loaded
367
+	 *
368
+	 * @return array where each value is the full folder path of a folder containing data migration scripts, WITH
369
+	 *               slashes at the end of the folder name.
370
+	 */
371
+	public function get_data_migration_script_folders()
372
+	{
373
+		return apply_filters(
374
+			'FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',
375
+			array('Core' => EE_CORE . 'data_migration_scripts')
376
+		);
377
+	}
378
+
379
+	/**
380
+	 * Gets the version the migration script upgrades to
381
+	 *
382
+	 * @param string $migration_script_name eg 'EE_DMS_Core_4_1_0'
383
+	 * @return array {
384
+	 * @type string  $slug                  like 'Core','Calendar',etc
385
+	 * @type string  $version               like 4.3.0
386
+	 *                                      }
387
+	 * @throws EE_Error
388
+	 */
389
+	public function script_migrates_to_version($migration_script_name, $eeAddonClass = '')
390
+	{
391
+		if (isset($this->script_migration_versions[ $migration_script_name ])) {
392
+			return $this->script_migration_versions[ $migration_script_name ];
393
+		}
394
+		$dms_info = $this->parse_dms_classname($migration_script_name);
395
+		$this->script_migration_versions[ $migration_script_name ] = array(
396
+			'slug'    => $eeAddonClass !== '' ? $eeAddonClass : $dms_info['slug'],
397
+			'version' => $dms_info['major_version'] . "." . $dms_info['minor_version'] . "." . $dms_info['micro_version'],
398
+		);
399
+		return $this->script_migration_versions[ $migration_script_name ];
400
+	}
401
+
402
+	/**
403
+	 * Gets the juicy details out of a dms filename like 'EE_DMS_Core_4_1_0'
404
+	 *
405
+	 * @param string $classname
406
+	 * @return array with keys 'slug','major_version','minor_version', and 'micro_version' (the last 3 are ints)
407
+	 * @throws EE_Error
408
+	 */
409
+	public function parse_dms_classname($classname)
410
+	{
411
+		$matches = array();
412
+		preg_match('~EE_DMS_(.*)_([0-9]*)_([0-9]*)_([0-9]*)~', $classname, $matches);
413
+		if (! $matches || ! (isset($matches[1]) && isset($matches[2]) && isset($matches[3]))) {
414
+			throw new EE_Error(
415
+				sprintf(
416
+					__(
417
+						"%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, ",
418
+						"event_espresso"
419
+					),
420
+					$classname
421
+				)
422
+			);
423
+		}
424
+		return array(
425
+			'slug'          => $matches[1],
426
+			'major_version' => intval($matches[2]),
427
+			'minor_version' => intval($matches[3]),
428
+			'micro_version' => intval($matches[4]),
429
+		);
430
+	}
431
+
432
+	/**
433
+	 * Ensures that the option indicating the current DB version is set. This should only be
434
+	 * a concern when activating EE for the first time, THEORETICALLY.
435
+	 * 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
436
+	 * to 4.1.x.
437
+	 *
438
+	 * @return string of current db state
439
+	 */
440
+	public function ensure_current_database_state_is_set()
441
+	{
442
+		$espresso_db_core_updates = get_option('espresso_db_update', array());
443
+		$db_state = get_option(EE_Data_Migration_Manager::current_database_state);
444
+		if (! $db_state) {
445
+			// mark the DB as being in the state as the last version in there.
446
+			// this is done to trigger maintenance mode and do data migration scripts
447
+			// if the admin installed this version of EE over 3.1.x or 4.0.x
448
+			// otherwise, the normal maintenance mode code is fine
449
+			$previous_versions_installed = array_keys($espresso_db_core_updates);
450
+			$previous_version_installed = end($previous_versions_installed);
451
+			if (version_compare('4.1.0', $previous_version_installed)) {
452
+				// last installed version was less than 4.1
453
+				// so we want the data migrations to happen. SO, we're going to say the DB is at that state
454
+				$db_state = array('Core' => $previous_version_installed);
455
+			} else {
456
+				$db_state = array('Core' => EVENT_ESPRESSO_VERSION);
457
+			}
458
+			update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
459
+		}
460
+		// in 4.1, $db_state would have only been a simple string like '4.1.0',
461
+		// but in 4.2+ it should be an array with at least key 'Core' and the value of that plugin's
462
+		// db, and possibly other keys for other addons like 'Calendar','Permissions',etc
463
+		if (! is_array($db_state)) {
464
+			$db_state = array('Core' => $db_state);
465
+			update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
466
+		}
467
+		return $db_state;
468
+	}
469
+
470
+	/**
471
+	 * Checks if there are any data migration scripts that ought to be run. If found,
472
+	 * returns the instantiated classes. If none are found (ie, they've all already been run
473
+	 * or they don't apply), returns an empty array
474
+	 *
475
+	 * @return EE_Data_Migration_Script_Base[]
476
+	 */
477
+	public function check_for_applicable_data_migration_scripts()
478
+	{
479
+		// get the option describing what options have already run
480
+		$scripts_ran = $this->get_data_migrations_ran();
481
+		// $scripts_ran = array('4.1.0.core'=>array('monkey'=>null));
482
+		$script_class_and_filepaths_available = $this->get_all_data_migration_scripts_available();
483
+
484
+
485
+		$current_database_state = $this->ensure_current_database_state_is_set();
486
+		// determine which have already been run
487
+		$script_classes_that_should_run_per_iteration = array();
488
+		$iteration = 0;
489
+		$next_database_state_to_consider = $current_database_state;
490
+		$theoretical_database_state = null;
491
+		do {
492
+			// the next state after the currently-considered one will start off looking the same as the current, but we may make additions...
493
+			$theoretical_database_state = $next_database_state_to_consider;
494
+			// the next db state to consider is "what would the DB be like had we run all the scripts we found that applied last time?)
495
+			foreach ($script_class_and_filepaths_available as $classname => $filepath) {
496
+				$migrates_to_version = $this->script_migrates_to_version($classname);
497
+				$script_converts_plugin_slug = $migrates_to_version['slug'];
498
+				$script_converts_to_version = $migrates_to_version['version'];
499
+				// check if this version script is DONE or not; or if it's never been ran
500
+				if (! $scripts_ran ||
501
+					! isset($scripts_ran[ $script_converts_plugin_slug ]) ||
502
+					! isset($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ])) {
503
+					// we haven't ran this conversion script before
504
+					// now check if it applies... note that we've added an autoloader for it on get_all_data_migration_scripts_available
505
+					$script = new $classname($this->_get_table_manager(), $this->_get_table_analysis());
506
+					/* @var $script EE_Data_Migration_Script_Base */
507
+					$can_migrate = $script->can_migrate_from_version($theoretical_database_state);
508
+					if ($can_migrate) {
509
+						$script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
510
+						$migrates_to_version = $script->migrates_to_version();
511
+						$next_database_state_to_consider[ $migrates_to_version['slug'] ] = $migrates_to_version['version'];
512
+						unset($script_class_and_filepaths_available[ $classname ]);
513
+					}
514
+				} elseif ($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ] instanceof EE_Data_Migration_Script_Base) {
515
+					// this script has been ran, or at least started
516
+					$script = $scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ];
517
+					if ($script->get_status() != self::status_completed) {
518
+						// this script is already underway... keep going with it
519
+						$script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
520
+						$migrates_to_version = $script->migrates_to_version();
521
+						$next_database_state_to_consider[ $migrates_to_version['slug'] ] = $migrates_to_version['version'];
522
+						unset($script_class_and_filepaths_available[ $classname ]);
523
+					} else {
524
+						// it must have a status that indicates it has finished, so we don't want to try and run it again
525
+					}
526
+				} else {
527
+					// it exists but it's not  a proper data migration script
528
+					// maybe the script got renamed? or was simply removed from EE?
529
+					// either way, its certainly not runnable!
530
+				}
531
+			}
532
+			$iteration++;
533
+		} while ($next_database_state_to_consider != $theoretical_database_state && $iteration < 6);
534
+		// ok we have all the scripts that should run, now let's make them into flat array
535
+		$scripts_that_should_run = array();
536
+		foreach ($script_classes_that_should_run_per_iteration as $scripts_at_priority) {
537
+			ksort($scripts_at_priority);
538
+			foreach ($scripts_at_priority as $scripts) {
539
+				foreach ($scripts as $script) {
540
+					$scripts_that_should_run[ get_class($script) ] = $script;
541
+				}
542
+			}
543
+		}
544
+
545
+		do_action(
546
+			'AHEE__EE_Data_Migration_Manager__check_for_applicable_data_migration_scripts__scripts_that_should_run',
547
+			$scripts_that_should_run
548
+		);
549
+		return $scripts_that_should_run;
550
+	}
551
+
552
+
553
+	/**
554
+	 * Gets the script which is currently being ran, if there is one. If $include_completed_scripts is set to TRUE
555
+	 * it will return the last ran script even if its complete.
556
+	 * This means: if you want to find the currently-executing script, leave it as FALSE.
557
+	 * If you really just want to find the script which ran most recently, regardless of status, leave it as TRUE.
558
+	 *
559
+	 * @param bool $include_completed_scripts
560
+	 * @return EE_Data_Migration_Script_Base
561
+	 */
562
+	public function get_last_ran_script($include_completed_scripts = false)
563
+	{
564
+		// make sure we've setup the class properties _last_ran_script and _last_ran_incomplete_script
565
+		if (! $this->_data_migrations_ran) {
566
+			$this->get_data_migrations_ran();
567
+		}
568
+		if ($include_completed_scripts) {
569
+			return $this->_last_ran_script;
570
+		} else {
571
+			return $this->_last_ran_incomplete_script;
572
+		}
573
+	}
574
+
575
+
576
+	/**
577
+	 * Runs the data migration scripts (well, each request to this method calls one of the
578
+	 * data migration scripts' migration_step() functions).
579
+	 *
580
+	 * @param int   $step_size
581
+	 * @throws EE_Error
582
+	 * @return array {
583
+	 *                                  // where the first item is one EE_Data_Migration_Script_Base's stati,
584
+	 *                                  //and the second item is a string describing what was done
585
+	 * @type int    $records_to_migrate from the current migration script
586
+	 * @type int    $records_migrated
587
+	 * @type string $status             one of EE_Data_Migration_Manager::status_*
588
+	 * @type string $script             verbose name of the current DMS
589
+	 * @type string $message            string describing what was done during this step
590
+	 *                                  }
591
+	 */
592
+	public function migration_step($step_size = 0)
593
+	{
594
+
595
+		// bandaid fix for issue https://events.codebasehq.com/projects/event-espresso/tickets/7535
596
+		if (class_exists('EE_CPT_Strategy')) {
597
+			remove_action('pre_get_posts', array(EE_CPT_Strategy::instance(), 'pre_get_posts'), 5);
598
+		}
599
+
600
+		try {
601
+			$currently_executing_script = $this->get_last_ran_script();
602
+			if (! $currently_executing_script) {
603
+				// Find the next script that needs to execute
604
+				$scripts = $this->check_for_applicable_data_migration_scripts();
605
+				if (! $scripts) {
606
+					// huh, no more scripts to run... apparently we're done!
607
+					// but dont forget to make sure initial data is there
608
+					// we should be good to allow them to exit maintenance mode now
609
+					EE_Maintenance_Mode::instance()->set_maintenance_level(
610
+						intval(EE_Maintenance_Mode::level_0_not_in_maintenance)
611
+					);
612
+					// saving migrations ran should actually be unnecessary, but leaving in place just in case
613
+					// remember this migration was finished (even if we timeout initing db for core and plugins)
614
+					$this->_save_migrations_ran();
615
+					// make sure DB was updated AFTER we've recorded the migration was done
616
+					$this->initialize_db_for_enqueued_ee_plugins();
617
+					return array(
618
+						'records_to_migrate' => 1,
619
+						'records_migrated'   => 1,
620
+						'status'             => self::status_no_more_migration_scripts,
621
+						'script'             => __("Data Migration Completed Successfully", "event_espresso"),
622
+						'message'            => __("All done!", "event_espresso"),
623
+					);
624
+				}
625
+				$currently_executing_script = array_shift($scripts);
626
+				// and add to the array/wp option showing the scripts ran
627
+
628
+				$migrates_to = $this->script_migrates_to_version(get_class($currently_executing_script));
629
+				$plugin_slug = $migrates_to['slug'];
630
+				$version = $migrates_to['version'];
631
+				$this->_data_migrations_ran[ $plugin_slug ][ $version ] = $currently_executing_script;
632
+			}
633
+			$current_script_name = get_class($currently_executing_script);
634
+		} catch (Exception $e) {
635
+			// an exception occurred while trying to get migration scripts
636
+
637
+			$message = sprintf(
638
+				__("Error Message: %sStack Trace:%s", "event_espresso"),
639
+				$e->getMessage() . '<br>',
640
+				$e->getTraceAsString()
641
+			);
642
+			// record it on the array of data migration scripts ran. This will be overwritten next time we try and try to run data migrations
643
+			// but that's ok-- it's just an FYI to support that we couldn't even run any data migrations
644
+			$this->add_error_to_migrations_ran(
645
+				sprintf(__("Could not run data migrations because: %s", "event_espresso"), $message)
646
+			);
647
+			return array(
648
+				'records_to_migrate' => 1,
649
+				'records_migrated'   => 0,
650
+				'status'             => self::status_fatal_error,
651
+				'script'             => __("Error loading data migration scripts", "event_espresso"),
652
+				'message'            => $message,
653
+			);
654
+		}
655
+		// ok so we definitely have a data migration script
656
+		try {
657
+			// how big of a bite do we want to take? Allow users to easily override via their wp-config
658
+			if (absint($step_size) < 1) {
659
+				$step_size = defined('EE_MIGRATION_STEP_SIZE') && absint(EE_MIGRATION_STEP_SIZE)
660
+					? EE_MIGRATION_STEP_SIZE : EE_Data_Migration_Manager::step_size;
661
+			}
662
+			// do what we came to do!
663
+			$currently_executing_script->migration_step($step_size);
664
+			// can we wrap it up and verify default data?
665
+			$init_dbs = false;
666
+			switch ($currently_executing_script->get_status()) {
667
+				case EE_Data_Migration_Manager::status_continue:
668
+					$response_array = array(
669
+						'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
670
+						'records_migrated'   => $currently_executing_script->count_records_migrated(),
671
+						'status'             => EE_Data_Migration_Manager::status_continue,
672
+						'message'            => $currently_executing_script->get_feedback_message(),
673
+						'script'             => $currently_executing_script->pretty_name(),
674
+					);
675
+					break;
676
+				case EE_Data_Migration_Manager::status_completed:
677
+					// ok so THAT script has completed
678
+					$this->update_current_database_state_to($this->script_migrates_to_version($current_script_name));
679
+					$response_array = array(
680
+						'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
681
+						'records_migrated'   => $currently_executing_script->count_records_migrated(),
682
+						'status'             => EE_Data_Migration_Manager::status_completed,
683
+						'message'            => $currently_executing_script->get_feedback_message(),
684
+						'script'             => sprintf(
685
+							__("%s Completed", 'event_espresso'),
686
+							$currently_executing_script->pretty_name()
687
+						),
688
+					);
689
+					// check if there are any more after this one.
690
+					$scripts_remaining = $this->check_for_applicable_data_migration_scripts();
691
+					if (! $scripts_remaining) {
692
+						// we should be good to allow them to exit maintenance mode now
693
+						EE_Maintenance_Mode::instance()->set_maintenance_level(
694
+							intval(EE_Maintenance_Mode::level_0_not_in_maintenance)
695
+						);
696
+						// huh, no more scripts to run... apparently we're done!
697
+						// but dont forget to make sure initial data is there
698
+						$init_dbs = true;
699
+						$response_array['status'] = self::status_no_more_migration_scripts;
700
+					}
701
+					break;
702
+				default:
703
+					$response_array = array(
704
+						'records_to_migrate' => $currently_executing_script->count_records_to_migrate(),
705
+						'records_migrated'   => $currently_executing_script->count_records_migrated(),
706
+						'status'             => $currently_executing_script->get_status(),
707
+						'message'            => sprintf(
708
+							__("Minor errors occurred during %s: %s", "event_espresso"),
709
+							$currently_executing_script->pretty_name(),
710
+							implode(", ", $currently_executing_script->get_errors())
711
+						),
712
+						'script'             => $currently_executing_script->pretty_name(),
713
+					);
714
+					break;
715
+			}
716
+		} catch (Exception $e) {
717
+			// ok so some exception was thrown which killed the data migration script
718
+			// double-check we have a real script
719
+			if ($currently_executing_script instanceof EE_Data_Migration_Script_Base) {
720
+				$script_name = $currently_executing_script->pretty_name();
721
+				$currently_executing_script->set_broken();
722
+				$currently_executing_script->add_error($e->getMessage());
723
+			} else {
724
+				$script_name = __("Error getting Migration Script", "event_espresso");
725
+			}
726
+			$response_array = array(
727
+				'records_to_migrate' => 1,
728
+				'records_migrated'   => 0,
729
+				'status'             => self::status_fatal_error,
730
+				'message'            => sprintf(
731
+					__("A fatal error occurred during the migration: %s", "event_espresso"),
732
+					$e->getMessage()
733
+				),
734
+				'script'             => $script_name,
735
+			);
736
+		}
737
+		$successful_save = $this->_save_migrations_ran();
738
+		if ($successful_save !== true) {
739
+			// ok so the current wp option didn't save. that's tricky, because we'd like to update it
740
+			// and mark it as having a fatal error, but remember- WE CAN'T SAVE THIS WP OPTION!
741
+			// however, if we throw an exception, and return that, then the next request
742
+			// won't have as much info in it, and it may be able to save
743
+			throw new EE_Error(
744
+				sprintf(
745
+					__(
746
+						"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.",
747
+						"event_espresso"
748
+					),
749
+					$successful_save
750
+				)
751
+			);
752
+		}
753
+		// if we're all done, initialize EE plugins' default data etc.
754
+		if ($init_dbs) {
755
+			$this->initialize_db_for_enqueued_ee_plugins();
756
+		}
757
+		return $response_array;
758
+	}
759
+
760
+
761
+	/**
762
+	 * Echo out JSON response to migration script AJAX requests. Takes precautions
763
+	 * to buffer output so that we don't throw junk into our json.
764
+	 *
765
+	 * @return array with keys:
766
+	 * 'records_to_migrate' which counts ALL the records for the current migration, and should remain constant. (ie,
767
+	 * it's NOT the count of hwo many remain)
768
+	 * 'records_migrated' which also counts ALL the records which have been migrated (ie, percent_complete =
769
+	 * records_migrated/records_to_migrate)
770
+	 * 'status'=>a string, one of EE_Data_migration_Manager::status_*
771
+	 * 'message'=>a string, containing any message you want to show to the user. We may decide to split this up into
772
+	 * errors, notifications, and successes
773
+	 * 'script'=>a pretty name of the script currently running
774
+	 */
775
+	public function response_to_migration_ajax_request()
776
+	{
777
+		ob_start();
778
+		try {
779
+			$response = $this->migration_step();
780
+		} catch (Exception $e) {
781
+			$response = array(
782
+				'records_to_migrate' => 0,
783
+				'records_migrated'   => 0,
784
+				'status'             => EE_Data_Migration_Manager::status_fatal_error,
785
+				'message'            => sprintf(
786
+					__("Unknown fatal error occurred: %s", "event_espresso"),
787
+					$e->getMessage()
788
+				),
789
+				'script'             => 'Unknown',
790
+			);
791
+			$this->add_error_to_migrations_ran($e->getMessage() . "; Stack trace:" . $e->getTraceAsString());
792
+		}
793
+		$warnings_etc = @ob_get_contents();
794
+		ob_end_clean();
795
+		$response['message'] .= $warnings_etc;
796
+		return $response;
797
+	}
798
+
799
+	/**
800
+	 * Updates the wordpress option that keeps track of which which EE version the database
801
+	 * is at (ie, the code may be at 4.1.0, but the database is still at 3.1.35)
802
+	 *
803
+	 * @param array $slug_and_version {
804
+	 * @type string $slug             like 'Core' or 'Calendar',
805
+	 * @type string $version          like '4.1.0'
806
+	 *                                }
807
+	 * @return void
808
+	 */
809
+	public function update_current_database_state_to($slug_and_version = null)
810
+	{
811
+		if (! $slug_and_version) {
812
+			// no version was provided, assume it should be at the current code version
813
+			$slug_and_version = array('slug' => 'Core', 'version' => espresso_version());
814
+		}
815
+		$current_database_state = get_option(self::current_database_state);
816
+		$current_database_state[ $slug_and_version['slug'] ] = $slug_and_version['version'];
817
+		update_option(self::current_database_state, $current_database_state);
818
+	}
819
+
820
+	/**
821
+	 * Determines if the database is currently at a state matching what's indicated in $slug and $version.
822
+	 *
823
+	 * @param array $slug_and_version {
824
+	 * @type string $slug             like 'Core' or 'Calendar',
825
+	 * @type string $version          like '4.1.0'
826
+	 *                                }
827
+	 * @return boolean
828
+	 */
829
+	public function database_needs_updating_to($slug_and_version)
830
+	{
831
+
832
+		$slug = $slug_and_version['slug'];
833
+		$version = $slug_and_version['version'];
834
+		$current_database_state = get_option(self::current_database_state);
835
+		if (! isset($current_database_state[ $slug ])) {
836
+			return true;
837
+		} else {
838
+			// 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
839
+			$version_parts_current_db_state = array_slice(explode('.', $current_database_state[ $slug ]), 0, 3);
840
+			$version_parts_of_provided_db_state = array_slice(explode('.', $version), 0, 3);
841
+			$needs_updating = false;
842
+			foreach ($version_parts_current_db_state as $offset => $version_part_in_current_db_state) {
843
+				if ($version_part_in_current_db_state < $version_parts_of_provided_db_state[ $offset ]) {
844
+					$needs_updating = true;
845
+					break;
846
+				}
847
+			}
848
+			return $needs_updating;
849
+		}
850
+	}
851
+
852
+
853
+	/**
854
+	 * Gets all the data migration scripts available in the core folder and folders
855
+	 * in addons. Has the side effect of adding them for autoloading
856
+	 *
857
+	 * @return array keys are expected classnames, values are their filepaths
858
+	 * @throws InvalidInterfaceException
859
+	 * @throws InvalidDataTypeException
860
+	 * @throws EE_Error
861
+	 * @throws InvalidArgumentException
862
+	 */
863
+	public function get_all_data_migration_scripts_available()
864
+	{
865
+		if (! $this->_data_migration_class_to_filepath_map) {
866
+			$this->_data_migration_class_to_filepath_map = array();
867
+			foreach ($this->get_data_migration_script_folders() as $eeAddonClass => $folder_path) {
868
+				// strip any placeholders added to classname to make it a unique array key
869
+				$eeAddonClass = trim($eeAddonClass, '*');
870
+				$eeAddonClass = $eeAddonClass === 'Core' || class_exists($eeAddonClass)
871
+					? $eeAddonClass
872
+					: '';
873
+				$folder_path = EEH_File::end_with_directory_separator($folder_path);
874
+				$files = glob($folder_path . '*.dms.php');
875
+				if (empty($files)) {
876
+					continue;
877
+				}
878
+				foreach ($files as $file) {
879
+					$pos_of_last_slash = strrpos($file, DS);
880
+					$classname = str_replace('.dms.php', '', substr($file, $pos_of_last_slash + 1));
881
+					$migrates_to = $this->script_migrates_to_version($classname, $eeAddonClass);
882
+					$slug = $migrates_to['slug'];
883
+					// check that the slug as contained in the DMS is associated with
884
+					// the slug of an addon or core
885
+					if ($slug !== 'Core' && EE_Registry::instance()->get_addon_by_name($slug) === null) {
886
+						EE_Error::doing_it_wrong(
887
+							__FUNCTION__,
888
+							sprintf(
889
+								esc_html__(
890
+									'The data migration script "%s" migrates the "%s" data, but there is no EE addon with that name. There is only: %s. ',
891
+									'event_espresso'
892
+								),
893
+								$classname,
894
+								$slug,
895
+								implode(', ', array_keys(EE_Registry::instance()->get_addons_by_name()))
896
+							),
897
+							'4.3.0.alpha.019'
898
+						);
899
+					}
900
+					$this->_data_migration_class_to_filepath_map[ $classname ] = $file;
901
+				}
902
+			}
903
+			EEH_Autoloader::register_autoloader($this->_data_migration_class_to_filepath_map);
904
+		}
905
+		return $this->_data_migration_class_to_filepath_map;
906
+	}
907
+
908
+
909
+	/**
910
+	 * Once we have an addon that works with EE4.1, we will actually want to fetch the PUE slugs
911
+	 * from each addon, and check if they need updating,
912
+	 *
913
+	 * @return boolean
914
+	 */
915
+	public function addons_need_updating()
916
+	{
917
+		return false;
918
+	}
919
+
920
+	/**
921
+	 * Adds this error string to the data_migrations_ran array, but we dont necessarily know
922
+	 * where to put it, so we just throw it in there... better than nothing...
923
+	 *
924
+	 * @param string $error_message
925
+	 * @throws EE_Error
926
+	 */
927
+	public function add_error_to_migrations_ran($error_message)
928
+	{
929
+		// get last-ran migration script
930
+		global $wpdb;
931
+		$last_migration_script_option = $wpdb->get_row(
932
+			"SELECT * FROM $wpdb->options WHERE option_name like '" . EE_Data_Migration_Manager::data_migration_script_option_prefix . "%' ORDER BY option_id DESC LIMIT 1",
933
+			ARRAY_A
934
+		);
935
+
936
+		$last_ran_migration_script_properties = isset($last_migration_script_option['option_value'])
937
+			? maybe_unserialize($last_migration_script_option['option_value']) : null;
938
+		// now, tread lightly because we're here because a FATAL non-catchable error
939
+		// was thrown last time when we were trying to run a data migration script
940
+		// so the fatal error could have happened while getting the migration script
941
+		// or doing running it...
942
+		$versions_migrated_to = isset($last_migration_script_option['option_name']) ? str_replace(
943
+			EE_Data_Migration_Manager::data_migration_script_option_prefix,
944
+			"",
945
+			$last_migration_script_option['option_name']
946
+		) : null;
947
+
948
+		// check if it THINKS its a data migration script and especially if it's one that HASN'T finished yet
949
+		// because if it has finished, then it obviously couldn't be the cause of this error, right? (because its all done)
950
+		if (isset($last_ran_migration_script_properties['class']) && isset($last_ran_migration_script_properties['_status']) && $last_ran_migration_script_properties['_status'] != self::status_completed) {
951
+			// ok then just add this error to its list of errors
952
+			$last_ran_migration_script_properties['_errors'][] = $error_message;
953
+			$last_ran_migration_script_properties['_status'] = self::status_fatal_error;
954
+		} else {
955
+			// so we don't even know which script was last running
956
+			// use the data migration error stub, which is designed specifically for this type of thing
957
+			$general_migration_error = new EE_DMS_Unknown_1_0_0();
958
+			$general_migration_error->add_error($error_message);
959
+			$general_migration_error->set_broken();
960
+			$last_ran_migration_script_properties = $general_migration_error->properties_as_array();
961
+			$versions_migrated_to = 'Unknown.1.0.0';
962
+			// now just to make sure appears as last (in case the were previously a fatal error like this)
963
+			// delete the old one
964
+			delete_option(self::data_migration_script_option_prefix . $versions_migrated_to);
965
+		}
966
+		update_option(
967
+			self::data_migration_script_option_prefix . $versions_migrated_to,
968
+			$last_ran_migration_script_properties
969
+		);
970
+	}
971
+
972
+	/**
973
+	 * saves what data migrations have ran to the database
974
+	 *
975
+	 * @return mixed TRUE if successfully saved migrations ran, string if an error occurred
976
+	 */
977
+	protected function _save_migrations_ran()
978
+	{
979
+		if ($this->_data_migrations_ran == null) {
980
+			$this->get_data_migrations_ran();
981
+		}
982
+		// now, we don't want to save actual classes to the DB because that's messy
983
+		$successful_updates = true;
984
+		foreach ($this->_data_migrations_ran as $plugin_slug => $migrations_ran_for_plugin) {
985
+			foreach ($migrations_ran_for_plugin as $version_string => $array_or_migration_obj) {
986
+				$plugin_slug_for_use_in_option_name = $plugin_slug . ".";
987
+				$option_name = self::data_migration_script_option_prefix . $plugin_slug_for_use_in_option_name . $version_string;
988
+				$old_option_value = get_option($option_name);
989
+				if ($array_or_migration_obj instanceof EE_Data_Migration_Script_Base) {
990
+					$script_array_for_saving = $array_or_migration_obj->properties_as_array();
991
+					if ($old_option_value != $script_array_for_saving) {
992
+						$successful_updates = update_option($option_name, $script_array_for_saving);
993
+					}
994
+				} else {// we don't know what this array-thing is. So just save it as-is
995
+					if ($old_option_value != $array_or_migration_obj) {
996
+						$successful_updates = update_option($option_name, $array_or_migration_obj);
997
+					}
998
+				}
999
+				if (! $successful_updates) {
1000
+					global $wpdb;
1001
+					return $wpdb->last_error;
1002
+				}
1003
+			}
1004
+		}
1005
+		return true;
1006
+		// $updated = update_option(self::data_migrations_option_name, $array_of_migrations);
1007
+		// if ($updated !== true) {
1008
+		//     global $wpdb;
1009
+		//     return $wpdb->last_error;
1010
+		// } else {
1011
+		//     return true;
1012
+		// }
1013
+		// wp_mail(
1014
+		//     "[email protected]",
1015
+		//     time() . " price debug info",
1016
+		//     "updated: $updated, last error: $last_error, byte length of option: " . strlen(
1017
+		//         serialize($array_of_migrations)
1018
+		//     )
1019
+		// );
1020
+	}
1021
+
1022
+	/**
1023
+	 * Takes an array of data migration script properties and re-creates the class from
1024
+	 * them. The argument $properties_array is assumed to have been made by
1025
+	 * EE_Data_Migration_Script_Base::properties_as_array()
1026
+	 *
1027
+	 * @param array $properties_array
1028
+	 * @return EE_Data_Migration_Script_Base
1029
+	 * @throws EE_Error
1030
+	 */
1031
+	public function _instantiate_script_from_properties_array($properties_array)
1032
+	{
1033
+		if (! isset($properties_array['class'])) {
1034
+			throw new EE_Error(
1035
+				sprintf(
1036
+					__("Properties array  has no 'class' properties. Here's what it has: %s", "event_espresso"),
1037
+					implode(",", $properties_array)
1038
+				)
1039
+			);
1040
+		}
1041
+		$class_name = $properties_array['class'];
1042
+		if (! class_exists($class_name)) {
1043
+			throw new EE_Error(sprintf(__("There is no migration script named %s", "event_espresso"), $class_name));
1044
+		}
1045
+		$class = new $class_name;
1046
+		if (! $class instanceof EE_Data_Migration_Script_Base) {
1047
+			throw new EE_Error(
1048
+				sprintf(
1049
+					__("Class '%s' is supposed to be a migration script. Its not, its a '%s'", "event_espresso"),
1050
+					$class_name,
1051
+					get_class($class)
1052
+				)
1053
+			);
1054
+		}
1055
+		$class->instantiate_from_array_of_properties($properties_array);
1056
+		return $class;
1057
+	}
1058
+
1059
+	/**
1060
+	 * Gets the classname for the most up-to-date DMS (ie, the one that will finally
1061
+	 * leave the DB in a state usable by the current plugin code).
1062
+	 *
1063
+	 * @param string $plugin_slug the slug for the ee plugin we are searching for. Default is 'Core'
1064
+	 * @return string
1065
+	 */
1066
+	public function get_most_up_to_date_dms($plugin_slug = 'Core')
1067
+	{
1068
+		$class_to_filepath_map = $this->get_all_data_migration_scripts_available();
1069
+		$most_up_to_date_dms_classname = null;
1070
+		foreach ($class_to_filepath_map as $classname => $filepath) {
1071
+			if ($most_up_to_date_dms_classname === null) {
1072
+				$migrates_to = $this->script_migrates_to_version($classname);
1073
+				$this_plugin_slug = $migrates_to['slug'];
1074
+				if ($this_plugin_slug == $plugin_slug) {
1075
+					// if it's for core, it wins
1076
+					$most_up_to_date_dms_classname = $classname;
1077
+				}
1078
+				// if it wasn't for core, we must keep searching for one that is!
1079
+				continue;
1080
+			} else {
1081
+				$champion_migrates_to = $this->script_migrates_to_version($most_up_to_date_dms_classname);
1082
+				$contender_migrates_to = $this->script_migrates_to_version($classname);
1083
+				if ($contender_migrates_to['slug'] == $plugin_slug
1084
+					&& version_compare(
1085
+						$champion_migrates_to['version'],
1086
+						$contender_migrates_to['version'],
1087
+						'<'
1088
+					)) {
1089
+					// so the contenders version is higher and its for Core
1090
+					$most_up_to_date_dms_classname = $classname;
1091
+				}
1092
+			}
1093
+		}
1094
+		return $most_up_to_date_dms_classname;
1095
+	}
1096
+
1097
+	/**
1098
+	 * Gets the migration script specified but ONLY if it has already ran.
1099
+	 *
1100
+	 * Eg, if you wanted to see if 'EE_DMS_Core_4_1_0' has ran, you would run the following code:
1101
+	 * <code> $core_4_1_0_dms_ran = EE_Data_Migration_Manager::instance()->get_migration_ran( '4.1.0', 'Core' ) !==
1102
+	 * NULL;</code> This is especially useful in addons' data migration scripts, this way they can tell if a core (or
1103
+	 * other addon) DMS has ran, in case the current DMS depends on it.
1104
+	 *
1105
+	 * @param string $version     the version the DMS searched for migrates to. Usually just the content before the 3rd
1106
+	 *                            period. Eg '4.1.0'
1107
+	 * @param string $plugin_slug like 'Core', 'Mailchimp', 'Calendar', etc
1108
+	 * @return EE_Data_Migration_Script_Base
1109
+	 */
1110
+	public function get_migration_ran($version, $plugin_slug = 'Core')
1111
+	{
1112
+		$migrations_ran = $this->get_data_migrations_ran();
1113
+		if (isset($migrations_ran[ $plugin_slug ]) && isset($migrations_ran[ $plugin_slug ][ $version ])) {
1114
+			return $migrations_ran[ $plugin_slug ][ $version ];
1115
+		} else {
1116
+			return null;
1117
+		}
1118
+	}
1119
+
1120
+	/**
1121
+	 * Resets the borked data migration scripts so they're no longer borked
1122
+	 * so we can again attempt to migrate
1123
+	 *
1124
+	 * @return bool
1125
+	 * @throws EE_Error
1126
+	 */
1127
+	public function reattempt()
1128
+	{
1129
+		// find if the last-ran script was borked
1130
+		// set it as being non-borked (we shouldn't ever get DMSs that we don't recognize)
1131
+		// add an 'error' saying that we attempted to reset
1132
+		// does it have a stage that was borked too? if so make it no longer borked
1133
+		// add an 'error' saying we attempted to reset
1134
+		$last_ran_script = $this->get_last_ran_script();
1135
+		if ($last_ran_script instanceof EE_DMS_Unknown_1_0_0) {
1136
+			// if it was an error DMS, just mark it as complete (if another error occurs it will overwrite it)
1137
+			$last_ran_script->set_completed();
1138
+		} elseif ($last_ran_script instanceof EE_Data_Migration_Script_Base) {
1139
+			$last_ran_script->reattempt();
1140
+		} else {
1141
+			throw new EE_Error(
1142
+				sprintf(
1143
+					__(
1144
+						'Unable to reattempt the last ran migration script because it was not a valid migration script. || It was %s',
1145
+						'event_espresso'
1146
+					),
1147
+					print_r($last_ran_script, true)
1148
+				)
1149
+			);
1150
+		}
1151
+		return $this->_save_migrations_ran();
1152
+	}
1153
+
1154
+	/**
1155
+	 * Gets whether or not this particular migration has run or not
1156
+	 *
1157
+	 * @param string $version     the version the DMS searched for migrates to. Usually just the content before the 3rd
1158
+	 *                            period. Eg '4.1.0'
1159
+	 * @param string $plugin_slug like 'Core', 'Mailchimp', 'Calendar', etc
1160
+	 * @return boolean
1161
+	 */
1162
+	public function migration_has_ran($version, $plugin_slug = 'Core')
1163
+	{
1164
+		return $this->get_migration_ran($version, $plugin_slug) !== null;
1165
+	}
1166
+
1167
+	/**
1168
+	 * Enqueues this ee plugin to have its data initialized
1169
+	 *
1170
+	 * @param string $plugin_slug either 'Core' or EE_Addon::name()'s return value
1171
+	 */
1172
+	public function enqueue_db_initialization_for($plugin_slug)
1173
+	{
1174
+		$queue = $this->get_db_initialization_queue();
1175
+		if (! in_array($plugin_slug, $queue)) {
1176
+			$queue[] = $plugin_slug;
1177
+		}
1178
+		update_option(self::db_init_queue_option_name, $queue);
1179
+	}
1180
+
1181
+	/**
1182
+	 * Calls EE_Addon::initialize_db_if_no_migrations_required() on each addon
1183
+	 * specified in EE_Data_Migration_Manager::get_db_init_queue(), and if 'Core' is
1184
+	 * in the queue, calls EE_System::initialize_db_if_no_migrations_required().
1185
+	 */
1186
+	public function initialize_db_for_enqueued_ee_plugins()
1187
+	{
1188
+		$queue = $this->get_db_initialization_queue();
1189
+		foreach ($queue as $plugin_slug) {
1190
+			$most_up_to_date_dms = $this->get_most_up_to_date_dms($plugin_slug);
1191
+			if (! $most_up_to_date_dms) {
1192
+				// if there is NO DMS for this plugin, obviously there's no schema to verify anyways
1193
+				$verify_db = false;
1194
+			} else {
1195
+				$most_up_to_date_dms_migrates_to = $this->script_migrates_to_version($most_up_to_date_dms);
1196
+				$verify_db = $this->database_needs_updating_to($most_up_to_date_dms_migrates_to);
1197
+			}
1198
+			if ($plugin_slug == 'Core') {
1199
+				EE_System::instance()->initialize_db_if_no_migrations_required(
1200
+					false,
1201
+					$verify_db
1202
+				);
1203
+			} else {
1204
+				// just loop through the addons to make sure their database is setup
1205
+				foreach (EE_Registry::instance()->addons as $addon) {
1206
+					if ($addon->name() == $plugin_slug) {
1207
+						$addon->initialize_db_if_no_migrations_required($verify_db);
1208
+						break;
1209
+					}
1210
+				}
1211
+			}
1212
+		}
1213
+		// because we just initialized the DBs for the enqueued ee plugins
1214
+		// we don't need to keep remembering which ones needed to be initialized
1215
+		delete_option(self::db_init_queue_option_name);
1216
+	}
1217
+
1218
+	/**
1219
+	 * Gets a numerically-indexed array of plugin slugs that need to have their databases
1220
+	 * (re-)initialized after migrations are complete. ie, each element should be either
1221
+	 * 'Core', or the return value of EE_Addon::name() for an addon
1222
+	 *
1223
+	 * @return array
1224
+	 */
1225
+	public function get_db_initialization_queue()
1226
+	{
1227
+		return get_option(self::db_init_queue_option_name, array());
1228
+	}
1229
+
1230
+	/**
1231
+	 * Gets the injected table analyzer, or throws an exception
1232
+	 *
1233
+	 * @return TableAnalysis
1234
+	 * @throws EE_Error
1235
+	 */
1236
+	protected function _get_table_analysis()
1237
+	{
1238
+		if ($this->_table_analysis instanceof TableAnalysis) {
1239
+			return $this->_table_analysis;
1240
+		} else {
1241
+			throw new EE_Error(
1242
+				sprintf(
1243
+					__('Table analysis class on class %1$s is not set properly.', 'event_espresso'),
1244
+					get_class($this)
1245
+				)
1246
+			);
1247
+		}
1248
+	}
1249
+
1250
+	/**
1251
+	 * Gets the injected table manager, or throws an exception
1252
+	 *
1253
+	 * @return TableManager
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	protected function _get_table_manager()
1257
+	{
1258
+		if ($this->_table_manager instanceof TableManager) {
1259
+			return $this->_table_manager;
1260
+		} else {
1261
+			throw new EE_Error(
1262
+				sprintf(
1263
+					__('Table manager class on class %1$s is not set properly.', 'event_espresso'),
1264
+					get_class($this)
1265
+				)
1266
+			);
1267
+		}
1268
+	}
1269 1269
 }
Please login to merge, or discard this patch.
Spacing   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
     public static function instance()
158 158
     {
159 159
         // check if class object is instantiated
160
-        if (! self::$_instance instanceof EE_Data_Migration_Manager) {
160
+        if ( ! self::$_instance instanceof EE_Data_Migration_Manager) {
161 161
             self::$_instance = new self();
162 162
         }
163 163
         return self::$_instance;
@@ -233,12 +233,12 @@  discard block
 block discarded – undo
233 233
 
234 234
         if (count($parts) == 4) {
235 235
             // it's 4.2-style.eg Core.4.1.0
236
-            $plugin_slug = $parts[0];// eg Core
237
-            $version_string = $parts[1] . "." . $parts[2] . "." . $parts[3]; // eg 4.1.0
236
+            $plugin_slug = $parts[0]; // eg Core
237
+            $version_string = $parts[1].".".$parts[2].".".$parts[3]; // eg 4.1.0
238 238
         } else {
239 239
             // it's 4.1-style: eg 4.1.0
240 240
             $plugin_slug = 'Core';
241
-            $version_string = $plugin_slug_and_version_string;// eg 4.1.0
241
+            $version_string = $plugin_slug_and_version_string; // eg 4.1.0
242 242
         }
243 243
         return array($plugin_slug, $version_string);
244 244
     }
@@ -290,11 +290,11 @@  discard block
 block discarded – undo
290 290
      */
291 291
     public function get_data_migrations_ran()
292 292
     {
293
-        if (! $this->_data_migrations_ran) {
293
+        if ( ! $this->_data_migrations_ran) {
294 294
             // setup autoloaders for each of the scripts in there
295 295
             $this->get_all_data_migration_scripts_available();
296 296
             $data_migrations_options = $this->get_all_migration_script_options(
297
-            );// get_option(EE_Data_Migration_Manager::data_migrations_option_name,get_option('espresso_data_migrations',array()));
297
+            ); // get_option(EE_Data_Migration_Manager::data_migrations_option_name,get_option('espresso_data_migrations',array()));
298 298
 
299 299
             $data_migrations_ran = array();
300 300
             // convert into data migration script classes where possible
@@ -308,23 +308,23 @@  discard block
 block discarded – undo
308 308
                         $data_migration_option['option_name'],
309 309
                         $data_migration_option['option_value']
310 310
                     );
311
-                    $data_migrations_ran[ $plugin_slug ][ $version_string ] = $class;
311
+                    $data_migrations_ran[$plugin_slug][$version_string] = $class;
312 312
                     // ok so far THIS is the 'last-ran-script'... unless we find another on next iteration
313 313
                     $this->_last_ran_script = $class;
314
-                    if (! $class->is_completed()) {
314
+                    if ( ! $class->is_completed()) {
315 315
                         // sometimes we also like to know which was the last incomplete script (or if there are any at all)
316 316
                         $this->_last_ran_incomplete_script = $class;
317 317
                     }
318 318
                 } catch (EE_Error $e) {
319 319
                     // ok so its not a DMS. We'll just keep it, although other code will need to expect non-DMSs
320
-                    $data_migrations_ran[ $plugin_slug ][ $version_string ] = maybe_unserialize(
320
+                    $data_migrations_ran[$plugin_slug][$version_string] = maybe_unserialize(
321 321
                         $data_migration_option['option_value']
322 322
                     );
323 323
                 }
324 324
             }
325 325
             // so here the array of $data_migrations_ran is actually a mix of classes and a few legacy arrays
326 326
             $this->_data_migrations_ran = $data_migrations_ran;
327
-            if (! $this->_data_migrations_ran || ! is_array($this->_data_migrations_ran)) {
327
+            if ( ! $this->_data_migrations_ran || ! is_array($this->_data_migrations_ran)) {
328 328
                 $this->_data_migrations_ran = array();
329 329
             }
330 330
         }
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
     {
358 358
         global $wpdb;
359 359
         return $wpdb->get_results(
360
-            "SELECT * FROM {$wpdb->options} WHERE option_name like '" . EE_Data_Migration_Manager::data_migration_script_option_prefix . "%' ORDER BY option_id ASC",
360
+            "SELECT * FROM {$wpdb->options} WHERE option_name like '".EE_Data_Migration_Manager::data_migration_script_option_prefix."%' ORDER BY option_id ASC",
361 361
             ARRAY_A
362 362
         );
363 363
     }
@@ -372,7 +372,7 @@  discard block
 block discarded – undo
372 372
     {
373 373
         return apply_filters(
374 374
             'FHEE__EE_Data_Migration_Manager__get_data_migration_script_folders',
375
-            array('Core' => EE_CORE . 'data_migration_scripts')
375
+            array('Core' => EE_CORE.'data_migration_scripts')
376 376
         );
377 377
     }
378 378
 
@@ -388,15 +388,15 @@  discard block
 block discarded – undo
388 388
      */
389 389
     public function script_migrates_to_version($migration_script_name, $eeAddonClass = '')
390 390
     {
391
-        if (isset($this->script_migration_versions[ $migration_script_name ])) {
392
-            return $this->script_migration_versions[ $migration_script_name ];
391
+        if (isset($this->script_migration_versions[$migration_script_name])) {
392
+            return $this->script_migration_versions[$migration_script_name];
393 393
         }
394 394
         $dms_info = $this->parse_dms_classname($migration_script_name);
395
-        $this->script_migration_versions[ $migration_script_name ] = array(
395
+        $this->script_migration_versions[$migration_script_name] = array(
396 396
             'slug'    => $eeAddonClass !== '' ? $eeAddonClass : $dms_info['slug'],
397
-            'version' => $dms_info['major_version'] . "." . $dms_info['minor_version'] . "." . $dms_info['micro_version'],
397
+            'version' => $dms_info['major_version'].".".$dms_info['minor_version'].".".$dms_info['micro_version'],
398 398
         );
399
-        return $this->script_migration_versions[ $migration_script_name ];
399
+        return $this->script_migration_versions[$migration_script_name];
400 400
     }
401 401
 
402 402
     /**
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
     {
411 411
         $matches = array();
412 412
         preg_match('~EE_DMS_(.*)_([0-9]*)_([0-9]*)_([0-9]*)~', $classname, $matches);
413
-        if (! $matches || ! (isset($matches[1]) && isset($matches[2]) && isset($matches[3]))) {
413
+        if ( ! $matches || ! (isset($matches[1]) && isset($matches[2]) && isset($matches[3]))) {
414 414
             throw new EE_Error(
415 415
                 sprintf(
416 416
                     __(
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
     {
442 442
         $espresso_db_core_updates = get_option('espresso_db_update', array());
443 443
         $db_state = get_option(EE_Data_Migration_Manager::current_database_state);
444
-        if (! $db_state) {
444
+        if ( ! $db_state) {
445 445
             // mark the DB as being in the state as the last version in there.
446 446
             // this is done to trigger maintenance mode and do data migration scripts
447 447
             // if the admin installed this version of EE over 3.1.x or 4.0.x
@@ -460,7 +460,7 @@  discard block
 block discarded – undo
460 460
         // in 4.1, $db_state would have only been a simple string like '4.1.0',
461 461
         // but in 4.2+ it should be an array with at least key 'Core' and the value of that plugin's
462 462
         // db, and possibly other keys for other addons like 'Calendar','Permissions',etc
463
-        if (! is_array($db_state)) {
463
+        if ( ! is_array($db_state)) {
464 464
             $db_state = array('Core' => $db_state);
465 465
             update_option(EE_Data_Migration_Manager::current_database_state, $db_state);
466 466
         }
@@ -497,29 +497,29 @@  discard block
 block discarded – undo
497 497
                 $script_converts_plugin_slug = $migrates_to_version['slug'];
498 498
                 $script_converts_to_version = $migrates_to_version['version'];
499 499
                 // check if this version script is DONE or not; or if it's never been ran
500
-                if (! $scripts_ran ||
501
-                    ! isset($scripts_ran[ $script_converts_plugin_slug ]) ||
502
-                    ! isset($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ])) {
500
+                if ( ! $scripts_ran ||
501
+                    ! isset($scripts_ran[$script_converts_plugin_slug]) ||
502
+                    ! isset($scripts_ran[$script_converts_plugin_slug][$script_converts_to_version])) {
503 503
                     // we haven't ran this conversion script before
504 504
                     // now check if it applies... note that we've added an autoloader for it on get_all_data_migration_scripts_available
505 505
                     $script = new $classname($this->_get_table_manager(), $this->_get_table_analysis());
506 506
                     /* @var $script EE_Data_Migration_Script_Base */
507 507
                     $can_migrate = $script->can_migrate_from_version($theoretical_database_state);
508 508
                     if ($can_migrate) {
509
-                        $script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
509
+                        $script_classes_that_should_run_per_iteration[$iteration][$script->priority()][] = $script;
510 510
                         $migrates_to_version = $script->migrates_to_version();
511
-                        $next_database_state_to_consider[ $migrates_to_version['slug'] ] = $migrates_to_version['version'];
512
-                        unset($script_class_and_filepaths_available[ $classname ]);
511
+                        $next_database_state_to_consider[$migrates_to_version['slug']] = $migrates_to_version['version'];
512
+                        unset($script_class_and_filepaths_available[$classname]);
513 513
                     }
514
-                } elseif ($scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ] instanceof EE_Data_Migration_Script_Base) {
514
+                } elseif ($scripts_ran[$script_converts_plugin_slug][$script_converts_to_version] instanceof EE_Data_Migration_Script_Base) {
515 515
                     // this script has been ran, or at least started
516
-                    $script = $scripts_ran[ $script_converts_plugin_slug ][ $script_converts_to_version ];
516
+                    $script = $scripts_ran[$script_converts_plugin_slug][$script_converts_to_version];
517 517
                     if ($script->get_status() != self::status_completed) {
518 518
                         // this script is already underway... keep going with it
519
-                        $script_classes_that_should_run_per_iteration[ $iteration ][ $script->priority() ][] = $script;
519
+                        $script_classes_that_should_run_per_iteration[$iteration][$script->priority()][] = $script;
520 520
                         $migrates_to_version = $script->migrates_to_version();
521
-                        $next_database_state_to_consider[ $migrates_to_version['slug'] ] = $migrates_to_version['version'];
522
-                        unset($script_class_and_filepaths_available[ $classname ]);
521
+                        $next_database_state_to_consider[$migrates_to_version['slug']] = $migrates_to_version['version'];
522
+                        unset($script_class_and_filepaths_available[$classname]);
523 523
                     } else {
524 524
                         // it must have a status that indicates it has finished, so we don't want to try and run it again
525 525
                     }
@@ -530,14 +530,14 @@  discard block
 block discarded – undo
530 530
                 }
531 531
             }
532 532
             $iteration++;
533
-        } while ($next_database_state_to_consider != $theoretical_database_state && $iteration < 6);
533
+        }while ($next_database_state_to_consider != $theoretical_database_state && $iteration < 6);
534 534
         // ok we have all the scripts that should run, now let's make them into flat array
535 535
         $scripts_that_should_run = array();
536 536
         foreach ($script_classes_that_should_run_per_iteration as $scripts_at_priority) {
537 537
             ksort($scripts_at_priority);
538 538
             foreach ($scripts_at_priority as $scripts) {
539 539
                 foreach ($scripts as $script) {
540
-                    $scripts_that_should_run[ get_class($script) ] = $script;
540
+                    $scripts_that_should_run[get_class($script)] = $script;
541 541
                 }
542 542
             }
543 543
         }
@@ -562,7 +562,7 @@  discard block
 block discarded – undo
562 562
     public function get_last_ran_script($include_completed_scripts = false)
563 563
     {
564 564
         // make sure we've setup the class properties _last_ran_script and _last_ran_incomplete_script
565
-        if (! $this->_data_migrations_ran) {
565
+        if ( ! $this->_data_migrations_ran) {
566 566
             $this->get_data_migrations_ran();
567 567
         }
568 568
         if ($include_completed_scripts) {
@@ -599,10 +599,10 @@  discard block
 block discarded – undo
599 599
 
600 600
         try {
601 601
             $currently_executing_script = $this->get_last_ran_script();
602
-            if (! $currently_executing_script) {
602
+            if ( ! $currently_executing_script) {
603 603
                 // Find the next script that needs to execute
604 604
                 $scripts = $this->check_for_applicable_data_migration_scripts();
605
-                if (! $scripts) {
605
+                if ( ! $scripts) {
606 606
                     // huh, no more scripts to run... apparently we're done!
607 607
                     // but dont forget to make sure initial data is there
608 608
                     // we should be good to allow them to exit maintenance mode now
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
                 $migrates_to = $this->script_migrates_to_version(get_class($currently_executing_script));
629 629
                 $plugin_slug = $migrates_to['slug'];
630 630
                 $version = $migrates_to['version'];
631
-                $this->_data_migrations_ran[ $plugin_slug ][ $version ] = $currently_executing_script;
631
+                $this->_data_migrations_ran[$plugin_slug][$version] = $currently_executing_script;
632 632
             }
633 633
             $current_script_name = get_class($currently_executing_script);
634 634
         } catch (Exception $e) {
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
 
637 637
             $message = sprintf(
638 638
                 __("Error Message: %sStack Trace:%s", "event_espresso"),
639
-                $e->getMessage() . '<br>',
639
+                $e->getMessage().'<br>',
640 640
                 $e->getTraceAsString()
641 641
             );
642 642
             // record it on the array of data migration scripts ran. This will be overwritten next time we try and try to run data migrations
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
                     );
689 689
                     // check if there are any more after this one.
690 690
                     $scripts_remaining = $this->check_for_applicable_data_migration_scripts();
691
-                    if (! $scripts_remaining) {
691
+                    if ( ! $scripts_remaining) {
692 692
                         // we should be good to allow them to exit maintenance mode now
693 693
                         EE_Maintenance_Mode::instance()->set_maintenance_level(
694 694
                             intval(EE_Maintenance_Mode::level_0_not_in_maintenance)
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
                 ),
789 789
                 'script'             => 'Unknown',
790 790
             );
791
-            $this->add_error_to_migrations_ran($e->getMessage() . "; Stack trace:" . $e->getTraceAsString());
791
+            $this->add_error_to_migrations_ran($e->getMessage()."; Stack trace:".$e->getTraceAsString());
792 792
         }
793 793
         $warnings_etc = @ob_get_contents();
794 794
         ob_end_clean();
@@ -808,12 +808,12 @@  discard block
 block discarded – undo
808 808
      */
809 809
     public function update_current_database_state_to($slug_and_version = null)
810 810
     {
811
-        if (! $slug_and_version) {
811
+        if ( ! $slug_and_version) {
812 812
             // no version was provided, assume it should be at the current code version
813 813
             $slug_and_version = array('slug' => 'Core', 'version' => espresso_version());
814 814
         }
815 815
         $current_database_state = get_option(self::current_database_state);
816
-        $current_database_state[ $slug_and_version['slug'] ] = $slug_and_version['version'];
816
+        $current_database_state[$slug_and_version['slug']] = $slug_and_version['version'];
817 817
         update_option(self::current_database_state, $current_database_state);
818 818
     }
819 819
 
@@ -832,15 +832,15 @@  discard block
 block discarded – undo
832 832
         $slug = $slug_and_version['slug'];
833 833
         $version = $slug_and_version['version'];
834 834
         $current_database_state = get_option(self::current_database_state);
835
-        if (! isset($current_database_state[ $slug ])) {
835
+        if ( ! isset($current_database_state[$slug])) {
836 836
             return true;
837 837
         } else {
838 838
             // 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
839
-            $version_parts_current_db_state = array_slice(explode('.', $current_database_state[ $slug ]), 0, 3);
839
+            $version_parts_current_db_state = array_slice(explode('.', $current_database_state[$slug]), 0, 3);
840 840
             $version_parts_of_provided_db_state = array_slice(explode('.', $version), 0, 3);
841 841
             $needs_updating = false;
842 842
             foreach ($version_parts_current_db_state as $offset => $version_part_in_current_db_state) {
843
-                if ($version_part_in_current_db_state < $version_parts_of_provided_db_state[ $offset ]) {
843
+                if ($version_part_in_current_db_state < $version_parts_of_provided_db_state[$offset]) {
844 844
                     $needs_updating = true;
845 845
                     break;
846 846
                 }
@@ -862,7 +862,7 @@  discard block
 block discarded – undo
862 862
      */
863 863
     public function get_all_data_migration_scripts_available()
864 864
     {
865
-        if (! $this->_data_migration_class_to_filepath_map) {
865
+        if ( ! $this->_data_migration_class_to_filepath_map) {
866 866
             $this->_data_migration_class_to_filepath_map = array();
867 867
             foreach ($this->get_data_migration_script_folders() as $eeAddonClass => $folder_path) {
868 868
                 // strip any placeholders added to classname to make it a unique array key
@@ -871,7 +871,7 @@  discard block
 block discarded – undo
871 871
                     ? $eeAddonClass
872 872
                     : '';
873 873
                 $folder_path = EEH_File::end_with_directory_separator($folder_path);
874
-                $files = glob($folder_path . '*.dms.php');
874
+                $files = glob($folder_path.'*.dms.php');
875 875
                 if (empty($files)) {
876 876
                     continue;
877 877
                 }
@@ -897,7 +897,7 @@  discard block
 block discarded – undo
897 897
                             '4.3.0.alpha.019'
898 898
                         );
899 899
                     }
900
-                    $this->_data_migration_class_to_filepath_map[ $classname ] = $file;
900
+                    $this->_data_migration_class_to_filepath_map[$classname] = $file;
901 901
                 }
902 902
             }
903 903
             EEH_Autoloader::register_autoloader($this->_data_migration_class_to_filepath_map);
@@ -929,7 +929,7 @@  discard block
 block discarded – undo
929 929
         // get last-ran migration script
930 930
         global $wpdb;
931 931
         $last_migration_script_option = $wpdb->get_row(
932
-            "SELECT * FROM $wpdb->options WHERE option_name like '" . EE_Data_Migration_Manager::data_migration_script_option_prefix . "%' ORDER BY option_id DESC LIMIT 1",
932
+            "SELECT * FROM $wpdb->options WHERE option_name like '".EE_Data_Migration_Manager::data_migration_script_option_prefix."%' ORDER BY option_id DESC LIMIT 1",
933 933
             ARRAY_A
934 934
         );
935 935
 
@@ -961,10 +961,10 @@  discard block
 block discarded – undo
961 961
             $versions_migrated_to = 'Unknown.1.0.0';
962 962
             // now just to make sure appears as last (in case the were previously a fatal error like this)
963 963
             // delete the old one
964
-            delete_option(self::data_migration_script_option_prefix . $versions_migrated_to);
964
+            delete_option(self::data_migration_script_option_prefix.$versions_migrated_to);
965 965
         }
966 966
         update_option(
967
-            self::data_migration_script_option_prefix . $versions_migrated_to,
967
+            self::data_migration_script_option_prefix.$versions_migrated_to,
968 968
             $last_ran_migration_script_properties
969 969
         );
970 970
     }
@@ -983,8 +983,8 @@  discard block
 block discarded – undo
983 983
         $successful_updates = true;
984 984
         foreach ($this->_data_migrations_ran as $plugin_slug => $migrations_ran_for_plugin) {
985 985
             foreach ($migrations_ran_for_plugin as $version_string => $array_or_migration_obj) {
986
-                $plugin_slug_for_use_in_option_name = $plugin_slug . ".";
987
-                $option_name = self::data_migration_script_option_prefix . $plugin_slug_for_use_in_option_name . $version_string;
986
+                $plugin_slug_for_use_in_option_name = $plugin_slug.".";
987
+                $option_name = self::data_migration_script_option_prefix.$plugin_slug_for_use_in_option_name.$version_string;
988 988
                 $old_option_value = get_option($option_name);
989 989
                 if ($array_or_migration_obj instanceof EE_Data_Migration_Script_Base) {
990 990
                     $script_array_for_saving = $array_or_migration_obj->properties_as_array();
@@ -996,7 +996,7 @@  discard block
 block discarded – undo
996 996
                         $successful_updates = update_option($option_name, $array_or_migration_obj);
997 997
                     }
998 998
                 }
999
-                if (! $successful_updates) {
999
+                if ( ! $successful_updates) {
1000 1000
                     global $wpdb;
1001 1001
                     return $wpdb->last_error;
1002 1002
                 }
@@ -1030,7 +1030,7 @@  discard block
 block discarded – undo
1030 1030
      */
1031 1031
     public function _instantiate_script_from_properties_array($properties_array)
1032 1032
     {
1033
-        if (! isset($properties_array['class'])) {
1033
+        if ( ! isset($properties_array['class'])) {
1034 1034
             throw new EE_Error(
1035 1035
                 sprintf(
1036 1036
                     __("Properties array  has no 'class' properties. Here's what it has: %s", "event_espresso"),
@@ -1039,11 +1039,11 @@  discard block
 block discarded – undo
1039 1039
             );
1040 1040
         }
1041 1041
         $class_name = $properties_array['class'];
1042
-        if (! class_exists($class_name)) {
1042
+        if ( ! class_exists($class_name)) {
1043 1043
             throw new EE_Error(sprintf(__("There is no migration script named %s", "event_espresso"), $class_name));
1044 1044
         }
1045 1045
         $class = new $class_name;
1046
-        if (! $class instanceof EE_Data_Migration_Script_Base) {
1046
+        if ( ! $class instanceof EE_Data_Migration_Script_Base) {
1047 1047
             throw new EE_Error(
1048 1048
                 sprintf(
1049 1049
                     __("Class '%s' is supposed to be a migration script. Its not, its a '%s'", "event_espresso"),
@@ -1110,8 +1110,8 @@  discard block
 block discarded – undo
1110 1110
     public function get_migration_ran($version, $plugin_slug = 'Core')
1111 1111
     {
1112 1112
         $migrations_ran = $this->get_data_migrations_ran();
1113
-        if (isset($migrations_ran[ $plugin_slug ]) && isset($migrations_ran[ $plugin_slug ][ $version ])) {
1114
-            return $migrations_ran[ $plugin_slug ][ $version ];
1113
+        if (isset($migrations_ran[$plugin_slug]) && isset($migrations_ran[$plugin_slug][$version])) {
1114
+            return $migrations_ran[$plugin_slug][$version];
1115 1115
         } else {
1116 1116
             return null;
1117 1117
         }
@@ -1172,7 +1172,7 @@  discard block
 block discarded – undo
1172 1172
     public function enqueue_db_initialization_for($plugin_slug)
1173 1173
     {
1174 1174
         $queue = $this->get_db_initialization_queue();
1175
-        if (! in_array($plugin_slug, $queue)) {
1175
+        if ( ! in_array($plugin_slug, $queue)) {
1176 1176
             $queue[] = $plugin_slug;
1177 1177
         }
1178 1178
         update_option(self::db_init_queue_option_name, $queue);
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
         $queue = $this->get_db_initialization_queue();
1189 1189
         foreach ($queue as $plugin_slug) {
1190 1190
             $most_up_to_date_dms = $this->get_most_up_to_date_dms($plugin_slug);
1191
-            if (! $most_up_to_date_dms) {
1191
+            if ( ! $most_up_to_date_dms) {
1192 1192
                 // if there is NO DMS for this plugin, obviously there's no schema to verify anyways
1193 1193
                 $verify_db = false;
1194 1194
             } else {
Please login to merge, or discard this patch.
core/espresso_definitions.php 2 patches
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -7,16 +7,16 @@  discard block
 block discarded – undo
7 7
 define('EE_SUPPORT_EMAIL', '[email protected]');
8 8
 // used to be DIRECTORY_SEPARATOR, but that caused issues on windows
9 9
 if (! defined('DS')) {
10
-    define('DS', '/');
10
+	define('DS', '/');
11 11
 }
12 12
 if (! defined('PS')) {
13
-    define('PS', PATH_SEPARATOR);
13
+	define('PS', PATH_SEPARATOR);
14 14
 }
15 15
 if (! defined('SP')) {
16
-    define('SP', ' ');
16
+	define('SP', ' ');
17 17
 }
18 18
 if (! defined('EENL')) {
19
-    define('EENL', "\n");
19
+	define('EENL', "\n");
20 20
 }
21 21
 // define the plugin directory and URL
22 22
 define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
@@ -70,16 +70,16 @@  discard block
 block discarded – undo
70 70
 define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
71 71
 // check for DOMPDF fonts in uploads
72 72
 if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
73
-    define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
73
+	define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
74 74
 }
75 75
 // ajax constants
76 76
 define(
77
-    'EE_FRONT_AJAX',
78
-    isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax'])
77
+	'EE_FRONT_AJAX',
78
+	isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax'])
79 79
 );
80 80
 define(
81
-    'EE_ADMIN_AJAX',
82
-    isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax'])
81
+	'EE_ADMIN_AJAX',
82
+	isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax'])
83 83
 );
84 84
 // just a handy constant occasionally needed for finding values representing infinity in the DB
85 85
 // you're better to use this than its straight value (currently -1) in case you ever
@@ -87,9 +87,9 @@  discard block
 block discarded – undo
87 87
 define('EE_INF_IN_DB', -1);
88 88
 define('EE_INF', INF > (float) PHP_INT_MAX ? INF : PHP_INT_MAX);
89 89
 if (! defined('EE_DEBUG')) {
90
-    define('EE_DEBUG', false);
90
+	define('EE_DEBUG', false);
91 91
 }
92 92
 // for older WP versions
93 93
 if (! defined('MONTH_IN_SECONDS')) {
94
-    define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
94
+	define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
95 95
 }
Please login to merge, or discard this patch.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -6,71 +6,71 @@  discard block
 block discarded – undo
6 6
 define('EE_MIN_PHP_VER_RECOMMENDED', '5.6.32');
7 7
 define('EE_SUPPORT_EMAIL', '[email protected]');
8 8
 // used to be DIRECTORY_SEPARATOR, but that caused issues on windows
9
-if (! defined('DS')) {
9
+if ( ! defined('DS')) {
10 10
     define('DS', '/');
11 11
 }
12
-if (! defined('PS')) {
12
+if ( ! defined('PS')) {
13 13
     define('PS', PATH_SEPARATOR);
14 14
 }
15
-if (! defined('SP')) {
15
+if ( ! defined('SP')) {
16 16
     define('SP', ' ');
17 17
 }
18
-if (! defined('EENL')) {
18
+if ( ! defined('EENL')) {
19 19
     define('EENL', "\n");
20 20
 }
21 21
 // define the plugin directory and URL
22 22
 define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
23
-define('EE_PLUGIN_DIR_PATH', dirname(EVENT_ESPRESSO_MAIN_FILE) . DS);
23
+define('EE_PLUGIN_DIR_PATH', dirname(EVENT_ESPRESSO_MAIN_FILE).DS);
24 24
 define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
25 25
 // main root folder paths
26
-define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
27
-define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
28
-define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
29
-define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
30
-define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
31
-define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
32
-define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
33
-define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
26
+define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH.'admin_pages'.DS);
27
+define('EE_CORE', EE_PLUGIN_DIR_PATH.'core'.DS);
28
+define('EE_MODULES', EE_PLUGIN_DIR_PATH.'modules'.DS);
29
+define('EE_PUBLIC', EE_PLUGIN_DIR_PATH.'public'.DS);
30
+define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH.'shortcodes'.DS);
31
+define('EE_WIDGETS', EE_PLUGIN_DIR_PATH.'widgets'.DS);
32
+define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH.'payment_methods'.DS);
33
+define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH.'caffeinated'.DS);
34 34
 // core system paths
35
-define('EE_ADMIN', EE_CORE . 'admin' . DS);
36
-define('EE_CPTS', EE_CORE . 'CPTs' . DS);
37
-define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
38
-define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
39
-define('EE_BUSINESS', EE_CORE . 'business' . DS);
40
-define('EE_MODELS', EE_CORE . 'db_models' . DS);
41
-define('EE_HELPERS', EE_CORE . 'helpers' . DS);
42
-define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
43
-define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
44
-define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
45
-define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
46
-define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
35
+define('EE_ADMIN', EE_CORE.'admin'.DS);
36
+define('EE_CPTS', EE_CORE.'CPTs'.DS);
37
+define('EE_CLASSES', EE_CORE.'db_classes'.DS);
38
+define('EE_INTERFACES', EE_CORE.'interfaces'.DS);
39
+define('EE_BUSINESS', EE_CORE.'business'.DS);
40
+define('EE_MODELS', EE_CORE.'db_models'.DS);
41
+define('EE_HELPERS', EE_CORE.'helpers'.DS);
42
+define('EE_LIBRARIES', EE_CORE.'libraries'.DS);
43
+define('EE_TEMPLATES', EE_CORE.'templates'.DS);
44
+define('EE_THIRD_PARTY', EE_CORE.'third_party_libs'.DS);
45
+define('EE_GLOBAL_ASSETS', EE_TEMPLATES.'global_assets'.DS);
46
+define('EE_FORM_SECTIONS', EE_LIBRARIES.'form_sections'.DS);
47 47
 // gateways
48
-define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
49
-define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
48
+define('EE_GATEWAYS', EE_MODULES.'gateways'.DS);
49
+define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL.'modules'.DS.'gateways'.DS);
50 50
 // asset URL paths
51
-define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
52
-define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
53
-define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
54
-define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
55
-define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
56
-define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
51
+define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL.'core'.DS.'templates'.DS);
52
+define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL.'global_assets'.DS);
53
+define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL.'images'.DS);
54
+define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL.'core'.DS.'third_party_libs'.DS);
55
+define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL.'core/helpers/assets/');
56
+define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL.'core/libraries/');
57 57
 // define upload paths
58 58
 $uploads = wp_upload_dir();
59 59
 // define the uploads directory and URL
60
-define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
61
-define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
60
+define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'].DS.'espresso'.DS);
61
+define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'].DS.'espresso'.DS);
62 62
 // define the templates directory and URL
63
-define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
64
-define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
63
+define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'].DS.'espresso'.DS.'templates'.DS);
64
+define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'].DS.'espresso'.DS.'templates'.DS);
65 65
 // define the gateway directory and URL
66
-define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
67
-define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
66
+define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'].DS.'espresso'.DS.'gateways'.DS);
67
+define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'].DS.'espresso'.DS.'gateways'.DS);
68 68
 // languages folder/path
69
-define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
70
-define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
69
+define('EE_LANGUAGES_SAFE_LOC', '..'.DS.'uploads'.DS.'espresso'.DS.'languages'.DS);
70
+define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR.'languages'.DS);
71 71
 // check for DOMPDF fonts in uploads
72
-if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
73
-    define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
72
+if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR.'fonts'.DS)) {
73
+    define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR.'fonts'.DS);
74 74
 }
75 75
 // ajax constants
76 76
 define(
@@ -86,10 +86,10 @@  discard block
 block discarded – undo
86 86
 // want to change its default value! or find when -1 means infinity
87 87
 define('EE_INF_IN_DB', -1);
88 88
 define('EE_INF', INF > (float) PHP_INT_MAX ? INF : PHP_INT_MAX);
89
-if (! defined('EE_DEBUG')) {
89
+if ( ! defined('EE_DEBUG')) {
90 90
     define('EE_DEBUG', false);
91 91
 }
92 92
 // for older WP versions
93
-if (! defined('MONTH_IN_SECONDS')) {
93
+if ( ! defined('MONTH_IN_SECONDS')) {
94 94
     define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
95 95
 }
Please login to merge, or discard this patch.
caffeinated/modules/recaptcha_invisible/InvisibleRecaptcha.php 2 patches
Indentation   +238 added lines, -238 removed lines patch added patch discarded remove patch
@@ -27,268 +27,268 @@
 block discarded – undo
27 27
 class InvisibleRecaptcha
28 28
 {
29 29
 
30
-    const URL_GOOGLE_RECAPTCHA_API          = 'https://www.google.com/recaptcha/api/siteverify';
30
+	const URL_GOOGLE_RECAPTCHA_API          = 'https://www.google.com/recaptcha/api/siteverify';
31 31
 
32
-    const SESSION_DATA_KEY_RECAPTCHA_PASSED = 'recaptcha_passed';
32
+	const SESSION_DATA_KEY_RECAPTCHA_PASSED = 'recaptcha_passed';
33 33
 
34
-    /**
35
-     * @var EE_Registration_Config $config
36
-     */
37
-    private $config;
34
+	/**
35
+	 * @var EE_Registration_Config $config
36
+	 */
37
+	private $config;
38 38
 
39
-    /**
40
-     * @var EE_Session $session
41
-     */
42
-    private $session;
39
+	/**
40
+	 * @var EE_Session $session
41
+	 */
42
+	private $session;
43 43
 
44
-    /**
45
-     * @var boolean $recaptcha_passed
46
-     */
47
-    private $recaptcha_passed;
44
+	/**
45
+	 * @var boolean $recaptcha_passed
46
+	 */
47
+	private $recaptcha_passed;
48 48
 
49 49
 
50
-    /**
51
-     * InvisibleRecaptcha constructor.
52
-     *
53
-     * @param EE_Registration_Config $registration_config
54
-     * @param EE_Session             $session
55
-     */
56
-    public function __construct(EE_Registration_Config $registration_config, EE_Session $session)
57
-    {
58
-        $this->config = $registration_config;
59
-        $this->session = $session;
60
-    }
50
+	/**
51
+	 * InvisibleRecaptcha constructor.
52
+	 *
53
+	 * @param EE_Registration_Config $registration_config
54
+	 * @param EE_Session             $session
55
+	 */
56
+	public function __construct(EE_Registration_Config $registration_config, EE_Session $session)
57
+	{
58
+		$this->config = $registration_config;
59
+		$this->session = $session;
60
+	}
61 61
 
62 62
 
63
-    /**
64
-     * @return boolean
65
-     */
66
-    public function useInvisibleRecaptcha()
67
-    {
68
-        return $this->config->use_captcha && $this->config->recaptcha_theme === 'invisible';
69
-    }
63
+	/**
64
+	 * @return boolean
65
+	 */
66
+	public function useInvisibleRecaptcha()
67
+	{
68
+		return $this->config->use_captcha && $this->config->recaptcha_theme === 'invisible';
69
+	}
70 70
 
71 71
 
72
-    /**
73
-     * @param array $input_settings
74
-     * @return EE_Invisible_Recaptcha_Input
75
-     * @throws InvalidDataTypeException
76
-     * @throws InvalidInterfaceException
77
-     * @throws InvalidArgumentException
78
-     * @throws DomainException
79
-     */
80
-    public function getInput(array $input_settings = array())
81
-    {
82
-        return new EE_Invisible_Recaptcha_Input(
83
-            $input_settings,
84
-            $this->config
85
-        );
86
-    }
72
+	/**
73
+	 * @param array $input_settings
74
+	 * @return EE_Invisible_Recaptcha_Input
75
+	 * @throws InvalidDataTypeException
76
+	 * @throws InvalidInterfaceException
77
+	 * @throws InvalidArgumentException
78
+	 * @throws DomainException
79
+	 */
80
+	public function getInput(array $input_settings = array())
81
+	{
82
+		return new EE_Invisible_Recaptcha_Input(
83
+			$input_settings,
84
+			$this->config
85
+		);
86
+	}
87 87
 
88 88
 
89
-    /**
90
-     * @param array $input_settings
91
-     * @return string
92
-     * @throws EE_Error
93
-     * @throws InvalidDataTypeException
94
-     * @throws InvalidInterfaceException
95
-     * @throws InvalidArgumentException
96
-     * @throws DomainException
97
-     */
98
-    public function getInputHtml(array $input_settings = array())
99
-    {
100
-        return $this->getInput($input_settings)->get_html_for_input();
101
-    }
89
+	/**
90
+	 * @param array $input_settings
91
+	 * @return string
92
+	 * @throws EE_Error
93
+	 * @throws InvalidDataTypeException
94
+	 * @throws InvalidInterfaceException
95
+	 * @throws InvalidArgumentException
96
+	 * @throws DomainException
97
+	 */
98
+	public function getInputHtml(array $input_settings = array())
99
+	{
100
+		return $this->getInput($input_settings)->get_html_for_input();
101
+	}
102 102
 
103 103
 
104
-    /**
105
-     * @param EE_Form_Section_Proper $form
106
-     * @param array                  $input_settings
107
-     * @throws EE_Error
108
-     * @throws InvalidArgumentException
109
-     * @throws InvalidDataTypeException
110
-     * @throws InvalidInterfaceException
111
-     * @throws DomainException
112
-     */
113
-    public function addToFormSection(EE_Form_Section_Proper $form, array $input_settings = array())
114
-    {
115
-        $form->add_subsections(
116
-            array(
117
-                'espresso_recaptcha' => $this->getInput($input_settings),
118
-            ),
119
-            null,
120
-            false
121
-        );
122
-    }
104
+	/**
105
+	 * @param EE_Form_Section_Proper $form
106
+	 * @param array                  $input_settings
107
+	 * @throws EE_Error
108
+	 * @throws InvalidArgumentException
109
+	 * @throws InvalidDataTypeException
110
+	 * @throws InvalidInterfaceException
111
+	 * @throws DomainException
112
+	 */
113
+	public function addToFormSection(EE_Form_Section_Proper $form, array $input_settings = array())
114
+	{
115
+		$form->add_subsections(
116
+			array(
117
+				'espresso_recaptcha' => $this->getInput($input_settings),
118
+			),
119
+			null,
120
+			false
121
+		);
122
+	}
123 123
 
124 124
 
125
-    /**
126
-     * @param RequestInterface $request
127
-     * @return boolean
128
-     * @throws InvalidArgumentException
129
-     * @throws InvalidDataTypeException
130
-     * @throws InvalidInterfaceException
131
-     * @throws RuntimeException
132
-     */
133
-    public function verifyToken(RequestInterface $request)
134
-    {
135
-        static $previous_recaptcha_response = array();
136
-        $grecaptcha_response = $request->getRequestParam('g-recaptcha-response');
137
-        // if this token has already been verified, then return previous response
138
-        if (isset($previous_recaptcha_response[ $grecaptcha_response ])) {
139
-            return $previous_recaptcha_response[ $grecaptcha_response ];
140
-        }
141
-        // still here but no g-recaptcha-response ? - verification failed
142
-        if (! $grecaptcha_response) {
143
-            EE_Error::add_error(
144
-                sprintf(
145
-                    /* translators: 1: missing parameter */
146
-                    esc_html__(
147
-                        // @codingStandardsIgnoreStart
148
-                        'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Missing "%1$s". Please try again.',
149
-                        // @codingStandardsIgnoreEnd
150
-                        'event_espresso'
151
-                    ),
152
-                    'g-recaptcha-response'
153
-                ),
154
-                __FILE__,
155
-                __FUNCTION__,
156
-                __LINE__
157
-            );
158
-            return false;
159
-        }
160
-        // will update to true if everything passes
161
-        $previous_recaptcha_response[ $grecaptcha_response ] = false;
162
-        $response                                            = wp_safe_remote_post(
163
-            InvisibleRecaptcha::URL_GOOGLE_RECAPTCHA_API,
164
-            array(
165
-                'body' => array(
166
-                    'secret'   => $this->config->recaptcha_privatekey,
167
-                    'response' => $grecaptcha_response,
168
-                    'remoteip' => $request->ipAddress(),
169
-                ),
170
-            )
171
-        );
172
-        if ($response instanceof WP_Error) {
173
-            $this->generateError($response->get_error_messages());
174
-            return false;
175
-        }
176
-        $results = json_decode(wp_remote_retrieve_body($response), true);
177
-        if (filter_var($results['success'], FILTER_VALIDATE_BOOLEAN) !== true) {
178
-            $errors   = array_map(
179
-                array($this, 'getErrorCode'),
180
-                $results['error-codes']
181
-            );
182
-            if (isset($results['challenge_ts'])) {
183
-                $errors[] = 'challenge timestamp: ' . $results['challenge_ts'] . '.';
184
-            }
185
-            $this->generateError(implode(' ', $errors), true);
186
-        }
187
-        $previous_recaptcha_response[ $grecaptcha_response ] = true;
188
-        add_action('shutdown', array($this, 'setSessionData'));
189
-        return true;
190
-    }
125
+	/**
126
+	 * @param RequestInterface $request
127
+	 * @return boolean
128
+	 * @throws InvalidArgumentException
129
+	 * @throws InvalidDataTypeException
130
+	 * @throws InvalidInterfaceException
131
+	 * @throws RuntimeException
132
+	 */
133
+	public function verifyToken(RequestInterface $request)
134
+	{
135
+		static $previous_recaptcha_response = array();
136
+		$grecaptcha_response = $request->getRequestParam('g-recaptcha-response');
137
+		// if this token has already been verified, then return previous response
138
+		if (isset($previous_recaptcha_response[ $grecaptcha_response ])) {
139
+			return $previous_recaptcha_response[ $grecaptcha_response ];
140
+		}
141
+		// still here but no g-recaptcha-response ? - verification failed
142
+		if (! $grecaptcha_response) {
143
+			EE_Error::add_error(
144
+				sprintf(
145
+					/* translators: 1: missing parameter */
146
+					esc_html__(
147
+						// @codingStandardsIgnoreStart
148
+						'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Missing "%1$s". Please try again.',
149
+						// @codingStandardsIgnoreEnd
150
+						'event_espresso'
151
+					),
152
+					'g-recaptcha-response'
153
+				),
154
+				__FILE__,
155
+				__FUNCTION__,
156
+				__LINE__
157
+			);
158
+			return false;
159
+		}
160
+		// will update to true if everything passes
161
+		$previous_recaptcha_response[ $grecaptcha_response ] = false;
162
+		$response                                            = wp_safe_remote_post(
163
+			InvisibleRecaptcha::URL_GOOGLE_RECAPTCHA_API,
164
+			array(
165
+				'body' => array(
166
+					'secret'   => $this->config->recaptcha_privatekey,
167
+					'response' => $grecaptcha_response,
168
+					'remoteip' => $request->ipAddress(),
169
+				),
170
+			)
171
+		);
172
+		if ($response instanceof WP_Error) {
173
+			$this->generateError($response->get_error_messages());
174
+			return false;
175
+		}
176
+		$results = json_decode(wp_remote_retrieve_body($response), true);
177
+		if (filter_var($results['success'], FILTER_VALIDATE_BOOLEAN) !== true) {
178
+			$errors   = array_map(
179
+				array($this, 'getErrorCode'),
180
+				$results['error-codes']
181
+			);
182
+			if (isset($results['challenge_ts'])) {
183
+				$errors[] = 'challenge timestamp: ' . $results['challenge_ts'] . '.';
184
+			}
185
+			$this->generateError(implode(' ', $errors), true);
186
+		}
187
+		$previous_recaptcha_response[ $grecaptcha_response ] = true;
188
+		add_action('shutdown', array($this, 'setSessionData'));
189
+		return true;
190
+	}
191 191
 
192 192
 
193
-    /**
194
-     * @param string $error_response
195
-     * @param bool   $show_errors
196
-     * @return void
197
-     * @throws RuntimeException
198
-     */
199
-    public function generateError($error_response = '', $show_errors = false)
200
-    {
201
-        throw new RuntimeException(
202
-            sprintf(
203
-                esc_html__(
204
-                    'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. %1$s %2$s Please try again.',
205
-                    'event_espresso'
206
-                ),
207
-                '<br />',
208
-                $show_errors || current_user_can('manage_options') ? $error_response : ''
209
-            )
210
-        );
211
-    }
193
+	/**
194
+	 * @param string $error_response
195
+	 * @param bool   $show_errors
196
+	 * @return void
197
+	 * @throws RuntimeException
198
+	 */
199
+	public function generateError($error_response = '', $show_errors = false)
200
+	{
201
+		throw new RuntimeException(
202
+			sprintf(
203
+				esc_html__(
204
+					'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. %1$s %2$s Please try again.',
205
+					'event_espresso'
206
+				),
207
+				'<br />',
208
+				$show_errors || current_user_can('manage_options') ? $error_response : ''
209
+			)
210
+		);
211
+	}
212 212
 
213 213
 
214
-    /**
215
-     * @param string $error_code
216
-     * @return string
217
-     */
218
-    public function getErrorCode(&$error_code)
219
-    {
220
-        $error_codes = array(
221
-            'missing-input-secret'   => 'The secret parameter is missing.',
222
-            'invalid-input-secret'   => 'The secret parameter is invalid or malformed.',
223
-            'missing-input-response' => 'The response parameter is missing.',
224
-            'invalid-input-response' => 'The response parameter is invalid or malformed.',
225
-            'bad-request'            => 'The request is invalid or malformed.',
226
-            'timeout-or-duplicate'   => 'The request took too long to be sent or was a duplicate of a previous request.',
227
-        );
228
-        return isset($error_codes[ $error_code ]) ? $error_codes[ $error_code ] : '';
229
-    }
214
+	/**
215
+	 * @param string $error_code
216
+	 * @return string
217
+	 */
218
+	public function getErrorCode(&$error_code)
219
+	{
220
+		$error_codes = array(
221
+			'missing-input-secret'   => 'The secret parameter is missing.',
222
+			'invalid-input-secret'   => 'The secret parameter is invalid or malformed.',
223
+			'missing-input-response' => 'The response parameter is missing.',
224
+			'invalid-input-response' => 'The response parameter is invalid or malformed.',
225
+			'bad-request'            => 'The request is invalid or malformed.',
226
+			'timeout-or-duplicate'   => 'The request took too long to be sent or was a duplicate of a previous request.',
227
+		);
228
+		return isset($error_codes[ $error_code ]) ? $error_codes[ $error_code ] : '';
229
+	}
230 230
 
231 231
 
232
-    /**
233
-     * @return array
234
-     * @throws InvalidInterfaceException
235
-     * @throws InvalidDataTypeException
236
-     * @throws InvalidArgumentException
237
-     */
238
-    public function getLocalizedVars()
239
-    {
240
-        return (array) apply_filters(
241
-            'FHEE__EventEspresso_caffeinated_modules_recaptcha_invisible_InvisibleRecaptcha__getLocalizedVars__localized_vars',
242
-            array(
243
-                'siteKey'          => $this->config->recaptcha_publickey,
244
-                'recaptcha_passed' => $this->recaptchaPassed(),
245
-                'wp_debug'         => WP_DEBUG,
246
-                'disable_submit'   => defined('EE_EVENT_QUEUE_BASE_URL'),
247
-                'failed_message'   => esc_html__(
248
-                    'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Please try again.',
249
-                    'event_espresso'
250
-                )
251
-            )
252
-        );
253
-    }
232
+	/**
233
+	 * @return array
234
+	 * @throws InvalidInterfaceException
235
+	 * @throws InvalidDataTypeException
236
+	 * @throws InvalidArgumentException
237
+	 */
238
+	public function getLocalizedVars()
239
+	{
240
+		return (array) apply_filters(
241
+			'FHEE__EventEspresso_caffeinated_modules_recaptcha_invisible_InvisibleRecaptcha__getLocalizedVars__localized_vars',
242
+			array(
243
+				'siteKey'          => $this->config->recaptcha_publickey,
244
+				'recaptcha_passed' => $this->recaptchaPassed(),
245
+				'wp_debug'         => WP_DEBUG,
246
+				'disable_submit'   => defined('EE_EVENT_QUEUE_BASE_URL'),
247
+				'failed_message'   => esc_html__(
248
+					'We\'re sorry but an attempt to verify the form\'s reCAPTCHA has failed. Please try again.',
249
+					'event_espresso'
250
+				)
251
+			)
252
+		);
253
+	}
254 254
 
255 255
 
256
-    /**
257
-     * @return boolean
258
-     * @throws InvalidInterfaceException
259
-     * @throws InvalidDataTypeException
260
-     * @throws InvalidArgumentException
261
-     */
262
-    public function recaptchaPassed()
263
-    {
264
-        if ($this->recaptcha_passed !== null) {
265
-            return $this->recaptcha_passed;
266
-        }
267
-        // logged in means you have already passed a turing test of sorts
268
-        if ($this->useInvisibleRecaptcha() === false || is_user_logged_in()) {
269
-            $this->recaptcha_passed = true;
270
-            return $this->recaptcha_passed;
271
-        }
272
-        // was test already passed?
273
-        $this->recaptcha_passed = filter_var(
274
-            $this->session->get_session_data(
275
-                InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED
276
-            ),
277
-            FILTER_VALIDATE_BOOLEAN
278
-        );
279
-        return $this->recaptcha_passed;
280
-    }
256
+	/**
257
+	 * @return boolean
258
+	 * @throws InvalidInterfaceException
259
+	 * @throws InvalidDataTypeException
260
+	 * @throws InvalidArgumentException
261
+	 */
262
+	public function recaptchaPassed()
263
+	{
264
+		if ($this->recaptcha_passed !== null) {
265
+			return $this->recaptcha_passed;
266
+		}
267
+		// logged in means you have already passed a turing test of sorts
268
+		if ($this->useInvisibleRecaptcha() === false || is_user_logged_in()) {
269
+			$this->recaptcha_passed = true;
270
+			return $this->recaptcha_passed;
271
+		}
272
+		// was test already passed?
273
+		$this->recaptcha_passed = filter_var(
274
+			$this->session->get_session_data(
275
+				InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED
276
+			),
277
+			FILTER_VALIDATE_BOOLEAN
278
+		);
279
+		return $this->recaptcha_passed;
280
+	}
281 281
 
282 282
 
283
-    /**
284
-     * @throws InvalidArgumentException
285
-     * @throws InvalidDataTypeException
286
-     * @throws InvalidInterfaceException
287
-     */
288
-    public function setSessionData()
289
-    {
290
-        $this->session->set_session_data(
291
-            array(InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED => true)
292
-        );
293
-    }
283
+	/**
284
+	 * @throws InvalidArgumentException
285
+	 * @throws InvalidDataTypeException
286
+	 * @throws InvalidInterfaceException
287
+	 */
288
+	public function setSessionData()
289
+	{
290
+		$this->session->set_session_data(
291
+			array(InvisibleRecaptcha::SESSION_DATA_KEY_RECAPTCHA_PASSED => true)
292
+		);
293
+	}
294 294
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -135,11 +135,11 @@  discard block
 block discarded – undo
135 135
         static $previous_recaptcha_response = array();
136 136
         $grecaptcha_response = $request->getRequestParam('g-recaptcha-response');
137 137
         // if this token has already been verified, then return previous response
138
-        if (isset($previous_recaptcha_response[ $grecaptcha_response ])) {
139
-            return $previous_recaptcha_response[ $grecaptcha_response ];
138
+        if (isset($previous_recaptcha_response[$grecaptcha_response])) {
139
+            return $previous_recaptcha_response[$grecaptcha_response];
140 140
         }
141 141
         // still here but no g-recaptcha-response ? - verification failed
142
-        if (! $grecaptcha_response) {
142
+        if ( ! $grecaptcha_response) {
143 143
             EE_Error::add_error(
144 144
                 sprintf(
145 145
                     /* translators: 1: missing parameter */
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
             return false;
159 159
         }
160 160
         // will update to true if everything passes
161
-        $previous_recaptcha_response[ $grecaptcha_response ] = false;
161
+        $previous_recaptcha_response[$grecaptcha_response] = false;
162 162
         $response                                            = wp_safe_remote_post(
163 163
             InvisibleRecaptcha::URL_GOOGLE_RECAPTCHA_API,
164 164
             array(
@@ -175,16 +175,16 @@  discard block
 block discarded – undo
175 175
         }
176 176
         $results = json_decode(wp_remote_retrieve_body($response), true);
177 177
         if (filter_var($results['success'], FILTER_VALIDATE_BOOLEAN) !== true) {
178
-            $errors   = array_map(
178
+            $errors = array_map(
179 179
                 array($this, 'getErrorCode'),
180 180
                 $results['error-codes']
181 181
             );
182 182
             if (isset($results['challenge_ts'])) {
183
-                $errors[] = 'challenge timestamp: ' . $results['challenge_ts'] . '.';
183
+                $errors[] = 'challenge timestamp: '.$results['challenge_ts'].'.';
184 184
             }
185 185
             $this->generateError(implode(' ', $errors), true);
186 186
         }
187
-        $previous_recaptcha_response[ $grecaptcha_response ] = true;
187
+        $previous_recaptcha_response[$grecaptcha_response] = true;
188 188
         add_action('shutdown', array($this, 'setSessionData'));
189 189
         return true;
190 190
     }
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
             'bad-request'            => 'The request is invalid or malformed.',
226 226
             'timeout-or-duplicate'   => 'The request took too long to be sent or was a duplicate of a previous request.',
227 227
         );
228
-        return isset($error_codes[ $error_code ]) ? $error_codes[ $error_code ] : '';
228
+        return isset($error_codes[$error_code]) ? $error_codes[$error_code] : '';
229 229
     }
230 230
 
231 231
 
Please login to merge, or discard this patch.
4_5_0_stages/EE_DMS_4_5_0_invoice_settings.dmsstage.php 2 patches
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -52,11 +52,11 @@  discard block
 block discarded – undo
52 52
     protected function _migration_step($num_items = 1)
53 53
     {
54 54
         // if this isn't set then something is really wrong
55
-        if (! EE_Config::instance()->gateway instanceof EE_Gateway_Config) {
55
+        if ( ! EE_Config::instance()->gateway instanceof EE_Gateway_Config) {
56 56
             throw new EE_Error(__('It appears the Event Espresso Core Configuration is not setup correctly.', 'event_espresso'));
57 57
         }
58 58
         $invoice_settings = isset(EE_Config::instance()->gateway->payment_settings['Invoice']) ? EE_Config::instance()->gateway->payment_settings['Invoice'] : null;
59
-        if (! $invoice_settings) {
59
+        if ( ! $invoice_settings) {
60 60
             $this->add_error(__('Could not migrate EE4.4 invoice settings to EE4.5 because they didnt exist', 'event_espresso'));
61 61
         } else {
62 62
             $invoice_settings['template_payment_instructions'] = $invoice_settings['pdf_instructions'];
@@ -89,8 +89,8 @@  discard block
 block discarded – undo
89 89
                 );
90 90
             }
91 91
             $templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
92
-            $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
93
-            $overridden_receipt_body= EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
92
+            $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path.'invoice_body.template.php', null, false, false, true);
93
+            $overridden_receipt_body = EEH_Template::locate_template($templates_relative_path.'receipt_body.template.php', null, false, false, true);
94 94
             if ($overridden_invoice_body || $overridden_receipt_body) {
95 95
                 new PersistentAdminNotice(
96 96
                     'invoice_overriding_templates',
Please login to merge, or discard this patch.
Indentation   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -15,95 +15,95 @@
 block discarded – undo
15 15
 class EE_DMS_4_5_0_invoice_settings extends EE_Data_Migration_Script_Stage
16 16
 {
17 17
 
18
-    /**
19
-     * Just initializes the status of the migration
20
-     */
21
-    public function __construct()
22
-    {
23
-        $this->_pretty_name = __('Update Invoice Gateway Settings', 'event_espresso');
24
-        parent::__construct();
25
-    }
18
+	/**
19
+	 * Just initializes the status of the migration
20
+	 */
21
+	public function __construct()
22
+	{
23
+		$this->_pretty_name = __('Update Invoice Gateway Settings', 'event_espresso');
24
+		parent::__construct();
25
+	}
26 26
 
27 27
 
28 28
 
29
-    /**
30
-     * _count_records_to_migrate
31
-     * Counts the records to migrate; the public version may cache it
32
-     *
33
-     * @access protected
34
-     * @return int
35
-     */
36
-    protected function _count_records_to_migrate()
37
-    {
38
-        return 1;
39
-    }
29
+	/**
30
+	 * _count_records_to_migrate
31
+	 * Counts the records to migrate; the public version may cache it
32
+	 *
33
+	 * @access protected
34
+	 * @return int
35
+	 */
36
+	protected function _count_records_to_migrate()
37
+	{
38
+		return 1;
39
+	}
40 40
 
41 41
 
42 42
 
43
-    /**
44
-     *    _migration_step
45
-     *
46
-     * @access protected
47
-     * @param int $num_items
48
-     * @throws EE_Error
49
-     * @return int number of items ACTUALLY migrated
50
-     * @throws InvalidDataTypeException
51
-     */
52
-    protected function _migration_step($num_items = 1)
53
-    {
54
-        // if this isn't set then something is really wrong
55
-        if (! EE_Config::instance()->gateway instanceof EE_Gateway_Config) {
56
-            throw new EE_Error(__('It appears the Event Espresso Core Configuration is not setup correctly.', 'event_espresso'));
57
-        }
58
-        $invoice_settings = isset(EE_Config::instance()->gateway->payment_settings['Invoice']) ? EE_Config::instance()->gateway->payment_settings['Invoice'] : null;
59
-        if (! $invoice_settings) {
60
-            $this->add_error(__('Could not migrate EE4.4 invoice settings to EE4.5 because they didnt exist', 'event_espresso'));
61
-        } else {
62
-            $invoice_settings['template_payment_instructions'] = $invoice_settings['pdf_instructions'];
63
-            $invoice_settings['template_invoice_payee_name'] = $invoice_settings['payable_to'];
64
-            $invoice_settings['template_invoice_address'] = $invoice_settings['payment_address'];
65
-            $invoice_settings['template_invoice_email'] = '';
66
-            $invoice_settings['template_invoice_tax_number'] = '';
67
-            unset($invoice_settings['pdf_instructions']);
68
-            unset($invoice_settings['payable_to']);
69
-            unset($invoice_settings['payment_address']);
70
-            EE_Config::instance()->gateway->payment_settings['Invoice'] = $invoice_settings;
71
-            EE_Config::instance()->update_espresso_config(false, false);
43
+	/**
44
+	 *    _migration_step
45
+	 *
46
+	 * @access protected
47
+	 * @param int $num_items
48
+	 * @throws EE_Error
49
+	 * @return int number of items ACTUALLY migrated
50
+	 * @throws InvalidDataTypeException
51
+	 */
52
+	protected function _migration_step($num_items = 1)
53
+	{
54
+		// if this isn't set then something is really wrong
55
+		if (! EE_Config::instance()->gateway instanceof EE_Gateway_Config) {
56
+			throw new EE_Error(__('It appears the Event Espresso Core Configuration is not setup correctly.', 'event_espresso'));
57
+		}
58
+		$invoice_settings = isset(EE_Config::instance()->gateway->payment_settings['Invoice']) ? EE_Config::instance()->gateway->payment_settings['Invoice'] : null;
59
+		if (! $invoice_settings) {
60
+			$this->add_error(__('Could not migrate EE4.4 invoice settings to EE4.5 because they didnt exist', 'event_espresso'));
61
+		} else {
62
+			$invoice_settings['template_payment_instructions'] = $invoice_settings['pdf_instructions'];
63
+			$invoice_settings['template_invoice_payee_name'] = $invoice_settings['payable_to'];
64
+			$invoice_settings['template_invoice_address'] = $invoice_settings['payment_address'];
65
+			$invoice_settings['template_invoice_email'] = '';
66
+			$invoice_settings['template_invoice_tax_number'] = '';
67
+			unset($invoice_settings['pdf_instructions']);
68
+			unset($invoice_settings['payable_to']);
69
+			unset($invoice_settings['payment_address']);
70
+			EE_Config::instance()->gateway->payment_settings['Invoice'] = $invoice_settings;
71
+			EE_Config::instance()->update_espresso_config(false, false);
72 72
 
73
-            // @todo: check 'invoice_css' too because we can't easily affect that so we might need to set a persistent notice
74
-            // (why is it tough to change? because we want to update the receipt and invoice message template, but
75
-            // message templates are only initialized AFTER migrations and those two are new in 4.5. So if we wanted to
76
-            // update them from a DMS, we'd need to have the DMS create the message templates which is quite a lot of code;
77
-            // also we don't want to build a dependency on the messages code because it is likely to change soon
78
-            if (isset($invoice_settings['invoice_css'])
79
-                && ! in_array($invoice_settings['invoice_css'], ['', 'simple.css'])) {
80
-                new PersistentAdminNotice(
81
-                    'invoice_css_not_updated',
82
-                    sprintf(
83
-                        esc_html__(
84
-                            'You had previously set your Invoice Payment Method\'s stylesheet to be %1$s, but that setting has moved. PDF and HTML Invoices and Receipts are now Messages, which means you can easily modify them from your Wordpress Dashboard instead of using filters or uploading template files. Please visit Messages -> Receipt and Messages -> Invoice to change their stylesheets.',
85
-                            'event_espresso'
86
-                        ),
87
-                        $invoice_settings['invoice_css']
88
-                    )
89
-                );
90
-            }
91
-            $templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
92
-            $overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
93
-            $overridden_receipt_body= EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
94
-            if ($overridden_invoice_body || $overridden_receipt_body) {
95
-                new PersistentAdminNotice(
96
-                    'invoice_overriding_templates',
97
-                    esc_html__(
98
-                        'Note: in this version of Event Espresso, PDF and HTML Invoices and Receipts are now Messages and can be changed just like any other messages; however we noticed you had previously overridden the old default Invoice/Receipt templates. Because of this, your old Invoice/Receipt templates will continue to be used INSTEAD of the new Invoice/Receipt message equivalents. We recommend deleting your old Invoice/Receipt templates and modifying the new Invoice and Receipt messages\'s content in Messages -> Invoice and Messages -> Receipt.',
99
-                        'event_espresso'
100
-                    ),
101
-                    true
102
-                );
103
-            }
104
-        }
105
-        // regardless of whether it worked or not, we ought to continue the migration
106
-        $this->set_completed();
107
-        return 1;
108
-    }
73
+			// @todo: check 'invoice_css' too because we can't easily affect that so we might need to set a persistent notice
74
+			// (why is it tough to change? because we want to update the receipt and invoice message template, but
75
+			// message templates are only initialized AFTER migrations and those two are new in 4.5. So if we wanted to
76
+			// update them from a DMS, we'd need to have the DMS create the message templates which is quite a lot of code;
77
+			// also we don't want to build a dependency on the messages code because it is likely to change soon
78
+			if (isset($invoice_settings['invoice_css'])
79
+				&& ! in_array($invoice_settings['invoice_css'], ['', 'simple.css'])) {
80
+				new PersistentAdminNotice(
81
+					'invoice_css_not_updated',
82
+					sprintf(
83
+						esc_html__(
84
+							'You had previously set your Invoice Payment Method\'s stylesheet to be %1$s, but that setting has moved. PDF and HTML Invoices and Receipts are now Messages, which means you can easily modify them from your Wordpress Dashboard instead of using filters or uploading template files. Please visit Messages -> Receipt and Messages -> Invoice to change their stylesheets.',
85
+							'event_espresso'
86
+						),
87
+						$invoice_settings['invoice_css']
88
+					)
89
+				);
90
+			}
91
+			$templates_relative_path = 'modules/gateways/Invoice/lib/templates/';
92
+			$overridden_invoice_body = EEH_Template::locate_template($templates_relative_path . 'invoice_body.template.php', null, false, false, true);
93
+			$overridden_receipt_body= EEH_Template::locate_template($templates_relative_path . 'receipt_body.template.php', null, false, false, true);
94
+			if ($overridden_invoice_body || $overridden_receipt_body) {
95
+				new PersistentAdminNotice(
96
+					'invoice_overriding_templates',
97
+					esc_html__(
98
+						'Note: in this version of Event Espresso, PDF and HTML Invoices and Receipts are now Messages and can be changed just like any other messages; however we noticed you had previously overridden the old default Invoice/Receipt templates. Because of this, your old Invoice/Receipt templates will continue to be used INSTEAD of the new Invoice/Receipt message equivalents. We recommend deleting your old Invoice/Receipt templates and modifying the new Invoice and Receipt messages\'s content in Messages -> Invoice and Messages -> Receipt.',
99
+						'event_espresso'
100
+					),
101
+					true
102
+				);
103
+			}
104
+		}
105
+		// regardless of whether it worked or not, we ought to continue the migration
106
+		$this->set_completed();
107
+		return 1;
108
+	}
109 109
 }
Please login to merge, or discard this patch.
core/data_migration_scripts/4_1_0_stages/EE_DMS_4_1_0_prices.dmsstage.php 2 patches
Indentation   +292 added lines, -292 removed lines patch added patch discarded remove patch
@@ -87,57 +87,57 @@  discard block
 block discarded – undo
87 87
  */
88 88
 class EE_DMS_4_1_0_prices extends EE_Data_Migration_Script_Stage_Table
89 89
 {
90
-    private $_new_price_table;
91
-    private $_new_ticket_table;
92
-    private $_new_ticket_price_table;
93
-    private $_new_datetime_ticket_table;
94
-    /**
95
-     * A count of all the different tickets created, used for setting the new ones' TKT_Order
96
-     * @var int
97
-     */
98
-    private $_ticket_count = 0;
99
-    const price_type_base = 1;
100
-    const price_type_member_discount = 3;
101
-    const price_type_percent_surcharge = 4;
102
-    const price_type_flat_surcharge = 5;
90
+	private $_new_price_table;
91
+	private $_new_ticket_table;
92
+	private $_new_ticket_price_table;
93
+	private $_new_datetime_ticket_table;
94
+	/**
95
+	 * A count of all the different tickets created, used for setting the new ones' TKT_Order
96
+	 * @var int
97
+	 */
98
+	private $_ticket_count = 0;
99
+	const price_type_base = 1;
100
+	const price_type_member_discount = 3;
101
+	const price_type_percent_surcharge = 4;
102
+	const price_type_flat_surcharge = 5;
103 103
 
104
-    public function __construct()
105
-    {
106
-        global $wpdb;
107
-        $this->_pretty_name = __("Prices", "event_espresso");
108
-        $this->_old_table = $wpdb->prefix."events_prices";
109
-        $this->select_expression = 'p.*, e.event_status';
110
-        $this->_extra_where_sql = ' AS p 
104
+	public function __construct()
105
+	{
106
+		global $wpdb;
107
+		$this->_pretty_name = __("Prices", "event_espresso");
108
+		$this->_old_table = $wpdb->prefix."events_prices";
109
+		$this->select_expression = 'p.*, e.event_status';
110
+		$this->_extra_where_sql = ' AS p 
111 111
             INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON p.event_id=e.id
112 112
             WHERE e.event_status!="D"';
113
-        $this->_new_price_table = $wpdb->prefix."esp_price";
114
-        $this->_new_ticket_table = $wpdb->prefix."esp_ticket";
115
-        $this->_new_ticket_price_table = $wpdb->prefix."esp_ticket_price";
116
-        $this->_new_datetime_ticket_table = $wpdb->prefix."esp_datetime_ticket";
117
-        parent::__construct();
118
-    }
119
-    protected function _migrate_old_row($old_row)
120
-    {
121
-        // create the base price
122
-        $new_price_id = $this->_insert_new_price($old_row);
123
-        // create the member discount if there is any
124
-        // commented-out because we may actually NOT be supporting this in 4.1
113
+		$this->_new_price_table = $wpdb->prefix."esp_price";
114
+		$this->_new_ticket_table = $wpdb->prefix."esp_ticket";
115
+		$this->_new_ticket_price_table = $wpdb->prefix."esp_ticket_price";
116
+		$this->_new_datetime_ticket_table = $wpdb->prefix."esp_datetime_ticket";
117
+		parent::__construct();
118
+	}
119
+	protected function _migrate_old_row($old_row)
120
+	{
121
+		// create the base price
122
+		$new_price_id = $this->_insert_new_price($old_row);
123
+		// create the member discount if there is any
124
+		// commented-out because we may actually NOT be supporting this in 4.1
125 125
 //      if($old_row['event_cost'] != $old_row['member_price']){
126 126
 //          $member_price_discount_id = $this->_insert_new_member_price($old_row);
127 127
 //      }else{
128 128
 //          $member_price_discount_id = 0;
129 129
 //      }
130
-        // create the surcharge if there is any
131
-        if (floatval($old_row['surcharge']) >= 0.01) {
132
-            $surcharge_price_id = $this->_insert_new_surcharge_price($old_row);
133
-            $this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_price_table, array($new_price_id,$surcharge_price_id));
134
-        } else {
135
-            $surcharge_price_id = 0;
136
-            $this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_price_table, array($new_price_id));
137
-        }
138
-        // associate the ticket to all datetimes for event (ie, this ONE ticket grants access to ALL datetimes, not just one of the attendee's choice.
139
-        // if the latter were the case, then we'd create a separate ticket for each datetime and ahve their association be one-to-one)
140
-        // create ticket
130
+		// create the surcharge if there is any
131
+		if (floatval($old_row['surcharge']) >= 0.01) {
132
+			$surcharge_price_id = $this->_insert_new_surcharge_price($old_row);
133
+			$this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_price_table, array($new_price_id,$surcharge_price_id));
134
+		} else {
135
+			$surcharge_price_id = 0;
136
+			$this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_price_table, array($new_price_id));
137
+		}
138
+		// associate the ticket to all datetimes for event (ie, this ONE ticket grants access to ALL datetimes, not just one of the attendee's choice.
139
+		// if the latter were the case, then we'd create a separate ticket for each datetime and ahve their association be one-to-one)
140
+		// create ticket
141 141
 //      $ticket_id = $this->_insert_new_ticket($old_row);
142 142
 //      if($ticket_id){
143 143
 //          $this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_ticket_table, $ticket_id);
@@ -149,62 +149,62 @@  discard block
 block discarded – undo
149 149
 //              $this->_insert_datetime_ticket_relation($new_datetime_id, $ticket_id);
150 150
 //          }
151 151
 //      }
152
-        // create a ticket for each old price -old datetime combo
153
-        $tickets_for_old_price = array();
154
-        foreach ($this->_get_datetime_ids_for_old_event_id($old_row['event_id']) as $new_datetime_id) {
155
-            $ticket_id = $this->_insert_new_ticket($old_row);
156
-            $tickets_for_old_price[] = $ticket_id;
157
-            // associate to old prices
158
-            $this->_insert_ticket_price_relation($ticket_id, $new_price_id);
159
-            $this->_insert_ticket_price_relation($ticket_id, $surcharge_price_id);
160
-            $this->_insert_datetime_ticket_relation($new_datetime_id, $ticket_id);
161
-        }
162
-        $this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_ticket_table, $tickets_for_old_price);
163
-    }
164
-    /**
165
-     * Creates a 4.1 price base type
166
-     * @global type $wpdb
167
-     * @param type $old_price
168
-     * @return int
169
-     */
170
-    private function _insert_new_price($old_price)
171
-    {
172
-        global $wpdb;
173
-        $cols_n_values = array(
174
-            'PRT_ID'=>self::price_type_base,
175
-            'PRC_amount'=>floatval($old_price['event_cost']),
176
-            'PRC_name'=>$old_price['price_type'],
177
-            'PRC_is_default'=>false,
178
-            'PRC_overrides'=>false,
179
-            'PRC_order'=>0,
180
-            'PRC_deleted'=>false,
181
-            'PRC_parent'=>null
152
+		// create a ticket for each old price -old datetime combo
153
+		$tickets_for_old_price = array();
154
+		foreach ($this->_get_datetime_ids_for_old_event_id($old_row['event_id']) as $new_datetime_id) {
155
+			$ticket_id = $this->_insert_new_ticket($old_row);
156
+			$tickets_for_old_price[] = $ticket_id;
157
+			// associate to old prices
158
+			$this->_insert_ticket_price_relation($ticket_id, $new_price_id);
159
+			$this->_insert_ticket_price_relation($ticket_id, $surcharge_price_id);
160
+			$this->_insert_datetime_ticket_relation($new_datetime_id, $ticket_id);
161
+		}
162
+		$this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_ticket_table, $tickets_for_old_price);
163
+	}
164
+	/**
165
+	 * Creates a 4.1 price base type
166
+	 * @global type $wpdb
167
+	 * @param type $old_price
168
+	 * @return int
169
+	 */
170
+	private function _insert_new_price($old_price)
171
+	{
172
+		global $wpdb;
173
+		$cols_n_values = array(
174
+			'PRT_ID'=>self::price_type_base,
175
+			'PRC_amount'=>floatval($old_price['event_cost']),
176
+			'PRC_name'=>$old_price['price_type'],
177
+			'PRC_is_default'=>false,
178
+			'PRC_overrides'=>false,
179
+			'PRC_order'=>0,
180
+			'PRC_deleted'=>false,
181
+			'PRC_parent'=>null
182 182
 
183
-        );
184
-        $datatypes = array(
185
-            '%d',// PRT_ID
186
-            '%f',// PRT_amount
187
-            '%s',// PRC_name
188
-            '%d',// PRC_is_default
189
-            '%d',// PRC_overrides
190
-            '%d',// PRC_order
191
-            '%d',// PRC_deleted
192
-            '%d',// PRC_parent
193
-        );
194
-        $success = $wpdb->insert($this->_new_price_table, $cols_n_values, $datatypes);
195
-        if (! $success) {
196
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price, $this->_new_price_table, $cols_n_values, $datatypes));
197
-            return 0;
198
-        }
199
-        $new_id = $wpdb->insert_id;
200
-        return $new_id;
201
-    }
202
-    /**
203
-     * Creates a 4.1 member price discount
204
-     * @global type $wpdb
205
-     * @param type $old_price
206
-     * @return int
207
-     */
183
+		);
184
+		$datatypes = array(
185
+			'%d',// PRT_ID
186
+			'%f',// PRT_amount
187
+			'%s',// PRC_name
188
+			'%d',// PRC_is_default
189
+			'%d',// PRC_overrides
190
+			'%d',// PRC_order
191
+			'%d',// PRC_deleted
192
+			'%d',// PRC_parent
193
+		);
194
+		$success = $wpdb->insert($this->_new_price_table, $cols_n_values, $datatypes);
195
+		if (! $success) {
196
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price, $this->_new_price_table, $cols_n_values, $datatypes));
197
+			return 0;
198
+		}
199
+		$new_id = $wpdb->insert_id;
200
+		return $new_id;
201
+	}
202
+	/**
203
+	 * Creates a 4.1 member price discount
204
+	 * @global type $wpdb
205
+	 * @param type $old_price
206
+	 * @return int
207
+	 */
208 208
 //  private function _insert_new_member_price($old_price){
209 209
 //      $discount_amount = floatval($old_price['event_cost']) - floatval($old_price['member_price']);
210 210
 //      global $wpdb;
@@ -237,207 +237,207 @@  discard block
 block discarded – undo
237 237
 //      $new_id = $wpdb->insert_id;
238 238
 //      return $new_id;
239 239
 //  }
240
-    /**
241
-     * Creates a 4.1 member price discount
242
-     * @global type $wpdb
243
-     * @param type $old_price
244
-     * @return int
245
-     */
246
-    private function _insert_new_surcharge_price($old_price)
247
-    {
240
+	/**
241
+	 * Creates a 4.1 member price discount
242
+	 * @global type $wpdb
243
+	 * @param type $old_price
244
+	 * @return int
245
+	 */
246
+	private function _insert_new_surcharge_price($old_price)
247
+	{
248 248
 
249
-        if ($old_price['surcharge_type'] == 'flat_rate') {
250
-            $price_type = self::price_type_flat_surcharge;
251
-        } else {
252
-            $price_type = self::price_type_percent_surcharge;
253
-        }
254
-        global $wpdb;
255
-        $cols_n_values = array(
256
-            'PRT_ID'=>$price_type,
257
-            'PRC_amount'=>floatval($old_price['surcharge']),
258
-            'PRC_name'=>  __("Surcharge", "event_espresso"),
259
-            'PRC_is_default'=>false,
260
-            'PRC_overrides'=>false,
261
-            'PRC_order'=>20,
262
-            'PRC_deleted'=>false,
263
-            'PRC_parent'=>null
249
+		if ($old_price['surcharge_type'] == 'flat_rate') {
250
+			$price_type = self::price_type_flat_surcharge;
251
+		} else {
252
+			$price_type = self::price_type_percent_surcharge;
253
+		}
254
+		global $wpdb;
255
+		$cols_n_values = array(
256
+			'PRT_ID'=>$price_type,
257
+			'PRC_amount'=>floatval($old_price['surcharge']),
258
+			'PRC_name'=>  __("Surcharge", "event_espresso"),
259
+			'PRC_is_default'=>false,
260
+			'PRC_overrides'=>false,
261
+			'PRC_order'=>20,
262
+			'PRC_deleted'=>false,
263
+			'PRC_parent'=>null
264 264
 
265
-        );
266
-        $datatypes = array(
267
-            '%d',// PRT_ID
268
-            '%f',// PRT_amount
269
-            '%s',// PRC_name
270
-            '%d',// PRC_is_default
271
-            '%d',// PRC_overrides
272
-            '%d',// PRC_order
273
-            '%d',// PRC_deleted
274
-            '%d',// PRC_parent
275
-        );
276
-        $success = $wpdb->insert($this->_new_price_table, $cols_n_values, $datatypes);
277
-        if (! $success) {
278
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price, $this->_new_price_table, $cols_n_values, $datatypes));
279
-            return 0;
280
-        }
281
-        $new_id = $wpdb->insert_id;
282
-        return $new_id;
283
-    }
284
-    /**
285
-     * Inserts a 4.1 ticket based off the 3.1 price, and the price IDs we've already made from the 3.1 price
286
-     * @param $old_price_row array where keys are columns
287
-     * @param $new_base_price_id int
288
-     * @param $new_member_discount_id int
289
-     * @param $new_surcharge_id int
290
-     * @return int new ticket id
291
-     */
292
-    private function _insert_new_ticket($old_price_row)
293
-    {
294
-        global $wpdb;
295
-        $event_row = $this->_get_event_row($old_price_row['event_id']);
296
-        if ($old_price_row['surcharge_type'] == 'flat_rate') {
297
-            $final_ticket_price = floatval($old_price_row['event_cost']) + floatval($old_price_row['surcharge']);
298
-        } else {// percent surcharge
299
-            $final_ticket_price = floatval($old_price_row['event_cost']) * (1 + floatval($old_price_row['surcharge'])/100);
300
-        }
301
-        $start_date = $event_row['registration_start']." ".$this->get_migration_script()->convertTimeFromAMPM($event_row['registration_startT']);
302
-        $start_date_utc = $this->get_migration_script()->convert_date_string_to_utc($this, $old_price_row, $start_date, $event_row['timezone_string']);
303
-        $end_date = $event_row['registration_end']." ".$this->get_migration_script()->convertTimeFromAMPM($event_row['registration_endT']);
304
-        $end_date_utc = $this->get_migration_script()->convert_date_string_to_utc($this, $old_price_row, $end_date, $event_row['timezone_string']);
305
-        $cols_n_values = array(
306
-            'TTM_ID'=>0,
307
-            'TKT_name'=>$old_price_row['price_type'],
308
-            'TKT_description'=>'',
309
-            'TKT_start_date'=>$start_date_utc,
310
-            'TKT_end_date'=>$end_date_utc,
311
-            'TKT_min'=>0,
312
-            'TKT_max'=>-1,
313
-            'TKT_price'=>$final_ticket_price,
314
-            'TKT_sold'=> 0,// note: this will get calculated as we actually add registrations during the migration
315
-            'TKT_qty'=> -1,
316
-            'TKT_uses'=> 1,
317
-            'TKT_taxable'=>false,// so by default, old prices are NOT taxable. This way they don't suddenly have a sudden spike in prices
318
-            'TKT_is_default'=>false,
319
-            'TKT_order'=>$this->_get_ticket_count(),
320
-            'TKT_row'=>0,// doesn't matter because UI reset this on first save anyways
321
-            'TKT_deleted'=>false,
322
-            'TKT_parent'=>0
265
+		);
266
+		$datatypes = array(
267
+			'%d',// PRT_ID
268
+			'%f',// PRT_amount
269
+			'%s',// PRC_name
270
+			'%d',// PRC_is_default
271
+			'%d',// PRC_overrides
272
+			'%d',// PRC_order
273
+			'%d',// PRC_deleted
274
+			'%d',// PRC_parent
275
+		);
276
+		$success = $wpdb->insert($this->_new_price_table, $cols_n_values, $datatypes);
277
+		if (! $success) {
278
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price, $this->_new_price_table, $cols_n_values, $datatypes));
279
+			return 0;
280
+		}
281
+		$new_id = $wpdb->insert_id;
282
+		return $new_id;
283
+	}
284
+	/**
285
+	 * Inserts a 4.1 ticket based off the 3.1 price, and the price IDs we've already made from the 3.1 price
286
+	 * @param $old_price_row array where keys are columns
287
+	 * @param $new_base_price_id int
288
+	 * @param $new_member_discount_id int
289
+	 * @param $new_surcharge_id int
290
+	 * @return int new ticket id
291
+	 */
292
+	private function _insert_new_ticket($old_price_row)
293
+	{
294
+		global $wpdb;
295
+		$event_row = $this->_get_event_row($old_price_row['event_id']);
296
+		if ($old_price_row['surcharge_type'] == 'flat_rate') {
297
+			$final_ticket_price = floatval($old_price_row['event_cost']) + floatval($old_price_row['surcharge']);
298
+		} else {// percent surcharge
299
+			$final_ticket_price = floatval($old_price_row['event_cost']) * (1 + floatval($old_price_row['surcharge'])/100);
300
+		}
301
+		$start_date = $event_row['registration_start']." ".$this->get_migration_script()->convertTimeFromAMPM($event_row['registration_startT']);
302
+		$start_date_utc = $this->get_migration_script()->convert_date_string_to_utc($this, $old_price_row, $start_date, $event_row['timezone_string']);
303
+		$end_date = $event_row['registration_end']." ".$this->get_migration_script()->convertTimeFromAMPM($event_row['registration_endT']);
304
+		$end_date_utc = $this->get_migration_script()->convert_date_string_to_utc($this, $old_price_row, $end_date, $event_row['timezone_string']);
305
+		$cols_n_values = array(
306
+			'TTM_ID'=>0,
307
+			'TKT_name'=>$old_price_row['price_type'],
308
+			'TKT_description'=>'',
309
+			'TKT_start_date'=>$start_date_utc,
310
+			'TKT_end_date'=>$end_date_utc,
311
+			'TKT_min'=>0,
312
+			'TKT_max'=>-1,
313
+			'TKT_price'=>$final_ticket_price,
314
+			'TKT_sold'=> 0,// note: this will get calculated as we actually add registrations during the migration
315
+			'TKT_qty'=> -1,
316
+			'TKT_uses'=> 1,
317
+			'TKT_taxable'=>false,// so by default, old prices are NOT taxable. This way they don't suddenly have a sudden spike in prices
318
+			'TKT_is_default'=>false,
319
+			'TKT_order'=>$this->_get_ticket_count(),
320
+			'TKT_row'=>0,// doesn't matter because UI reset this on first save anyways
321
+			'TKT_deleted'=>false,
322
+			'TKT_parent'=>0
323 323
 
324
-        );
325
-        $datatypes = array(
326
-            '%d',// TTM_ID
327
-            '%s',// TKT_name
328
-            '%s',// TKT_description
329
-            '%s',// TKT_start_date
330
-            '%s',// TKT_end_date
331
-            '%d',// TKT_min
332
-            '%d',// TKT_max
333
-            '%f',// TKT_price
334
-            '%d',// TKT_sold
335
-            '%d',// TKT_qty
336
-            '%d',// TKT_uses
337
-            '%d',// TKT_taxable
338
-            '%d',// TKT_is_default
339
-            '%d',// TKT_order
340
-            '%d',// TKT_row
341
-            '%d',// TKT_deleted
342
-            '%d',// TKT_parent
343
-        );
344
-        $success = $wpdb->insert($this->_new_ticket_table, $cols_n_values, $datatypes);
345
-        if (! $success) {
346
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price_row, $this->_new_ticket_table, $cols_n_values, $datatypes));
347
-            return 0;
348
-        }
349
-        $new_id = $wpdb->insert_id;
350
-        return $new_id;
351
-    }
324
+		);
325
+		$datatypes = array(
326
+			'%d',// TTM_ID
327
+			'%s',// TKT_name
328
+			'%s',// TKT_description
329
+			'%s',// TKT_start_date
330
+			'%s',// TKT_end_date
331
+			'%d',// TKT_min
332
+			'%d',// TKT_max
333
+			'%f',// TKT_price
334
+			'%d',// TKT_sold
335
+			'%d',// TKT_qty
336
+			'%d',// TKT_uses
337
+			'%d',// TKT_taxable
338
+			'%d',// TKT_is_default
339
+			'%d',// TKT_order
340
+			'%d',// TKT_row
341
+			'%d',// TKT_deleted
342
+			'%d',// TKT_parent
343
+		);
344
+		$success = $wpdb->insert($this->_new_ticket_table, $cols_n_values, $datatypes);
345
+		if (! $success) {
346
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price_row, $this->_new_ticket_table, $cols_n_values, $datatypes));
347
+			return 0;
348
+		}
349
+		$new_id = $wpdb->insert_id;
350
+		return $new_id;
351
+	}
352 352
 
353
-    /**
354
-     * Adds a join between a ticket and a price
355
-     * @global type $wpdb
356
-     * @param type $new_ticket_id
357
-     * @param type $new_price_id
358
-     * @return int
359
-     */
360
-    private function _insert_ticket_price_relation($new_ticket_id, $new_price_id)
361
-    {
362
-        global $wpdb;
363
-        $cols_n_values = array(
364
-            'TKT_ID'=>$new_ticket_id,
365
-            'PRC_ID'=>$new_price_id,
366
-        );
367
-        $datatypes = array(
368
-            '%d',// TKT_ID
369
-            '%d',// PRC_ID
370
-        );
371
-        $success = $wpdb->insert($this->_new_ticket_price_table, $cols_n_values, $datatypes);
372
-        if (! $success) {
373
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, array('ticket id'=>$new_ticket_id,'price id'=>$new_price_id), $this->_new_ticket_price_table, $cols_n_values, $datatypes));
374
-            return 0;
375
-        }
376
-        $new_id = $wpdb->insert_id;
377
-        return $new_id;
378
-    }
353
+	/**
354
+	 * Adds a join between a ticket and a price
355
+	 * @global type $wpdb
356
+	 * @param type $new_ticket_id
357
+	 * @param type $new_price_id
358
+	 * @return int
359
+	 */
360
+	private function _insert_ticket_price_relation($new_ticket_id, $new_price_id)
361
+	{
362
+		global $wpdb;
363
+		$cols_n_values = array(
364
+			'TKT_ID'=>$new_ticket_id,
365
+			'PRC_ID'=>$new_price_id,
366
+		);
367
+		$datatypes = array(
368
+			'%d',// TKT_ID
369
+			'%d',// PRC_ID
370
+		);
371
+		$success = $wpdb->insert($this->_new_ticket_price_table, $cols_n_values, $datatypes);
372
+		if (! $success) {
373
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, array('ticket id'=>$new_ticket_id,'price id'=>$new_price_id), $this->_new_ticket_price_table, $cols_n_values, $datatypes));
374
+			return 0;
375
+		}
376
+		$new_id = $wpdb->insert_id;
377
+		return $new_id;
378
+	}
379 379
 
380
-    /**
381
-     * Adds a join between a ticket and a datetime
382
-     * @global type $wpdb
383
-     * @param type $new_ticket_id
384
-     * @param type $new_price_id
385
-     * @return int
386
-     */
387
-    private function _insert_datetime_ticket_relation($new_datetime_id, $new_ticket_id)
388
-    {
389
-        global $wpdb;
390
-        $cols_n_values = array(
391
-            'TKT_ID'=>$new_ticket_id,
392
-            'DTT_ID'=>$new_datetime_id,
393
-        );
394
-        $datatypes = array(
395
-            '%d',// TKT_ID
396
-            '%d',// DTT_ID
397
-        );
398
-        $success = $wpdb->insert($this->_new_datetime_ticket_table, $cols_n_values, $datatypes);
399
-        if (! $success) {
400
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, array('ticket id'=>$new_ticket_id,'datetime id'=>$new_datetime_id), $this->_new_datetime_ticket_table, $cols_n_values, $datatypes));
401
-            return 0;
402
-        }
403
-        $new_id = $wpdb->insert_id;
404
-        return $new_id;
405
-    }
380
+	/**
381
+	 * Adds a join between a ticket and a datetime
382
+	 * @global type $wpdb
383
+	 * @param type $new_ticket_id
384
+	 * @param type $new_price_id
385
+	 * @return int
386
+	 */
387
+	private function _insert_datetime_ticket_relation($new_datetime_id, $new_ticket_id)
388
+	{
389
+		global $wpdb;
390
+		$cols_n_values = array(
391
+			'TKT_ID'=>$new_ticket_id,
392
+			'DTT_ID'=>$new_datetime_id,
393
+		);
394
+		$datatypes = array(
395
+			'%d',// TKT_ID
396
+			'%d',// DTT_ID
397
+		);
398
+		$success = $wpdb->insert($this->_new_datetime_ticket_table, $cols_n_values, $datatypes);
399
+		if (! $success) {
400
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, array('ticket id'=>$new_ticket_id,'datetime id'=>$new_datetime_id), $this->_new_datetime_ticket_table, $cols_n_values, $datatypes));
401
+			return 0;
402
+		}
403
+		$new_id = $wpdb->insert_id;
404
+		return $new_id;
405
+	}
406 406
 
407
-    /**
408
-     * Simply gets the 3.1 event row data
409
-     * @global type $wpdb
410
-     * @param type $event_id
411
-     * @return array
412
-     */
413
-    private function _get_event_row($event_id)
414
-    {
415
-        global $wpdb;
416
-        $old_event_table = $wpdb->prefix."events_detail";
417
-        return $wpdb->get_row($wpdb->prepare("SELECT * FROM $old_event_table WHERE id=%d", $event_id), ARRAY_A);
418
-    }
419
-    /**
420
-     * Gets a higher ticket count than last time it was called (and is persisted between HTTP requests).
421
-     * Yes we COULD run a query joining events->datetimes->ticket_datetimes->tickets, but this should work fine too
422
-     * @return int
423
-     */
424
-    private function _get_ticket_count()
425
-    {
426
-        return $this->_ticket_count++;
427
-    }
407
+	/**
408
+	 * Simply gets the 3.1 event row data
409
+	 * @global type $wpdb
410
+	 * @param type $event_id
411
+	 * @return array
412
+	 */
413
+	private function _get_event_row($event_id)
414
+	{
415
+		global $wpdb;
416
+		$old_event_table = $wpdb->prefix."events_detail";
417
+		return $wpdb->get_row($wpdb->prepare("SELECT * FROM $old_event_table WHERE id=%d", $event_id), ARRAY_A);
418
+	}
419
+	/**
420
+	 * Gets a higher ticket count than last time it was called (and is persisted between HTTP requests).
421
+	 * Yes we COULD run a query joining events->datetimes->ticket_datetimes->tickets, but this should work fine too
422
+	 * @return int
423
+	 */
424
+	private function _get_ticket_count()
425
+	{
426
+		return $this->_ticket_count++;
427
+	}
428 428
 
429
-    /**
430
-     * Using the 3.1 event id, gets the 4.1 datetimes for it
431
-     * @param int $old_event_id
432
-     * @return array where values are datetime ids
433
-     */
434
-    private function _get_datetime_ids_for_old_event_id($old_event_id)
435
-    {
436
-        global $wpdb;
437
-        $new_cpt_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix."events_detail", $old_event_id, $wpdb->posts);
438
-        $datetime_ids = $wpdb->get_col($wpdb->prepare("SELECT DTT_ID FROM {$wpdb->prefix}esp_datetime WHERE EVT_ID=%d", $new_cpt_id));
439
-        return $datetime_ids;
440
-    }
429
+	/**
430
+	 * Using the 3.1 event id, gets the 4.1 datetimes for it
431
+	 * @param int $old_event_id
432
+	 * @return array where values are datetime ids
433
+	 */
434
+	private function _get_datetime_ids_for_old_event_id($old_event_id)
435
+	{
436
+		global $wpdb;
437
+		$new_cpt_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix."events_detail", $old_event_id, $wpdb->posts);
438
+		$datetime_ids = $wpdb->get_col($wpdb->prepare("SELECT DTT_ID FROM {$wpdb->prefix}esp_datetime WHERE EVT_ID=%d", $new_cpt_id));
439
+		return $datetime_ids;
440
+	}
441 441
 }
442 442
 // @todo: tell users that in 3.1 the limit was on registration PER event,in 4.1 it's limit PER TICKET... SO, if they sell 2 different types of tickets
443 443
 //
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
         $this->_old_table = $wpdb->prefix."events_prices";
109 109
         $this->select_expression = 'p.*, e.event_status';
110 110
         $this->_extra_where_sql = ' AS p 
111
-            INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON p.event_id=e.id
111
+            INNER JOIN ' . $wpdb->prefix.'events_detail AS e ON p.event_id=e.id
112 112
             WHERE e.event_status!="D"';
113 113
         $this->_new_price_table = $wpdb->prefix."esp_price";
114 114
         $this->_new_ticket_table = $wpdb->prefix."esp_ticket";
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
         // create the surcharge if there is any
131 131
         if (floatval($old_row['surcharge']) >= 0.01) {
132 132
             $surcharge_price_id = $this->_insert_new_surcharge_price($old_row);
133
-            $this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_price_table, array($new_price_id,$surcharge_price_id));
133
+            $this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_price_table, array($new_price_id, $surcharge_price_id));
134 134
         } else {
135 135
             $surcharge_price_id = 0;
136 136
             $this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_price_table, array($new_price_id));
@@ -182,17 +182,17 @@  discard block
 block discarded – undo
182 182
 
183 183
         );
184 184
         $datatypes = array(
185
-            '%d',// PRT_ID
186
-            '%f',// PRT_amount
187
-            '%s',// PRC_name
188
-            '%d',// PRC_is_default
189
-            '%d',// PRC_overrides
190
-            '%d',// PRC_order
191
-            '%d',// PRC_deleted
192
-            '%d',// PRC_parent
185
+            '%d', // PRT_ID
186
+            '%f', // PRT_amount
187
+            '%s', // PRC_name
188
+            '%d', // PRC_is_default
189
+            '%d', // PRC_overrides
190
+            '%d', // PRC_order
191
+            '%d', // PRC_deleted
192
+            '%d', // PRC_parent
193 193
         );
194 194
         $success = $wpdb->insert($this->_new_price_table, $cols_n_values, $datatypes);
195
-        if (! $success) {
195
+        if ( ! $success) {
196 196
             $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price, $this->_new_price_table, $cols_n_values, $datatypes));
197 197
             return 0;
198 198
         }
@@ -264,17 +264,17 @@  discard block
 block discarded – undo
264 264
 
265 265
         );
266 266
         $datatypes = array(
267
-            '%d',// PRT_ID
268
-            '%f',// PRT_amount
269
-            '%s',// PRC_name
270
-            '%d',// PRC_is_default
271
-            '%d',// PRC_overrides
272
-            '%d',// PRC_order
273
-            '%d',// PRC_deleted
274
-            '%d',// PRC_parent
267
+            '%d', // PRT_ID
268
+            '%f', // PRT_amount
269
+            '%s', // PRC_name
270
+            '%d', // PRC_is_default
271
+            '%d', // PRC_overrides
272
+            '%d', // PRC_order
273
+            '%d', // PRC_deleted
274
+            '%d', // PRC_parent
275 275
         );
276 276
         $success = $wpdb->insert($this->_new_price_table, $cols_n_values, $datatypes);
277
-        if (! $success) {
277
+        if ( ! $success) {
278 278
             $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price, $this->_new_price_table, $cols_n_values, $datatypes));
279 279
             return 0;
280 280
         }
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
         if ($old_price_row['surcharge_type'] == 'flat_rate') {
297 297
             $final_ticket_price = floatval($old_price_row['event_cost']) + floatval($old_price_row['surcharge']);
298 298
         } else {// percent surcharge
299
-            $final_ticket_price = floatval($old_price_row['event_cost']) * (1 + floatval($old_price_row['surcharge'])/100);
299
+            $final_ticket_price = floatval($old_price_row['event_cost']) * (1 + floatval($old_price_row['surcharge']) / 100);
300 300
         }
301 301
         $start_date = $event_row['registration_start']." ".$this->get_migration_script()->convertTimeFromAMPM($event_row['registration_startT']);
302 302
         $start_date_utc = $this->get_migration_script()->convert_date_string_to_utc($this, $old_price_row, $start_date, $event_row['timezone_string']);
@@ -311,38 +311,38 @@  discard block
 block discarded – undo
311 311
             'TKT_min'=>0,
312 312
             'TKT_max'=>-1,
313 313
             'TKT_price'=>$final_ticket_price,
314
-            'TKT_sold'=> 0,// note: this will get calculated as we actually add registrations during the migration
314
+            'TKT_sold'=> 0, // note: this will get calculated as we actually add registrations during the migration
315 315
             'TKT_qty'=> -1,
316 316
             'TKT_uses'=> 1,
317
-            'TKT_taxable'=>false,// so by default, old prices are NOT taxable. This way they don't suddenly have a sudden spike in prices
317
+            'TKT_taxable'=>false, // so by default, old prices are NOT taxable. This way they don't suddenly have a sudden spike in prices
318 318
             'TKT_is_default'=>false,
319 319
             'TKT_order'=>$this->_get_ticket_count(),
320
-            'TKT_row'=>0,// doesn't matter because UI reset this on first save anyways
320
+            'TKT_row'=>0, // doesn't matter because UI reset this on first save anyways
321 321
             'TKT_deleted'=>false,
322 322
             'TKT_parent'=>0
323 323
 
324 324
         );
325 325
         $datatypes = array(
326
-            '%d',// TTM_ID
327
-            '%s',// TKT_name
328
-            '%s',// TKT_description
329
-            '%s',// TKT_start_date
330
-            '%s',// TKT_end_date
331
-            '%d',// TKT_min
332
-            '%d',// TKT_max
333
-            '%f',// TKT_price
334
-            '%d',// TKT_sold
335
-            '%d',// TKT_qty
336
-            '%d',// TKT_uses
337
-            '%d',// TKT_taxable
338
-            '%d',// TKT_is_default
339
-            '%d',// TKT_order
340
-            '%d',// TKT_row
341
-            '%d',// TKT_deleted
342
-            '%d',// TKT_parent
326
+            '%d', // TTM_ID
327
+            '%s', // TKT_name
328
+            '%s', // TKT_description
329
+            '%s', // TKT_start_date
330
+            '%s', // TKT_end_date
331
+            '%d', // TKT_min
332
+            '%d', // TKT_max
333
+            '%f', // TKT_price
334
+            '%d', // TKT_sold
335
+            '%d', // TKT_qty
336
+            '%d', // TKT_uses
337
+            '%d', // TKT_taxable
338
+            '%d', // TKT_is_default
339
+            '%d', // TKT_order
340
+            '%d', // TKT_row
341
+            '%d', // TKT_deleted
342
+            '%d', // TKT_parent
343 343
         );
344 344
         $success = $wpdb->insert($this->_new_ticket_table, $cols_n_values, $datatypes);
345
-        if (! $success) {
345
+        if ( ! $success) {
346 346
             $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_price_row, $this->_new_ticket_table, $cols_n_values, $datatypes));
347 347
             return 0;
348 348
         }
@@ -365,12 +365,12 @@  discard block
 block discarded – undo
365 365
             'PRC_ID'=>$new_price_id,
366 366
         );
367 367
         $datatypes = array(
368
-            '%d',// TKT_ID
369
-            '%d',// PRC_ID
368
+            '%d', // TKT_ID
369
+            '%d', // PRC_ID
370 370
         );
371 371
         $success = $wpdb->insert($this->_new_ticket_price_table, $cols_n_values, $datatypes);
372
-        if (! $success) {
373
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, array('ticket id'=>$new_ticket_id,'price id'=>$new_price_id), $this->_new_ticket_price_table, $cols_n_values, $datatypes));
372
+        if ( ! $success) {
373
+            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, array('ticket id'=>$new_ticket_id, 'price id'=>$new_price_id), $this->_new_ticket_price_table, $cols_n_values, $datatypes));
374 374
             return 0;
375 375
         }
376 376
         $new_id = $wpdb->insert_id;
@@ -392,12 +392,12 @@  discard block
 block discarded – undo
392 392
             'DTT_ID'=>$new_datetime_id,
393 393
         );
394 394
         $datatypes = array(
395
-            '%d',// TKT_ID
396
-            '%d',// DTT_ID
395
+            '%d', // TKT_ID
396
+            '%d', // DTT_ID
397 397
         );
398 398
         $success = $wpdb->insert($this->_new_datetime_ticket_table, $cols_n_values, $datatypes);
399
-        if (! $success) {
400
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, array('ticket id'=>$new_ticket_id,'datetime id'=>$new_datetime_id), $this->_new_datetime_ticket_table, $cols_n_values, $datatypes));
399
+        if ( ! $success) {
400
+            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, array('ticket id'=>$new_ticket_id, 'datetime id'=>$new_datetime_id), $this->_new_datetime_ticket_table, $cols_n_values, $datatypes));
401 401
             return 0;
402 402
         }
403 403
         $new_id = $wpdb->insert_id;
Please login to merge, or discard this patch.
core/data_migration_scripts/4_1_0_stages/EE_DMS_4_1_0_answers.dmsstage.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -42,8 +42,8 @@  discard block
 block discarded – undo
42 42
         // join to attendee and then join to events table
43 43
         $this->select_expression = 'ans.*, e.event_status';
44 44
         $this->_extra_where_sql = ' AS ans 
45
-            INNER JOIN ' . $wpdb->prefix . 'events_attendee AS att ON ans.attendee_id = att.id
46
-            INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id = e.id 
45
+            INNER JOIN ' . $wpdb->prefix.'events_attendee AS att ON ans.attendee_id = att.id
46
+            INNER JOIN ' . $wpdb->prefix.'events_detail AS e ON att.event_id = e.id 
47 47
             WHERE e.event_status !="D"';
48 48
         $this->_new_answer_table = $wpdb->prefix."esp_answer";
49 49
         $this->_new_question_table = $wpdb->prefix."esp_question";
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
         $old_attendee_table = $wpdb->prefix."events_attendee";
57 57
         $new_reg_table = $wpdb->prefix."esp_registration";
58 58
         $regs = $this->get_migration_script()->get_mapping_new_pk($old_attendee_table, $old_row['attendee_id'], $new_reg_table);
59
-        if (! $regs) {
59
+        if ( ! $regs) {
60 60
             $this->add_error(sprintf(__("Could not find new registrations for old attendee %d when creating answer %s", "event_espresso"), $old_row['attendee_id'], $this->_json_encode($old_row)));
61 61
             return false;
62 62
         }
@@ -90,12 +90,12 @@  discard block
 block discarded – undo
90 90
             'ANS_value'=>$ans_value
91 91
         );
92 92
         $datatypes = array(
93
-            '%d',// REG_ID
94
-            '%d',// QST_ID
95
-            '%s',// ANS_value
93
+            '%d', // REG_ID
94
+            '%d', // QST_ID
95
+            '%s', // ANS_value
96 96
         );
97 97
         $success = $wpdb->insert($this->_new_answer_table, $cols_n_values, $datatypes);
98
-        if (! $success) {
98
+        if ( ! $success) {
99 99
             $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_answer, $this->_new_answer_table, $cols_n_values, $datatypes));
100 100
             return 0;
101 101
         }
Please login to merge, or discard this patch.
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -32,102 +32,102 @@
 block discarded – undo
32 32
 
33 33
 class EE_DMS_4_1_0_answers extends EE_Data_Migration_Script_Stage_Table
34 34
 {
35
-    private $_new_answer_table;
36
-    private $_new_question_table;
37
-    public function __construct()
38
-    {
39
-        global $wpdb;
40
-        $this->_pretty_name = __("Answers", "event_espresso");
41
-        $this->_old_table = $wpdb->prefix."events_answer";
42
-        // join to attendee and then join to events table
43
-        $this->select_expression = 'ans.*, e.event_status';
44
-        $this->_extra_where_sql = ' AS ans 
35
+	private $_new_answer_table;
36
+	private $_new_question_table;
37
+	public function __construct()
38
+	{
39
+		global $wpdb;
40
+		$this->_pretty_name = __("Answers", "event_espresso");
41
+		$this->_old_table = $wpdb->prefix."events_answer";
42
+		// join to attendee and then join to events table
43
+		$this->select_expression = 'ans.*, e.event_status';
44
+		$this->_extra_where_sql = ' AS ans 
45 45
             INNER JOIN ' . $wpdb->prefix . 'events_attendee AS att ON ans.attendee_id = att.id
46 46
             INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id = e.id 
47 47
             WHERE e.event_status !="D"';
48
-        $this->_new_answer_table = $wpdb->prefix."esp_answer";
49
-        $this->_new_question_table = $wpdb->prefix."esp_question";
50
-        parent::__construct();
51
-    }
52
-    protected function _migrate_old_row($old_row)
53
-    {
54
-        // get the new REGs for the old answer
55
-        global $wpdb;
56
-        $old_attendee_table = $wpdb->prefix."events_attendee";
57
-        $new_reg_table = $wpdb->prefix."esp_registration";
58
-        $regs = $this->get_migration_script()->get_mapping_new_pk($old_attendee_table, $old_row['attendee_id'], $new_reg_table);
59
-        if (! $regs) {
60
-            $this->add_error(sprintf(__("Could not find new registrations for old attendee %d when creating answer %s", "event_espresso"), $old_row['attendee_id'], $this->_json_encode($old_row)));
61
-            return false;
62
-        }
63
-        // as inefficient as this sounds, we create an answer per REGISTRATION, (even if the registrations use the same attendee)
64
-        foreach ($regs as $new_reg_id) {
65
-            $this->_insert_new_answer($old_row, $new_reg_id);
66
-        }
67
-    }
68
-    /**
69
-     * Creates a 4.1 price base type
70
-     * @global type $wpdb
71
-     * @param array $old_price
72
-     * @param int $new_reg_id
73
-     * @return int
74
-     */
75
-    private function _insert_new_answer($old_answer, $new_reg_id)
76
-    {
77
-        global $wpdb;
78
-        $old_question_table = $wpdb->prefix."events_question";
79
-        $new_question_id = $this->get_migration_script()->get_mapping_new_pk($old_question_table, $old_answer['question_id'], $this->_new_question_table);
48
+		$this->_new_answer_table = $wpdb->prefix."esp_answer";
49
+		$this->_new_question_table = $wpdb->prefix."esp_question";
50
+		parent::__construct();
51
+	}
52
+	protected function _migrate_old_row($old_row)
53
+	{
54
+		// get the new REGs for the old answer
55
+		global $wpdb;
56
+		$old_attendee_table = $wpdb->prefix."events_attendee";
57
+		$new_reg_table = $wpdb->prefix."esp_registration";
58
+		$regs = $this->get_migration_script()->get_mapping_new_pk($old_attendee_table, $old_row['attendee_id'], $new_reg_table);
59
+		if (! $regs) {
60
+			$this->add_error(sprintf(__("Could not find new registrations for old attendee %d when creating answer %s", "event_espresso"), $old_row['attendee_id'], $this->_json_encode($old_row)));
61
+			return false;
62
+		}
63
+		// as inefficient as this sounds, we create an answer per REGISTRATION, (even if the registrations use the same attendee)
64
+		foreach ($regs as $new_reg_id) {
65
+			$this->_insert_new_answer($old_row, $new_reg_id);
66
+		}
67
+	}
68
+	/**
69
+	 * Creates a 4.1 price base type
70
+	 * @global type $wpdb
71
+	 * @param array $old_price
72
+	 * @param int $new_reg_id
73
+	 * @return int
74
+	 */
75
+	private function _insert_new_answer($old_answer, $new_reg_id)
76
+	{
77
+		global $wpdb;
78
+		$old_question_table = $wpdb->prefix."events_question";
79
+		$new_question_id = $this->get_migration_script()->get_mapping_new_pk($old_question_table, $old_answer['question_id'], $this->_new_question_table);
80 80
 
81
-        $question_row = $this->_get_question_type_and_system($new_question_id);
82
-        if ($question_row['QST_system']) {
83
-            // It's an answer to a system question? EE3 used to store that on both the attendee and the answers column,
84
-            // but not EE4! It's just stored in the attendee meta table. The answers table is ONLY for answers to custom
85
-            // questions.
86
-            return 0;
87
-        }
88
-        if (in_array($question_row['QST_type'], array('MULTIPLE'))) {
89
-            $ans_value = serialize(explode(",", stripslashes($old_answer['answer'])));
90
-        } else {
91
-            $ans_value = stripslashes($old_answer['answer']);
92
-        }
93
-        $cols_n_values = array(
94
-            'REG_ID'=>$new_reg_id,
95
-            'QST_ID'=>$new_question_id,
96
-            'ANS_value'=>$ans_value
97
-        );
98
-        $datatypes = array(
99
-            '%d',// REG_ID
100
-            '%d',// QST_ID
101
-            '%s',// ANS_value
102
-        );
103
-        $success = $wpdb->insert($this->_new_answer_table, $cols_n_values, $datatypes);
104
-        if (! $success) {
105
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_answer, $this->_new_answer_table, $cols_n_values, $datatypes));
106
-            return 0;
107
-        }
108
-        $new_id = $wpdb->insert_id;
109
-        return $new_id;
110
-    }
81
+		$question_row = $this->_get_question_type_and_system($new_question_id);
82
+		if ($question_row['QST_system']) {
83
+			// It's an answer to a system question? EE3 used to store that on both the attendee and the answers column,
84
+			// but not EE4! It's just stored in the attendee meta table. The answers table is ONLY for answers to custom
85
+			// questions.
86
+			return 0;
87
+		}
88
+		if (in_array($question_row['QST_type'], array('MULTIPLE'))) {
89
+			$ans_value = serialize(explode(",", stripslashes($old_answer['answer'])));
90
+		} else {
91
+			$ans_value = stripslashes($old_answer['answer']);
92
+		}
93
+		$cols_n_values = array(
94
+			'REG_ID'=>$new_reg_id,
95
+			'QST_ID'=>$new_question_id,
96
+			'ANS_value'=>$ans_value
97
+		);
98
+		$datatypes = array(
99
+			'%d',// REG_ID
100
+			'%d',// QST_ID
101
+			'%s',// ANS_value
102
+		);
103
+		$success = $wpdb->insert($this->_new_answer_table, $cols_n_values, $datatypes);
104
+		if (! $success) {
105
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_answer, $this->_new_answer_table, $cols_n_values, $datatypes));
106
+			return 0;
107
+		}
108
+		$new_id = $wpdb->insert_id;
109
+		return $new_id;
110
+	}
111 111
 
112
-    /**
113
-     * Gets the question's type
114
-     * @global type $wpdb
115
-     * @param type $question_id
116
-     * @return array {
117
-     *  @type string $QST_type
118
-     *  @type string $QST_system
119
-     * }
120
-     */
121
-    private function _get_question_type_and_system($question_id)
122
-    {
123
-        global $wpdb;
124
-        $row = $wpdb->get_row(
125
-            $wpdb->prepare(
126
-                "SELECT QST_type, QST_system FROM ".$this->_new_question_table." WHERE QST_ID=%d LIMIT 1",
127
-                $question_id
128
-            ),
129
-            ARRAY_A
130
-        );
131
-        return $row;
132
-    }
112
+	/**
113
+	 * Gets the question's type
114
+	 * @global type $wpdb
115
+	 * @param type $question_id
116
+	 * @return array {
117
+	 *  @type string $QST_type
118
+	 *  @type string $QST_system
119
+	 * }
120
+	 */
121
+	private function _get_question_type_and_system($question_id)
122
+	{
123
+		global $wpdb;
124
+		$row = $wpdb->get_row(
125
+			$wpdb->prepare(
126
+				"SELECT QST_type, QST_system FROM ".$this->_new_question_table." WHERE QST_ID=%d LIMIT 1",
127
+				$question_id
128
+			),
129
+			ARRAY_A
130
+		);
131
+		return $row;
132
+	}
133 133
 }
Please login to merge, or discard this patch.
core/data_migration_scripts/4_1_0_stages/EE_DMS_4_1_0_checkins.dmsstage.php 2 patches
Indentation   +142 added lines, -142 removed lines patch added patch discarded remove patch
@@ -26,160 +26,160 @@
 block discarded – undo
26 26
 
27 27
 class EE_DMS_4_1_0_checkins extends EE_Data_Migration_Script_Stage_Table
28 28
 {
29
-    private $_new_table;
30
-    public function __construct()
31
-    {
32
-        global $wpdb;
33
-        $this->_pretty_name = esc_html__('Checkins', 'event_espresso');
34
-        $this->_old_table = $wpdb->prefix."events_attendee";
35
-        $this->select_expression = 'att.*, e.event_status';
36
-        $this->_extra_where_sql = 'AS att
29
+	private $_new_table;
30
+	public function __construct()
31
+	{
32
+		global $wpdb;
33
+		$this->_pretty_name = esc_html__('Checkins', 'event_espresso');
34
+		$this->_old_table = $wpdb->prefix."events_attendee";
35
+		$this->select_expression = 'att.*, e.event_status';
36
+		$this->_extra_where_sql = 'AS att
37 37
             INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id=e.id
38 38
             WHERE e.event_status!="D"';
39
-        $this->_new_table = $wpdb->prefix."esp_checkin";
40
-        parent::__construct();
41
-    }
42
-    protected function _migrate_old_row($old_row)
43
-    {
44
-        global $wpdb;
45
-        $new_reg_table = $wpdb->prefix."esp_registration";
39
+		$this->_new_table = $wpdb->prefix."esp_checkin";
40
+		parent::__construct();
41
+	}
42
+	protected function _migrate_old_row($old_row)
43
+	{
44
+		global $wpdb;
45
+		$new_reg_table = $wpdb->prefix."esp_registration";
46 46
 
47
-        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
47
+		$num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
48 48
 
49
-        $new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
-        if (! $new_registrations_for_attendee) {
51
-            $new_registrations_for_attendee = array();
52
-        }
53
-        $new_datetime = $this->_try_to_find_datetime($old_row);
49
+		$new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
+		if (! $new_registrations_for_attendee) {
51
+			$new_registrations_for_attendee = array();
52
+		}
53
+		$new_datetime = $this->_try_to_find_datetime($old_row);
54 54
 
55
-        // make sure registrations array is numerically indexed starting at 0 (it probably already is)
56
-        $new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57
-        $new_checkin_ids = array();
58
-        for ($i = 0; $i<abs($num_to_checkin_at_this_time); $i++) {
59
-            $new_reg_id = $new_registrations_for_attendee[ $i ];
60
-            if (! $new_reg_id) {
61
-                $this->add_error(sprintf(
62
-                    esc_html__(
63
-                        /* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
55
+		// make sure registrations array is numerically indexed starting at 0 (it probably already is)
56
+		$new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57
+		$new_checkin_ids = array();
58
+		for ($i = 0; $i<abs($num_to_checkin_at_this_time); $i++) {
59
+			$new_reg_id = $new_registrations_for_attendee[ $i ];
60
+			if (! $new_reg_id) {
61
+				$this->add_error(sprintf(
62
+					esc_html__(
63
+						/* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
64 64
                         *  %3$s number of registrations for the attendee, %4$s new registration rows represented in JSON
65 65
                         */
66
-                        // @codingStandardsIgnoreStart
67
-                        'It appears we wanted to check-in more registrations than actually exist. The old attendee record (%1$s) indicated we should check-in %2$d registrations, but there are only %3$d registrations for that attendee (%4$s)',
68
-                        // @codingStandardsIgnoreEnd
69
-                        'event_espresso'
70
-                    ),
71
-                    $this->_json_encode($old_row),
72
-                    abs($num_to_checkin_at_this_time),
73
-                    count($new_registrations_for_attendee),
74
-                    $this->_json_encode($new_registrations_for_attendee)
75
-                ));
76
-                break;
77
-            }
78
-            $existing_checkin_record = $wpdb->get_var(
79
-                $wpdb->prepare(
80
-                    "SELECT CHK_ID FROM $this->_new_table WHERE REG_ID = %d ORDER BY CHK_ID DESC LIMIT 1",
81
-                    $new_reg_id
82
-                )
83
-            );
84
-            if (! $existing_checkin_record) {
85
-                $new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86
-                if ($new_id) {
87
-                    $new_checkin_ids[]= $new_id;
88
-                }
89
-            }
90
-        }
91
-        if ($new_checkin_ids) {
92
-            $this->get_migration_script()->set_mapping(
93
-                $this->_old_table,
94
-                $old_row['id'],
95
-                $this->_new_table,
96
-                $new_checkin_ids
97
-            );
98
-        }
99
-    }
66
+						// @codingStandardsIgnoreStart
67
+						'It appears we wanted to check-in more registrations than actually exist. The old attendee record (%1$s) indicated we should check-in %2$d registrations, but there are only %3$d registrations for that attendee (%4$s)',
68
+						// @codingStandardsIgnoreEnd
69
+						'event_espresso'
70
+					),
71
+					$this->_json_encode($old_row),
72
+					abs($num_to_checkin_at_this_time),
73
+					count($new_registrations_for_attendee),
74
+					$this->_json_encode($new_registrations_for_attendee)
75
+				));
76
+				break;
77
+			}
78
+			$existing_checkin_record = $wpdb->get_var(
79
+				$wpdb->prepare(
80
+					"SELECT CHK_ID FROM $this->_new_table WHERE REG_ID = %d ORDER BY CHK_ID DESC LIMIT 1",
81
+					$new_reg_id
82
+				)
83
+			);
84
+			if (! $existing_checkin_record) {
85
+				$new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86
+				if ($new_id) {
87
+					$new_checkin_ids[]= $new_id;
88
+				}
89
+			}
90
+		}
91
+		if ($new_checkin_ids) {
92
+			$this->get_migration_script()->set_mapping(
93
+				$this->_old_table,
94
+				$old_row['id'],
95
+				$this->_new_table,
96
+				$new_checkin_ids
97
+			);
98
+		}
99
+	}
100 100
 
101 101
 
102
-    /**
103
-     * Tries to find the new datetime the Check-in was for, based on the attendee row
104
-     * (because we know the attendee was for an event as a specific time, and we know
105
-     * the event's OLD ID...)
106
-     * @global type $wpdb
107
-     * @param array $old_attendee_row
108
-     * @return array row of datetime from DB
109
-     */
110
-    private function _try_to_find_datetime($old_attendee)
111
-    {
112
-        global $wpdb;
102
+	/**
103
+	 * Tries to find the new datetime the Check-in was for, based on the attendee row
104
+	 * (because we know the attendee was for an event as a specific time, and we know
105
+	 * the event's OLD ID...)
106
+	 * @global type $wpdb
107
+	 * @param array $old_attendee_row
108
+	 * @return array row of datetime from DB
109
+	 */
110
+	private function _try_to_find_datetime($old_attendee)
111
+	{
112
+		global $wpdb;
113 113
 
114
-        $new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix."events_detail", $old_attendee['event_id'], $wpdb->posts);
115
-        if (! $new_event_id) {
116
-            $this->add_error(
117
-                sprintf(
118
-                    esc_html__(
119
-                        /* translators: 1: original event ID, 2: original attendee database row */
120
-                        // @codingStandardsIgnoreStart
121
-                        'Could not find new event ID with old event ID %1$d, on attendee row %2$s; and because of that couldn\'t find the correct datetime for Check-in',
122
-                        // @codingStandardsIgnoreEnd
123
-                        'event_espresso'
124
-                    ),
125
-                    $old_attendee['event_id'],
126
-                    $this->_json_encode($old_attendee)
127
-                )
128
-            );
129
-            return 0;
130
-        }
131
-        $old_att_start_date = $old_attendee['start_date'];
132
-        $old_att_start_time = $this->get_migration_script()->convertTimeFromAMPM($old_attendee['event_time']);
133
-        $old_att_datetime = $this->get_migration_script()->convert_date_string_to_utc($this, $old_attendee, "$old_att_start_date $old_att_start_time:00");
114
+		$new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix."events_detail", $old_attendee['event_id'], $wpdb->posts);
115
+		if (! $new_event_id) {
116
+			$this->add_error(
117
+				sprintf(
118
+					esc_html__(
119
+						/* translators: 1: original event ID, 2: original attendee database row */
120
+						// @codingStandardsIgnoreStart
121
+						'Could not find new event ID with old event ID %1$d, on attendee row %2$s; and because of that couldn\'t find the correct datetime for Check-in',
122
+						// @codingStandardsIgnoreEnd
123
+						'event_espresso'
124
+					),
125
+					$old_attendee['event_id'],
126
+					$this->_json_encode($old_attendee)
127
+				)
128
+			);
129
+			return 0;
130
+		}
131
+		$old_att_start_date = $old_attendee['start_date'];
132
+		$old_att_start_time = $this->get_migration_script()->convertTimeFromAMPM($old_attendee['event_time']);
133
+		$old_att_datetime = $this->get_migration_script()->convert_date_string_to_utc($this, $old_attendee, "$old_att_start_date $old_att_start_time:00");
134 134
 
135
-        $datetime_table = $wpdb->prefix."esp_datetime";
136
-        // add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137
-        // the most important condition should be last, as it will be array_shift'ed off last
138
-        $conditions = array(
139
-            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
-            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
141
-        );
142
-        // start running queries, widening search each time by removing a condition
143
-        $datetime_found = null;
144
-        do {
145
-            $full_query = "SELECT * FROM $datetime_table WHERE ".implode(" AND ", $conditions)." LIMIT 1";
146
-            $datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147
-            array_shift($conditions);
148
-        } while (! $datetime_found && $conditions);
149
-        return $datetime_found;
150
-    }
135
+		$datetime_table = $wpdb->prefix."esp_datetime";
136
+		// add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137
+		// the most important condition should be last, as it will be array_shift'ed off last
138
+		$conditions = array(
139
+			$wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
+			$wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
141
+		);
142
+		// start running queries, widening search each time by removing a condition
143
+		$datetime_found = null;
144
+		do {
145
+			$full_query = "SELECT * FROM $datetime_table WHERE ".implode(" AND ", $conditions)." LIMIT 1";
146
+			$datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147
+			array_shift($conditions);
148
+		} while (! $datetime_found && $conditions);
149
+		return $datetime_found;
150
+	}
151 151
 
152
-    /**
153
-     * Adds a new Check-in/checkout record according for $new_reg_id,$new_datetime_id,$checking_in, and $timestmap
154
-     * @param int $new_reg_id
155
-     * @param int $new_datetime_id
156
-     * @param string $timestamp mysql datetime
157
-     * @return int new Check-in id
158
-     */
159
-    private function _insert_checkin_record($new_reg_id, $new_datetime)
160
-    {
161
-        global $wpdb;
152
+	/**
153
+	 * Adds a new Check-in/checkout record according for $new_reg_id,$new_datetime_id,$checking_in, and $timestmap
154
+	 * @param int $new_reg_id
155
+	 * @param int $new_datetime_id
156
+	 * @param string $timestamp mysql datetime
157
+	 * @return int new Check-in id
158
+	 */
159
+	private function _insert_checkin_record($new_reg_id, $new_datetime)
160
+	{
161
+		global $wpdb;
162 162
 
163 163
 
164
-        // ok we can actually do what we set out to do: add a checkin/checkout record
165
-        $cols_n_values = array(
166
-            'REG_ID'=>$new_reg_id,
167
-            'DTT_ID'=>$new_datetime['DTT_ID'],
168
-            'CHK_in'=>true,
169
-            'CHK_timestamp'=>$new_datetime['DTT_EVT_start']
170
-        );
171
-        $datatypes = array(
172
-            '%d',// REG_ID
173
-            '%d',// DTT_ID
174
-            '%d',// CHK_in
175
-            '%s',// CHK_timestamp
176
-        );
177
-        $success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
-        if (! $success) {
179
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180
-            return 0;
181
-        }
182
-        $new_id = $wpdb->insert_id;
183
-        return $new_id;
184
-    }
164
+		// ok we can actually do what we set out to do: add a checkin/checkout record
165
+		$cols_n_values = array(
166
+			'REG_ID'=>$new_reg_id,
167
+			'DTT_ID'=>$new_datetime['DTT_ID'],
168
+			'CHK_in'=>true,
169
+			'CHK_timestamp'=>$new_datetime['DTT_EVT_start']
170
+		);
171
+		$datatypes = array(
172
+			'%d',// REG_ID
173
+			'%d',// DTT_ID
174
+			'%d',// CHK_in
175
+			'%s',// CHK_timestamp
176
+		);
177
+		$success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
+		if (! $success) {
179
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180
+			return 0;
181
+		}
182
+		$new_id = $wpdb->insert_id;
183
+		return $new_id;
184
+	}
185 185
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
         $this->_old_table = $wpdb->prefix."events_attendee";
35 35
         $this->select_expression = 'att.*, e.event_status';
36 36
         $this->_extra_where_sql = 'AS att
37
-            INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id=e.id
37
+            INNER JOIN ' . $wpdb->prefix.'events_detail AS e ON att.event_id=e.id
38 38
             WHERE e.event_status!="D"';
39 39
         $this->_new_table = $wpdb->prefix."esp_checkin";
40 40
         parent::__construct();
@@ -44,10 +44,10 @@  discard block
 block discarded – undo
44 44
         global $wpdb;
45 45
         $new_reg_table = $wpdb->prefix."esp_registration";
46 46
 
47
-        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']),intval($old_row['checked_in']))) ;
47
+        $num_to_checkin_at_this_time = max(array(intval($old_row['checked_in_quantity']), intval($old_row['checked_in'])));
48 48
 
49 49
         $new_registrations_for_attendee = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $new_reg_table);
50
-        if (! $new_registrations_for_attendee) {
50
+        if ( ! $new_registrations_for_attendee) {
51 51
             $new_registrations_for_attendee = array();
52 52
         }
53 53
         $new_datetime = $this->_try_to_find_datetime($old_row);
@@ -55,9 +55,9 @@  discard block
 block discarded – undo
55 55
         // make sure registrations array is numerically indexed starting at 0 (it probably already is)
56 56
         $new_registrations_for_attendee = array_values($new_registrations_for_attendee);
57 57
         $new_checkin_ids = array();
58
-        for ($i = 0; $i<abs($num_to_checkin_at_this_time); $i++) {
59
-            $new_reg_id = $new_registrations_for_attendee[ $i ];
60
-            if (! $new_reg_id) {
58
+        for ($i = 0; $i < abs($num_to_checkin_at_this_time); $i++) {
59
+            $new_reg_id = $new_registrations_for_attendee[$i];
60
+            if ( ! $new_reg_id) {
61 61
                 $this->add_error(sprintf(
62 62
                     esc_html__(
63 63
                         /* translators: %1$s database row represented in JSON, %2$s number of registrations to check-in
@@ -81,10 +81,10 @@  discard block
 block discarded – undo
81 81
                     $new_reg_id
82 82
                 )
83 83
             );
84
-            if (! $existing_checkin_record) {
84
+            if ( ! $existing_checkin_record) {
85 85
                 $new_id = $this->_insert_checkin_record($new_reg_id, $new_datetime);
86 86
                 if ($new_id) {
87
-                    $new_checkin_ids[]= $new_id;
87
+                    $new_checkin_ids[] = $new_id;
88 88
                 }
89 89
             }
90 90
         }
@@ -112,7 +112,7 @@  discard block
 block discarded – undo
112 112
         global $wpdb;
113 113
 
114 114
         $new_event_id = $this->get_migration_script()->get_mapping_new_pk($wpdb->prefix."events_detail", $old_attendee['event_id'], $wpdb->posts);
115
-        if (! $new_event_id) {
115
+        if ( ! $new_event_id) {
116 116
             $this->add_error(
117 117
                 sprintf(
118 118
                     esc_html__(
@@ -136,8 +136,8 @@  discard block
 block discarded – undo
136 136
         // add all conditions to an array from which we can SHIFT conditions off in order to widen our search
137 137
         // the most important condition should be last, as it will be array_shift'ed off last
138 138
         $conditions = array(
139
-            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime),// times match?
140
-            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id),// events match?
139
+            $wpdb->prepare("$datetime_table.DTT_EVT_start = %s", $old_att_datetime), // times match?
140
+            $wpdb->prepare("$datetime_table.EVT_ID = %d", $new_event_id), // events match?
141 141
         );
142 142
         // start running queries, widening search each time by removing a condition
143 143
         $datetime_found = null;
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
             $full_query = "SELECT * FROM $datetime_table WHERE ".implode(" AND ", $conditions)." LIMIT 1";
146 146
             $datetime_found = $wpdb->get_row($full_query, ARRAY_A);
147 147
             array_shift($conditions);
148
-        } while (! $datetime_found && $conditions);
148
+        }while ( ! $datetime_found && $conditions);
149 149
         return $datetime_found;
150 150
     }
151 151
 
@@ -169,13 +169,13 @@  discard block
 block discarded – undo
169 169
             'CHK_timestamp'=>$new_datetime['DTT_EVT_start']
170 170
         );
171 171
         $datatypes = array(
172
-            '%d',// REG_ID
173
-            '%d',// DTT_ID
174
-            '%d',// CHK_in
175
-            '%s',// CHK_timestamp
172
+            '%d', // REG_ID
173
+            '%d', // DTT_ID
174
+            '%d', // CHK_in
175
+            '%s', // CHK_timestamp
176 176
         );
177 177
         $success = $wpdb->insert($this->_new_table, $cols_n_values, $datatypes);
178
-        if (! $success) {
178
+        if ( ! $success) {
179 179
             $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_checkin, $this->_new_table, $cols_n_values, $datatypes));
180 180
             return 0;
181 181
         }
Please login to merge, or discard this patch.
data_migration_scripts/4_1_0_stages/EE_DMS_4_1_0_line_items.dmsstage.php 2 patches
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -38,172 +38,172 @@
 block discarded – undo
38 38
  */
39 39
 class EE_DMS_4_1_0_line_items extends EE_Data_Migration_Script_Stage_Table
40 40
 {
41
-    private $_new_line_table;
42
-    private $_new_transaction_table;
43
-    private $_new_reg_table;
44
-    public function __construct()
45
-    {
46
-        global $wpdb;
47
-        $this->_pretty_name = __("Line Items", "event_espresso");
48
-        $this->_old_table = $wpdb->prefix."events_attendee";
49
-        $this->select_expression = 'att.*, e.event_status';
50
-        $this->_extra_where_sql = ' AS att
41
+	private $_new_line_table;
42
+	private $_new_transaction_table;
43
+	private $_new_reg_table;
44
+	public function __construct()
45
+	{
46
+		global $wpdb;
47
+		$this->_pretty_name = __("Line Items", "event_espresso");
48
+		$this->_old_table = $wpdb->prefix."events_attendee";
49
+		$this->select_expression = 'att.*, e.event_status';
50
+		$this->_extra_where_sql = ' AS att
51 51
             INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id=e.id
52 52
             WHERE e.event_status!="D"';
53
-        $this->_new_transaction_table = $wpdb->prefix."esp_transaction";
54
-        $this->_new_line_table = $wpdb->prefix."esp_line_item";
55
-        $this->_new_reg_table = $wpdb->prefix."esp_registration";
56
-        parent::__construct();
57
-    }
53
+		$this->_new_transaction_table = $wpdb->prefix."esp_transaction";
54
+		$this->_new_line_table = $wpdb->prefix."esp_line_item";
55
+		$this->_new_reg_table = $wpdb->prefix."esp_registration";
56
+		parent::__construct();
57
+	}
58 58
     
59
-    protected function _migrate_old_row($old_row)
60
-    {
61
-        // insert line items if its a primary id
62
-        if (intval($old_row['is_primary'])) {
63
-            $txn_id = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $this->_new_transaction_table);
64
-            if (! $txn_id) {
65
-                $this->add_error(sprintf(__("Could not find the transaction for the 3.1 attendee %d from row %s", "event_espresso"), $old_row['id'], $this->_json_encode($old_row)));
66
-                return;
67
-            }
68
-            $txn = $this->_get_txn($txn_id);
69
-            $new_line_items = $this->_insert_new_line_items($txn, $old_row);
70
-            $this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_line_table, $new_line_items);
71
-        }
72
-    }
59
+	protected function _migrate_old_row($old_row)
60
+	{
61
+		// insert line items if its a primary id
62
+		if (intval($old_row['is_primary'])) {
63
+			$txn_id = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $this->_new_transaction_table);
64
+			if (! $txn_id) {
65
+				$this->add_error(sprintf(__("Could not find the transaction for the 3.1 attendee %d from row %s", "event_espresso"), $old_row['id'], $this->_json_encode($old_row)));
66
+				return;
67
+			}
68
+			$txn = $this->_get_txn($txn_id);
69
+			$new_line_items = $this->_insert_new_line_items($txn, $old_row);
70
+			$this->get_migration_script()->set_mapping($this->_old_table, $old_row['id'], $this->_new_line_table, $new_line_items);
71
+		}
72
+	}
73 73
     
74
-    private function _get_txn($txn_id)
75
-    {
76
-        global $wpdb;
77
-        $txn = $wpdb->get_row($wpdb->prepare("SELECT * FROM $this->_new_transaction_table WHERE TXN_ID=%d", $txn_id), ARRAY_A);
78
-        return $txn;
79
-    }
74
+	private function _get_txn($txn_id)
75
+	{
76
+		global $wpdb;
77
+		$txn = $wpdb->get_row($wpdb->prepare("SELECT * FROM $this->_new_transaction_table WHERE TXN_ID=%d", $txn_id), ARRAY_A);
78
+		return $txn;
79
+	}
80 80
     
81
-    /**
82
-     * In 4.1, we'd normally need more info than just the registrations to make the line items. Ie, we'd need
83
-     * the transaction, and tax prices at the time of registration. (And probably promotions and other price factors).
84
-     * But seeing how these are REGs created from 3.1 attendee data, which have
85
-     * @param array $transaction
86
-     * @return array new line item ids
87
-     */
88
-    private function _insert_new_line_items($transaction, $old_attendee)
89
-    {
90
-        global $wpdb;
91
-        $regs_on_this_transaction = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".$this->_new_reg_table." WHERE TXN_ID=%d", $transaction['TXN_ID']), ARRAY_A);
92
-        $new_line_item_ids = array();
93
-        // create a totla line item
94
-        $total_line_item_id = $this->_insert_new_line_item(array(
95
-            'LIN_code'=>'total',
96
-            'TXN_ID'=>$transaction['TXN_ID'],
97
-            'LIN_name'=>  __("Total", "event_espresso"),
98
-            'LIN_total'=>$transaction['TXN_total'],
99
-            'LIN_type'=>'total',
100
-            'OBJ_ID'=>$transaction['TXN_ID'],
101
-            'OBJ_type'=>'Transaction'
102
-        ), $old_attendee);
103
-        $new_line_item_ids[] = $total_line_item_id;
104
-        // create a subtotal line item
105
-        $reg_total = 0;
106
-        foreach ($regs_on_this_transaction as $new_reg) {
107
-            $reg_total += floatval($new_reg['REG_final_price']);
108
-        }
109
-        $subtotal_line_item_id = $this->_insert_new_line_item(array(
110
-            'LIN_code'=>'sub-total',
111
-            'TXN_ID'=>$transaction['TXN_ID'],
112
-            'LIN_name'=>  __("Subtotal", "event_espresso"),
113
-            'LIN_total'=>$reg_total,
114
-            'LIN_parent'=>$total_line_item_id,
115
-            'LIN_type'=>'sub-total',
116
-        ), $old_attendee);
117
-        $new_line_item_ids[] = $subtotal_line_item_id;
118
-        // group REGs by TKT_ID
119
-        $regs_by_tkt = array();
120
-        foreach ($regs_on_this_transaction as $new_reg) {
121
-            $regs_by_tkt[ $new_reg['TKT_ID'] ][] = $new_reg;
122
-        }
81
+	/**
82
+	 * In 4.1, we'd normally need more info than just the registrations to make the line items. Ie, we'd need
83
+	 * the transaction, and tax prices at the time of registration. (And probably promotions and other price factors).
84
+	 * But seeing how these are REGs created from 3.1 attendee data, which have
85
+	 * @param array $transaction
86
+	 * @return array new line item ids
87
+	 */
88
+	private function _insert_new_line_items($transaction, $old_attendee)
89
+	{
90
+		global $wpdb;
91
+		$regs_on_this_transaction = $wpdb->get_results($wpdb->prepare("SELECT * FROM ".$this->_new_reg_table." WHERE TXN_ID=%d", $transaction['TXN_ID']), ARRAY_A);
92
+		$new_line_item_ids = array();
93
+		// create a totla line item
94
+		$total_line_item_id = $this->_insert_new_line_item(array(
95
+			'LIN_code'=>'total',
96
+			'TXN_ID'=>$transaction['TXN_ID'],
97
+			'LIN_name'=>  __("Total", "event_espresso"),
98
+			'LIN_total'=>$transaction['TXN_total'],
99
+			'LIN_type'=>'total',
100
+			'OBJ_ID'=>$transaction['TXN_ID'],
101
+			'OBJ_type'=>'Transaction'
102
+		), $old_attendee);
103
+		$new_line_item_ids[] = $total_line_item_id;
104
+		// create a subtotal line item
105
+		$reg_total = 0;
106
+		foreach ($regs_on_this_transaction as $new_reg) {
107
+			$reg_total += floatval($new_reg['REG_final_price']);
108
+		}
109
+		$subtotal_line_item_id = $this->_insert_new_line_item(array(
110
+			'LIN_code'=>'sub-total',
111
+			'TXN_ID'=>$transaction['TXN_ID'],
112
+			'LIN_name'=>  __("Subtotal", "event_espresso"),
113
+			'LIN_total'=>$reg_total,
114
+			'LIN_parent'=>$total_line_item_id,
115
+			'LIN_type'=>'sub-total',
116
+		), $old_attendee);
117
+		$new_line_item_ids[] = $subtotal_line_item_id;
118
+		// group REGs by TKT_ID
119
+		$regs_by_tkt = array();
120
+		foreach ($regs_on_this_transaction as $new_reg) {
121
+			$regs_by_tkt[ $new_reg['TKT_ID'] ][] = $new_reg;
122
+		}
123 123
         
124
-        // create individual line items
124
+		// create individual line items
125 125
         
126
-        foreach ($regs_by_tkt as $ticket_id => $regs) {
127
-            $count = count($regs);
128
-            $line_total = 0;
129
-            foreach ($regs as $new_reg) {
130
-                $line_total += $new_reg['REG_final_price'];
131
-            }
132
-            $a_reg = reset($regs);
133
-            $new_ticket = $this->_get_new_ticket_row($a_reg['TKT_ID']);
134
-            $reg_line_item_id = $this->_insert_new_line_item(array(
135
-                'LIN_code'=> md5('Ticket' . $ticket_id . time()),
136
-                'TXN_ID'=>$transaction['TXN_ID'],
137
-                'LIN_name'=>$new_ticket['TKT_name'],
138
-                'LIN_unit_price'=>$a_reg['REG_final_price'],
139
-                'LIN_is_taxable'=>false,
140
-                'LIN_total'=>$line_total,
141
-                'LIN_quantity'=>$count,
142
-                'LIN_parent'=>$subtotal_line_item_id,
143
-                'OBJ_ID'=>$ticket_id,
144
-                'OBJ_type'=>'Ticket'
145
-            ), $old_attendee);
146
-            $new_line_item_ids[] = $reg_line_item_id;
147
-        }
126
+		foreach ($regs_by_tkt as $ticket_id => $regs) {
127
+			$count = count($regs);
128
+			$line_total = 0;
129
+			foreach ($regs as $new_reg) {
130
+				$line_total += $new_reg['REG_final_price'];
131
+			}
132
+			$a_reg = reset($regs);
133
+			$new_ticket = $this->_get_new_ticket_row($a_reg['TKT_ID']);
134
+			$reg_line_item_id = $this->_insert_new_line_item(array(
135
+				'LIN_code'=> md5('Ticket' . $ticket_id . time()),
136
+				'TXN_ID'=>$transaction['TXN_ID'],
137
+				'LIN_name'=>$new_ticket['TKT_name'],
138
+				'LIN_unit_price'=>$a_reg['REG_final_price'],
139
+				'LIN_is_taxable'=>false,
140
+				'LIN_total'=>$line_total,
141
+				'LIN_quantity'=>$count,
142
+				'LIN_parent'=>$subtotal_line_item_id,
143
+				'OBJ_ID'=>$ticket_id,
144
+				'OBJ_type'=>'Ticket'
145
+			), $old_attendee);
146
+			$new_line_item_ids[] = $reg_line_item_id;
147
+		}
148 148
         
149 149
             
150 150
         
151
-        return $new_line_item_ids;
152
-    }
153
-    /**
154
-     * Gets the full ticket by ID
155
-     * @global type $wpdb
156
-     * @param type $new_ticket_id
157
-     * @return array
158
-     */
159
-    private function _get_new_ticket_row($new_ticket_id)
160
-    {
161
-        global $wpdb;
162
-        $ticket_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->prefix."esp_ticket WHERE TKT_ID=%d", $new_ticket_id), ARRAY_A);
163
-        return $ticket_row;
164
-    }
151
+		return $new_line_item_ids;
152
+	}
153
+	/**
154
+	 * Gets the full ticket by ID
155
+	 * @global type $wpdb
156
+	 * @param type $new_ticket_id
157
+	 * @return array
158
+	 */
159
+	private function _get_new_ticket_row($new_ticket_id)
160
+	{
161
+		global $wpdb;
162
+		$ticket_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM ".$wpdb->prefix."esp_ticket WHERE TKT_ID=%d", $new_ticket_id), ARRAY_A);
163
+		return $ticket_row;
164
+	}
165 165
     
166
-    private function _insert_new_line_item($cols_n_values, $old_attendee)
167
-    {
168
-        global $wpdb;
169
-        $default_cols_n_values = array(
170
-            'LIN_code'=>'',
171
-            'TXN_ID'=>0,
172
-            'LIN_name'=>'',
173
-            'LIN_desc'=>'',
174
-            'LIN_unit_price'=>0,
175
-            'LIN_percent'=>0,
176
-            'LIN_is_taxable'=>false,
177
-            'LIN_order'=>0,
178
-            'LIN_total'=>0,
179
-            'LIN_quantity'=>null,
180
-            'LIN_parent'=>0,
181
-            'LIN_type'=>'line-item',
182
-            'OBJ_ID'=>null,
183
-            'OBJ_type'=>null
184
-        );
185
-        $cols_n_values = array_merge($default_cols_n_values, $cols_n_values);
186
-            $datatypes = array(
187
-                '%s',// LIN_code
188
-                '%d',// TXN_ID
189
-                '%s',// LIN_name
190
-                '%s',// LIN_desc
191
-                '%f',// LIN_unit_price
192
-                '%f',// LIN_percent
193
-                '%d',// LIN_is_taxable
194
-                '%d',// LIN_order
195
-                '%f',// LIN_total
196
-                '%d',// LIN_quantity
197
-                '%d',// LIN_parent
198
-                '%s',// LIN_type
199
-                '%d',// OBJ_ID
200
-                '%s',// OBJ_type
201
-            );
202
-            $success = $wpdb->insert($this->_new_line_table, $cols_n_values, $datatypes);
203
-        if (! $success) {
204
-            $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_attendee, $this->_new_reg_table, $cols_n_values, $datatypes));
205
-            return 0;
206
-        }
207
-            return $wpdb->insert_id;
208
-    }
166
+	private function _insert_new_line_item($cols_n_values, $old_attendee)
167
+	{
168
+		global $wpdb;
169
+		$default_cols_n_values = array(
170
+			'LIN_code'=>'',
171
+			'TXN_ID'=>0,
172
+			'LIN_name'=>'',
173
+			'LIN_desc'=>'',
174
+			'LIN_unit_price'=>0,
175
+			'LIN_percent'=>0,
176
+			'LIN_is_taxable'=>false,
177
+			'LIN_order'=>0,
178
+			'LIN_total'=>0,
179
+			'LIN_quantity'=>null,
180
+			'LIN_parent'=>0,
181
+			'LIN_type'=>'line-item',
182
+			'OBJ_ID'=>null,
183
+			'OBJ_type'=>null
184
+		);
185
+		$cols_n_values = array_merge($default_cols_n_values, $cols_n_values);
186
+			$datatypes = array(
187
+				'%s',// LIN_code
188
+				'%d',// TXN_ID
189
+				'%s',// LIN_name
190
+				'%s',// LIN_desc
191
+				'%f',// LIN_unit_price
192
+				'%f',// LIN_percent
193
+				'%d',// LIN_is_taxable
194
+				'%d',// LIN_order
195
+				'%f',// LIN_total
196
+				'%d',// LIN_quantity
197
+				'%d',// LIN_parent
198
+				'%s',// LIN_type
199
+				'%d',// OBJ_ID
200
+				'%s',// OBJ_type
201
+			);
202
+			$success = $wpdb->insert($this->_new_line_table, $cols_n_values, $datatypes);
203
+		if (! $success) {
204
+			$this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_attendee, $this->_new_reg_table, $cols_n_values, $datatypes));
205
+			return 0;
206
+		}
207
+			return $wpdb->insert_id;
208
+	}
209 209
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
         $this->_old_table = $wpdb->prefix."events_attendee";
49 49
         $this->select_expression = 'att.*, e.event_status';
50 50
         $this->_extra_where_sql = ' AS att
51
-            INNER JOIN ' . $wpdb->prefix . 'events_detail AS e ON att.event_id=e.id
51
+            INNER JOIN ' . $wpdb->prefix.'events_detail AS e ON att.event_id=e.id
52 52
             WHERE e.event_status!="D"';
53 53
         $this->_new_transaction_table = $wpdb->prefix."esp_transaction";
54 54
         $this->_new_line_table = $wpdb->prefix."esp_line_item";
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
         // insert line items if its a primary id
62 62
         if (intval($old_row['is_primary'])) {
63 63
             $txn_id = $this->get_migration_script()->get_mapping_new_pk($this->_old_table, $old_row['id'], $this->_new_transaction_table);
64
-            if (! $txn_id) {
64
+            if ( ! $txn_id) {
65 65
                 $this->add_error(sprintf(__("Could not find the transaction for the 3.1 attendee %d from row %s", "event_espresso"), $old_row['id'], $this->_json_encode($old_row)));
66 66
                 return;
67 67
             }
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
         // group REGs by TKT_ID
119 119
         $regs_by_tkt = array();
120 120
         foreach ($regs_on_this_transaction as $new_reg) {
121
-            $regs_by_tkt[ $new_reg['TKT_ID'] ][] = $new_reg;
121
+            $regs_by_tkt[$new_reg['TKT_ID']][] = $new_reg;
122 122
         }
123 123
         
124 124
         // create individual line items
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
             $a_reg = reset($regs);
133 133
             $new_ticket = $this->_get_new_ticket_row($a_reg['TKT_ID']);
134 134
             $reg_line_item_id = $this->_insert_new_line_item(array(
135
-                'LIN_code'=> md5('Ticket' . $ticket_id . time()),
135
+                'LIN_code'=> md5('Ticket'.$ticket_id.time()),
136 136
                 'TXN_ID'=>$transaction['TXN_ID'],
137 137
                 'LIN_name'=>$new_ticket['TKT_name'],
138 138
                 'LIN_unit_price'=>$a_reg['REG_final_price'],
@@ -184,23 +184,23 @@  discard block
 block discarded – undo
184 184
         );
185 185
         $cols_n_values = array_merge($default_cols_n_values, $cols_n_values);
186 186
             $datatypes = array(
187
-                '%s',// LIN_code
188
-                '%d',// TXN_ID
189
-                '%s',// LIN_name
190
-                '%s',// LIN_desc
191
-                '%f',// LIN_unit_price
192
-                '%f',// LIN_percent
193
-                '%d',// LIN_is_taxable
194
-                '%d',// LIN_order
195
-                '%f',// LIN_total
196
-                '%d',// LIN_quantity
197
-                '%d',// LIN_parent
198
-                '%s',// LIN_type
199
-                '%d',// OBJ_ID
200
-                '%s',// OBJ_type
187
+                '%s', // LIN_code
188
+                '%d', // TXN_ID
189
+                '%s', // LIN_name
190
+                '%s', // LIN_desc
191
+                '%f', // LIN_unit_price
192
+                '%f', // LIN_percent
193
+                '%d', // LIN_is_taxable
194
+                '%d', // LIN_order
195
+                '%f', // LIN_total
196
+                '%d', // LIN_quantity
197
+                '%d', // LIN_parent
198
+                '%s', // LIN_type
199
+                '%d', // OBJ_ID
200
+                '%s', // OBJ_type
201 201
             );
202 202
             $success = $wpdb->insert($this->_new_line_table, $cols_n_values, $datatypes);
203
-        if (! $success) {
203
+        if ( ! $success) {
204 204
             $this->add_error($this->get_migration_script()->_create_error_message_for_db_insertion($this->_old_table, $old_attendee, $this->_new_reg_table, $cols_n_values, $datatypes));
205 205
             return 0;
206 206
         }
Please login to merge, or discard this patch.
core/services/assets/Registry.php 2 patches
Indentation   +584 added lines, -584 removed lines patch added patch discarded remove patch
@@ -23,595 +23,595 @@
 block discarded – undo
23 23
 class Registry
24 24
 {
25 25
 
26
-    const FILE_NAME_BUILD_MANIFEST = 'build-manifest.json';
27
-
28
-    /**
29
-     * @var AssetCollection $assets
30
-     */
31
-    protected $assets;
32
-
33
-    /**
34
-     * @var I18nRegistry
35
-     */
36
-    private $i18n_registry;
37
-
38
-    /**
39
-     * This holds the jsdata data object that will be exposed on pages that enqueue the `eejs-core` script.
40
-     *
41
-     * @var array
42
-     */
43
-    protected $jsdata = array();
44
-
45
-    /**
46
-     * This keeps track of all scripts with registered data.  It is used to prevent duplicate data objects setup in the
47
-     * page source.
48
-     *
49
-     * @var array
50
-     */
51
-    private $script_handles_with_data = array();
52
-
53
-
54
-    /**
55
-     * Holds the manifest data obtained from registered manifest files.
56
-     * Manifests are maps of asset chunk name to actual built asset file names.
57
-     * Shape of this array is:
58
-     * array(
59
-     *  'some_namespace_slug' => array(
60
-     *      'some_chunk_name' => array(
61
-     *          'js' => 'filename.js'
62
-     *          'css' => 'filename.js'
63
-     *      ),
64
-     *      'url_base' => 'https://baseurl.com/to/assets
65
-     *  )
66
-     * )
67
-     *
68
-     * @var array
69
-     */
70
-    private $manifest_data = array();
71
-
72
-
73
-    /**
74
-     * Registry constructor.
75
-     * Hooking into WP actions for script registry.
76
-     *
77
-     * @param AssetCollection $assets
78
-     * @param I18nRegistry    $i18n_registry
79
-     */
80
-    public function __construct(AssetCollection $assets, I18nRegistry $i18n_registry)
81
-    {
82
-        $this->assets = $assets;
83
-        $this->i18n_registry = $i18n_registry;
84
-        add_action('wp_enqueue_scripts', array($this, 'registerManifestFiles'), 1);
85
-        add_action('admin_enqueue_scripts', array($this, 'registerManifestFiles'), 1);
86
-        add_action('wp_enqueue_scripts', array($this, 'registerScriptsAndStyles'), 3);
87
-        add_action('admin_enqueue_scripts', array($this, 'registerScriptsAndStyles'), 3);
88
-        add_action('wp_enqueue_scripts', array($this, 'enqueueData'), 4);
89
-        add_action('admin_enqueue_scripts', array($this, 'enqueueData'), 4);
90
-        add_action('wp_print_footer_scripts', array($this, 'enqueueData'), 1);
91
-        add_action('admin_print_footer_scripts', array($this, 'enqueueData'), 1);
92
-    }
93
-
94
-
95
-    /**
96
-     * For classes that have Registry as a dependency, this provides a handy way to register script handles for i18n
97
-     * translation handling.
98
-     *
99
-     * @return I18nRegistry
100
-     */
101
-    public function getI18nRegistry()
102
-    {
103
-        return $this->i18n_registry;
104
-    }
105
-
106
-
107
-    /**
108
-     * Callback for the wp_enqueue_scripts actions used to register assets.
109
-     *
110
-     * @since 4.9.62.p
111
-     * @throws Exception
112
-     */
113
-    public function registerScriptsAndStyles()
114
-    {
115
-        try {
116
-            $this->registerScripts($this->assets->getJavascriptAssets());
117
-            $this->registerStyles($this->assets->getStylesheetAssets());
118
-        } catch (Exception $exception) {
119
-            new ExceptionStackTraceDisplay($exception);
120
-        }
121
-    }
122
-
123
-
124
-    /**
125
-     * Registers JS assets with WP core
126
-     *
127
-     * @since 4.9.62.p
128
-     * @param JavascriptAsset[] $scripts
129
-     * @throws AssetRegistrationException
130
-     * @throws InvalidDataTypeException
131
-     */
132
-    public function registerScripts(array $scripts)
133
-    {
134
-        foreach ($scripts as $script) {
135
-            // skip to next script if this has already been done
136
-            if ($script->isRegistered()) {
137
-                continue;
138
-            }
139
-            do_action(
140
-                'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
141
-                $script
142
-            );
143
-            $registered = wp_register_script(
144
-                $script->handle(),
145
-                $script->source(),
146
-                $script->dependencies(),
147
-                $script->version(),
148
-                $script->loadInFooter()
149
-            );
150
-            if (! $registered && $this->debug()) {
151
-                throw new AssetRegistrationException($script->handle());
152
-            }
153
-            $script->setRegistered($registered);
154
-            if ($script->requiresTranslation()) {
155
-                $this->registerTranslation($script->handle());
156
-            }
157
-            do_action(
158
-                'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__after_script',
159
-                $script
160
-            );
161
-        }
162
-    }
163
-
164
-
165
-    /**
166
-     * Registers CSS assets with WP core
167
-     *
168
-     * @since 4.9.62.p
169
-     * @param StylesheetAsset[] $styles
170
-     * @throws InvalidDataTypeException
171
-     */
172
-    public function registerStyles(array $styles)
173
-    {
174
-        foreach ($styles as $style) {
175
-            // skip to next style if this has already been done
176
-            if ($style->isRegistered()) {
177
-                continue;
178
-            }
179
-            do_action(
180
-                'AHEE__EventEspresso_core_services_assets_Registry__registerStyles__before_style',
181
-                $style
182
-            );
183
-            wp_register_style(
184
-                $style->handle(),
185
-                $style->source(),
186
-                $style->dependencies(),
187
-                $style->version(),
188
-                $style->media()
189
-            );
190
-            $style->setRegistered();
191
-            do_action(
192
-                'AHEE__EventEspresso_core_services_assets_Registry__registerStyles__after_style',
193
-                $style
194
-            );
195
-        }
196
-    }
197
-
198
-
199
-    /**
200
-     * Call back for the script print in frontend and backend.
201
-     * Used to call wp_localize_scripts so that data can be added throughout the runtime until this later hook point.
202
-     *
203
-     * @since 4.9.31.rc.015
204
-     */
205
-    public function enqueueData()
206
-    {
207
-        $this->removeAlreadyRegisteredDataForScriptHandles();
208
-        wp_add_inline_script(
209
-            'eejs-core',
210
-            'var eejsdata=' . wp_json_encode(array('data' => $this->jsdata)),
211
-            'before'
212
-        );
213
-        $scripts = $this->assets->getJavascriptAssetsWithData();
214
-        foreach ($scripts as $script) {
215
-            $this->addRegisteredScriptHandlesWithData($script->handle());
216
-            if ($script->hasInlineDataCallback()) {
217
-                $localize = $script->inlineDataCallback();
218
-                $localize();
219
-            }
220
-        }
221
-    }
222
-
223
-
224
-    /**
225
-     * Used to add data to eejs.data object.
226
-     * Note:  Overriding existing data is not allowed.
227
-     * Data will be accessible as a javascript object when you list `eejs-core` as a dependency for your javascript.
228
-     * If the data you add is something like this:
229
-     *  $this->addData( 'my_plugin_data', array( 'foo' => 'gar' ) );
230
-     * It will be exposed in the page source as:
231
-     *  eejs.data.my_plugin_data.foo == gar
232
-     *
233
-     * @param string       $key   Key used to access your data
234
-     * @param string|array $value Value to attach to key
235
-     * @throws InvalidArgumentException
236
-     */
237
-    public function addData($key, $value)
238
-    {
239
-        if ($this->verifyDataNotExisting($key)) {
240
-            $this->jsdata[ $key ] = $value;
241
-        }
242
-    }
243
-
244
-
245
-    /**
246
-     * Similar to addData except this allows for users to push values to an existing key where the values on key are
247
-     * elements in an array.
248
-     *
249
-     * When you use this method, the value you include will be merged with the array on $key.
250
-     * So if the $key was 'test' and you added a value of ['my_data'] then it would be represented in the javascript
251
-     * object like this, eejs.data.test = [ my_data,
252
-     * ]
253
-     * If there has already been a scalar value attached to the data object given key (via addData for instance), then
254
-     * this will throw an exception.
255
-     *
256
-     * Caution: Only add data using this method if you are okay with the potential for additional data added on the same
257
-     * key potentially overriding the existing data on merge (specifically with associative arrays).
258
-     *
259
-     * @param string       $key   Key to attach data to.
260
-     * @param string|array $value Value being registered.
261
-     * @throws InvalidArgumentException
262
-     */
263
-    public function pushData($key, $value)
264
-    {
265
-        if (isset($this->jsdata[ $key ])
266
-            && ! is_array($this->jsdata[ $key ])
267
-        ) {
268
-            if (! $this->debug()) {
269
-                return;
270
-            }
271
-            throw new InvalidArgumentException(
272
-                sprintf(
273
-                    __(
274
-                        'The value for %1$s is already set and it is not an array. The %2$s method can only be used to
26
+	const FILE_NAME_BUILD_MANIFEST = 'build-manifest.json';
27
+
28
+	/**
29
+	 * @var AssetCollection $assets
30
+	 */
31
+	protected $assets;
32
+
33
+	/**
34
+	 * @var I18nRegistry
35
+	 */
36
+	private $i18n_registry;
37
+
38
+	/**
39
+	 * This holds the jsdata data object that will be exposed on pages that enqueue the `eejs-core` script.
40
+	 *
41
+	 * @var array
42
+	 */
43
+	protected $jsdata = array();
44
+
45
+	/**
46
+	 * This keeps track of all scripts with registered data.  It is used to prevent duplicate data objects setup in the
47
+	 * page source.
48
+	 *
49
+	 * @var array
50
+	 */
51
+	private $script_handles_with_data = array();
52
+
53
+
54
+	/**
55
+	 * Holds the manifest data obtained from registered manifest files.
56
+	 * Manifests are maps of asset chunk name to actual built asset file names.
57
+	 * Shape of this array is:
58
+	 * array(
59
+	 *  'some_namespace_slug' => array(
60
+	 *      'some_chunk_name' => array(
61
+	 *          'js' => 'filename.js'
62
+	 *          'css' => 'filename.js'
63
+	 *      ),
64
+	 *      'url_base' => 'https://baseurl.com/to/assets
65
+	 *  )
66
+	 * )
67
+	 *
68
+	 * @var array
69
+	 */
70
+	private $manifest_data = array();
71
+
72
+
73
+	/**
74
+	 * Registry constructor.
75
+	 * Hooking into WP actions for script registry.
76
+	 *
77
+	 * @param AssetCollection $assets
78
+	 * @param I18nRegistry    $i18n_registry
79
+	 */
80
+	public function __construct(AssetCollection $assets, I18nRegistry $i18n_registry)
81
+	{
82
+		$this->assets = $assets;
83
+		$this->i18n_registry = $i18n_registry;
84
+		add_action('wp_enqueue_scripts', array($this, 'registerManifestFiles'), 1);
85
+		add_action('admin_enqueue_scripts', array($this, 'registerManifestFiles'), 1);
86
+		add_action('wp_enqueue_scripts', array($this, 'registerScriptsAndStyles'), 3);
87
+		add_action('admin_enqueue_scripts', array($this, 'registerScriptsAndStyles'), 3);
88
+		add_action('wp_enqueue_scripts', array($this, 'enqueueData'), 4);
89
+		add_action('admin_enqueue_scripts', array($this, 'enqueueData'), 4);
90
+		add_action('wp_print_footer_scripts', array($this, 'enqueueData'), 1);
91
+		add_action('admin_print_footer_scripts', array($this, 'enqueueData'), 1);
92
+	}
93
+
94
+
95
+	/**
96
+	 * For classes that have Registry as a dependency, this provides a handy way to register script handles for i18n
97
+	 * translation handling.
98
+	 *
99
+	 * @return I18nRegistry
100
+	 */
101
+	public function getI18nRegistry()
102
+	{
103
+		return $this->i18n_registry;
104
+	}
105
+
106
+
107
+	/**
108
+	 * Callback for the wp_enqueue_scripts actions used to register assets.
109
+	 *
110
+	 * @since 4.9.62.p
111
+	 * @throws Exception
112
+	 */
113
+	public function registerScriptsAndStyles()
114
+	{
115
+		try {
116
+			$this->registerScripts($this->assets->getJavascriptAssets());
117
+			$this->registerStyles($this->assets->getStylesheetAssets());
118
+		} catch (Exception $exception) {
119
+			new ExceptionStackTraceDisplay($exception);
120
+		}
121
+	}
122
+
123
+
124
+	/**
125
+	 * Registers JS assets with WP core
126
+	 *
127
+	 * @since 4.9.62.p
128
+	 * @param JavascriptAsset[] $scripts
129
+	 * @throws AssetRegistrationException
130
+	 * @throws InvalidDataTypeException
131
+	 */
132
+	public function registerScripts(array $scripts)
133
+	{
134
+		foreach ($scripts as $script) {
135
+			// skip to next script if this has already been done
136
+			if ($script->isRegistered()) {
137
+				continue;
138
+			}
139
+			do_action(
140
+				'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__before_script',
141
+				$script
142
+			);
143
+			$registered = wp_register_script(
144
+				$script->handle(),
145
+				$script->source(),
146
+				$script->dependencies(),
147
+				$script->version(),
148
+				$script->loadInFooter()
149
+			);
150
+			if (! $registered && $this->debug()) {
151
+				throw new AssetRegistrationException($script->handle());
152
+			}
153
+			$script->setRegistered($registered);
154
+			if ($script->requiresTranslation()) {
155
+				$this->registerTranslation($script->handle());
156
+			}
157
+			do_action(
158
+				'AHEE__EventEspresso_core_services_assets_Registry__registerScripts__after_script',
159
+				$script
160
+			);
161
+		}
162
+	}
163
+
164
+
165
+	/**
166
+	 * Registers CSS assets with WP core
167
+	 *
168
+	 * @since 4.9.62.p
169
+	 * @param StylesheetAsset[] $styles
170
+	 * @throws InvalidDataTypeException
171
+	 */
172
+	public function registerStyles(array $styles)
173
+	{
174
+		foreach ($styles as $style) {
175
+			// skip to next style if this has already been done
176
+			if ($style->isRegistered()) {
177
+				continue;
178
+			}
179
+			do_action(
180
+				'AHEE__EventEspresso_core_services_assets_Registry__registerStyles__before_style',
181
+				$style
182
+			);
183
+			wp_register_style(
184
+				$style->handle(),
185
+				$style->source(),
186
+				$style->dependencies(),
187
+				$style->version(),
188
+				$style->media()
189
+			);
190
+			$style->setRegistered();
191
+			do_action(
192
+				'AHEE__EventEspresso_core_services_assets_Registry__registerStyles__after_style',
193
+				$style
194
+			);
195
+		}
196
+	}
197
+
198
+
199
+	/**
200
+	 * Call back for the script print in frontend and backend.
201
+	 * Used to call wp_localize_scripts so that data can be added throughout the runtime until this later hook point.
202
+	 *
203
+	 * @since 4.9.31.rc.015
204
+	 */
205
+	public function enqueueData()
206
+	{
207
+		$this->removeAlreadyRegisteredDataForScriptHandles();
208
+		wp_add_inline_script(
209
+			'eejs-core',
210
+			'var eejsdata=' . wp_json_encode(array('data' => $this->jsdata)),
211
+			'before'
212
+		);
213
+		$scripts = $this->assets->getJavascriptAssetsWithData();
214
+		foreach ($scripts as $script) {
215
+			$this->addRegisteredScriptHandlesWithData($script->handle());
216
+			if ($script->hasInlineDataCallback()) {
217
+				$localize = $script->inlineDataCallback();
218
+				$localize();
219
+			}
220
+		}
221
+	}
222
+
223
+
224
+	/**
225
+	 * Used to add data to eejs.data object.
226
+	 * Note:  Overriding existing data is not allowed.
227
+	 * Data will be accessible as a javascript object when you list `eejs-core` as a dependency for your javascript.
228
+	 * If the data you add is something like this:
229
+	 *  $this->addData( 'my_plugin_data', array( 'foo' => 'gar' ) );
230
+	 * It will be exposed in the page source as:
231
+	 *  eejs.data.my_plugin_data.foo == gar
232
+	 *
233
+	 * @param string       $key   Key used to access your data
234
+	 * @param string|array $value Value to attach to key
235
+	 * @throws InvalidArgumentException
236
+	 */
237
+	public function addData($key, $value)
238
+	{
239
+		if ($this->verifyDataNotExisting($key)) {
240
+			$this->jsdata[ $key ] = $value;
241
+		}
242
+	}
243
+
244
+
245
+	/**
246
+	 * Similar to addData except this allows for users to push values to an existing key where the values on key are
247
+	 * elements in an array.
248
+	 *
249
+	 * When you use this method, the value you include will be merged with the array on $key.
250
+	 * So if the $key was 'test' and you added a value of ['my_data'] then it would be represented in the javascript
251
+	 * object like this, eejs.data.test = [ my_data,
252
+	 * ]
253
+	 * If there has already been a scalar value attached to the data object given key (via addData for instance), then
254
+	 * this will throw an exception.
255
+	 *
256
+	 * Caution: Only add data using this method if you are okay with the potential for additional data added on the same
257
+	 * key potentially overriding the existing data on merge (specifically with associative arrays).
258
+	 *
259
+	 * @param string       $key   Key to attach data to.
260
+	 * @param string|array $value Value being registered.
261
+	 * @throws InvalidArgumentException
262
+	 */
263
+	public function pushData($key, $value)
264
+	{
265
+		if (isset($this->jsdata[ $key ])
266
+			&& ! is_array($this->jsdata[ $key ])
267
+		) {
268
+			if (! $this->debug()) {
269
+				return;
270
+			}
271
+			throw new InvalidArgumentException(
272
+				sprintf(
273
+					__(
274
+						'The value for %1$s is already set and it is not an array. The %2$s method can only be used to
275 275
                          push values to this data element when it is an array.',
276
-                        'event_espresso'
277
-                    ),
278
-                    $key,
279
-                    __METHOD__
280
-                )
281
-            );
282
-        }
283
-        if ( ! isset( $this->jsdata[ $key ] ) ) {
284
-            $this->jsdata[ $key ] = is_array($value) ? $value : [$value];
285
-        } else {
286
-            $this->jsdata[ $key ] = array_merge( $this->jsdata[$key], (array) $value);
287
-        }
288
-    }
289
-
290
-
291
-    /**
292
-     * Used to set content used by javascript for a template.
293
-     * Note: Overrides of existing registered templates are not allowed.
294
-     *
295
-     * @param string $template_reference
296
-     * @param string $template_content
297
-     * @throws InvalidArgumentException
298
-     */
299
-    public function addTemplate($template_reference, $template_content)
300
-    {
301
-        if (! isset($this->jsdata['templates'])) {
302
-            $this->jsdata['templates'] = array();
303
-        }
304
-        //no overrides allowed.
305
-        if (isset($this->jsdata['templates'][ $template_reference ])) {
306
-            if (! $this->debug()) {
307
-                return;
308
-            }
309
-            throw new InvalidArgumentException(
310
-                sprintf(
311
-                    __(
312
-                        'The %1$s key already exists for the templates array in the js data array.  No overrides are allowed.',
313
-                        'event_espresso'
314
-                    ),
315
-                    $template_reference
316
-                )
317
-            );
318
-        }
319
-        $this->jsdata['templates'][ $template_reference ] = $template_content;
320
-    }
321
-
322
-
323
-    /**
324
-     * Retrieve the template content already registered for the given reference.
325
-     *
326
-     * @param string $template_reference
327
-     * @return string
328
-     */
329
-    public function getTemplate($template_reference)
330
-    {
331
-        return isset($this->jsdata['templates'][ $template_reference ])
332
-            ? $this->jsdata['templates'][ $template_reference ]
333
-            : '';
334
-    }
335
-
336
-
337
-    /**
338
-     * Retrieve registered data.
339
-     *
340
-     * @param string $key Name of key to attach data to.
341
-     * @return mixed                If there is no for the given key, then false is returned.
342
-     */
343
-    public function getData($key)
344
-    {
345
-        return isset($this->jsdata[ $key ])
346
-            ? $this->jsdata[ $key ]
347
-            : false;
348
-    }
349
-
350
-
351
-    /**
352
-     * Verifies whether the given data exists already on the jsdata array.
353
-     * Overriding data is not allowed.
354
-     *
355
-     * @param string $key Index for data.
356
-     * @return bool        If valid then return true.
357
-     * @throws InvalidArgumentException if data already exists.
358
-     */
359
-    protected function verifyDataNotExisting($key)
360
-    {
361
-        if (isset($this->jsdata[ $key ])) {
362
-            if (! $this->debug()) {
363
-                return false;
364
-            }
365
-            if (is_array($this->jsdata[ $key ])) {
366
-                throw new InvalidArgumentException(
367
-                    sprintf(
368
-                        __(
369
-                            'The value for %1$s already exists in the Registry::eejs object.
276
+						'event_espresso'
277
+					),
278
+					$key,
279
+					__METHOD__
280
+				)
281
+			);
282
+		}
283
+		if ( ! isset( $this->jsdata[ $key ] ) ) {
284
+			$this->jsdata[ $key ] = is_array($value) ? $value : [$value];
285
+		} else {
286
+			$this->jsdata[ $key ] = array_merge( $this->jsdata[$key], (array) $value);
287
+		}
288
+	}
289
+
290
+
291
+	/**
292
+	 * Used to set content used by javascript for a template.
293
+	 * Note: Overrides of existing registered templates are not allowed.
294
+	 *
295
+	 * @param string $template_reference
296
+	 * @param string $template_content
297
+	 * @throws InvalidArgumentException
298
+	 */
299
+	public function addTemplate($template_reference, $template_content)
300
+	{
301
+		if (! isset($this->jsdata['templates'])) {
302
+			$this->jsdata['templates'] = array();
303
+		}
304
+		//no overrides allowed.
305
+		if (isset($this->jsdata['templates'][ $template_reference ])) {
306
+			if (! $this->debug()) {
307
+				return;
308
+			}
309
+			throw new InvalidArgumentException(
310
+				sprintf(
311
+					__(
312
+						'The %1$s key already exists for the templates array in the js data array.  No overrides are allowed.',
313
+						'event_espresso'
314
+					),
315
+					$template_reference
316
+				)
317
+			);
318
+		}
319
+		$this->jsdata['templates'][ $template_reference ] = $template_content;
320
+	}
321
+
322
+
323
+	/**
324
+	 * Retrieve the template content already registered for the given reference.
325
+	 *
326
+	 * @param string $template_reference
327
+	 * @return string
328
+	 */
329
+	public function getTemplate($template_reference)
330
+	{
331
+		return isset($this->jsdata['templates'][ $template_reference ])
332
+			? $this->jsdata['templates'][ $template_reference ]
333
+			: '';
334
+	}
335
+
336
+
337
+	/**
338
+	 * Retrieve registered data.
339
+	 *
340
+	 * @param string $key Name of key to attach data to.
341
+	 * @return mixed                If there is no for the given key, then false is returned.
342
+	 */
343
+	public function getData($key)
344
+	{
345
+		return isset($this->jsdata[ $key ])
346
+			? $this->jsdata[ $key ]
347
+			: false;
348
+	}
349
+
350
+
351
+	/**
352
+	 * Verifies whether the given data exists already on the jsdata array.
353
+	 * Overriding data is not allowed.
354
+	 *
355
+	 * @param string $key Index for data.
356
+	 * @return bool        If valid then return true.
357
+	 * @throws InvalidArgumentException if data already exists.
358
+	 */
359
+	protected function verifyDataNotExisting($key)
360
+	{
361
+		if (isset($this->jsdata[ $key ])) {
362
+			if (! $this->debug()) {
363
+				return false;
364
+			}
365
+			if (is_array($this->jsdata[ $key ])) {
366
+				throw new InvalidArgumentException(
367
+					sprintf(
368
+						__(
369
+							'The value for %1$s already exists in the Registry::eejs object.
370 370
                             Overrides are not allowed. Since the value of this data is an array, you may want to use the
371 371
                             %2$s method to push your value to the array.',
372
-                            'event_espresso'
373
-                        ),
374
-                        $key,
375
-                        'pushData()'
376
-                    )
377
-                );
378
-            }
379
-            throw new InvalidArgumentException(
380
-                sprintf(
381
-                    __(
382
-                        'The value for %1$s already exists in the Registry::eejs object. Overrides are not
372
+							'event_espresso'
373
+						),
374
+						$key,
375
+						'pushData()'
376
+					)
377
+				);
378
+			}
379
+			throw new InvalidArgumentException(
380
+				sprintf(
381
+					__(
382
+						'The value for %1$s already exists in the Registry::eejs object. Overrides are not
383 383
                         allowed.  Consider attaching your value to a different key',
384
-                        'event_espresso'
385
-                    ),
386
-                    $key
387
-                )
388
-            );
389
-        }
390
-        return true;
391
-    }
392
-
393
-
394
-    /**
395
-     * Get the actual asset path for asset manifests.
396
-     * If there is no asset path found for the given $chunk_name, then the $chunk_name is returned.
397
-     *
398
-     * @param string $namespace  The namespace associated with the manifest file hosting the map of chunk_name to actual
399
-     *                           asset file location.
400
-     * @param string $chunk_name
401
-     * @param string $asset_type
402
-     * @return string
403
-     * @since 4.9.59.p
404
-     */
405
-    public function getAssetUrl($namespace, $chunk_name, $asset_type)
406
-    {
407
-        $url = isset(
408
-            $this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ],
409
-            $this->manifest_data[ $namespace ]['url_base']
410
-        )
411
-            ? $this->manifest_data[ $namespace ]['url_base']
412
-              . $this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ]
413
-            : $chunk_name;
414
-
415
-        return apply_filters(
416
-            'FHEE__EventEspresso_core_services_assets_Registry__getAssetUrl',
417
-            $url,
418
-            $namespace,
419
-            $chunk_name,
420
-            $asset_type
421
-        );
422
-    }
423
-
424
-
425
-
426
-    /**
427
-     * Return the url to a js file for the given namespace and chunk name.
428
-     *
429
-     * @param string $namespace
430
-     * @param string $chunk_name
431
-     * @return string
432
-     */
433
-    public function getJsUrl($namespace, $chunk_name)
434
-    {
435
-        return $this->getAssetUrl($namespace, $chunk_name, Asset::TYPE_JS);
436
-    }
437
-
438
-
439
-    /**
440
-     * Return the url to a css file for the given namespace and chunk name.
441
-     *
442
-     * @param string $namespace
443
-     * @param string $chunk_name
444
-     * @return string
445
-     */
446
-    public function getCssUrl($namespace, $chunk_name)
447
-    {
448
-        return $this->getAssetUrl($namespace, $chunk_name, Asset::TYPE_CSS);
449
-    }
450
-
451
-
452
-    /**
453
-     * @since 4.9.62.p
454
-     * @throws InvalidArgumentException
455
-     * @throws InvalidFilePathException
456
-     */
457
-    public function registerManifestFiles()
458
-    {
459
-        $manifest_files = $this->assets->getManifestFiles();
460
-        foreach ($manifest_files as $manifest_file) {
461
-            $this->registerManifestFile(
462
-                $manifest_file->assetNamespace(),
463
-                $manifest_file->urlBase(),
464
-                $manifest_file->filepath() . Registry::FILE_NAME_BUILD_MANIFEST
465
-            );
466
-        }
467
-    }
468
-
469
-
470
-    /**
471
-     * Used to register a js/css manifest file with the registered_manifest_files property.
472
-     *
473
-     * @param string $namespace     Provided to associate the manifest file with a specific namespace.
474
-     * @param string $url_base      The url base for the manifest file location.
475
-     * @param string $manifest_file The absolute path to the manifest file.
476
-     * @throws InvalidArgumentException
477
-     * @throws InvalidFilePathException
478
-     * @since 4.9.59.p
479
-     */
480
-    public function registerManifestFile($namespace, $url_base, $manifest_file)
481
-    {
482
-        if (isset($this->manifest_data[ $namespace ])) {
483
-            if (! $this->debug()) {
484
-                return;
485
-            }
486
-            throw new InvalidArgumentException(
487
-                sprintf(
488
-                    esc_html__(
489
-                        'The namespace for this manifest file has already been registered, choose a namespace other than %s',
490
-                        'event_espresso'
491
-                    ),
492
-                    $namespace
493
-                )
494
-            );
495
-        }
496
-        if (filter_var($url_base, FILTER_VALIDATE_URL) === false) {
497
-            if (is_admin()) {
498
-                EE_Error::add_error(
499
-                    sprintf(
500
-                        esc_html__(
501
-                            'The url given for %1$s assets is invalid.  The url provided was: "%2$s". This usually happens when another plugin or theme on a site is using the "%3$s" filter or has an invalid url set for the "%4$s" constant',
502
-                            'event_espresso'
503
-                        ),
504
-                        'Event Espresso',
505
-                        $url_base,
506
-                        'plugins_url',
507
-                        'WP_PLUGIN_URL'
508
-                    ),
509
-                    __FILE__,
510
-                    __FUNCTION__,
511
-                    __LINE__
512
-                );
513
-            }
514
-            return;
515
-        }
516
-        $this->manifest_data[ $namespace ] = $this->decodeManifestFile($manifest_file);
517
-        if (! isset($this->manifest_data[ $namespace ]['url_base'])) {
518
-            $this->manifest_data[ $namespace ]['url_base'] = trailingslashit($url_base);
519
-        }
520
-    }
521
-
522
-
523
-    /**
524
-     * Decodes json from the provided manifest file.
525
-     *
526
-     * @since 4.9.59.p
527
-     * @param string $manifest_file Path to manifest file.
528
-     * @return array
529
-     * @throws InvalidFilePathException
530
-     */
531
-    private function decodeManifestFile($manifest_file)
532
-    {
533
-        if (! file_exists($manifest_file)) {
534
-            throw new InvalidFilePathException($manifest_file);
535
-        }
536
-        return json_decode(file_get_contents($manifest_file), true);
537
-    }
538
-
539
-
540
-    /**
541
-     * This is used to set registered script handles that have data.
542
-     *
543
-     * @param string $script_handle
544
-     */
545
-    private function addRegisteredScriptHandlesWithData($script_handle)
546
-    {
547
-        $this->script_handles_with_data[ $script_handle ] = $script_handle;
548
-    }
549
-
550
-
551
-    /**i
384
+						'event_espresso'
385
+					),
386
+					$key
387
+				)
388
+			);
389
+		}
390
+		return true;
391
+	}
392
+
393
+
394
+	/**
395
+	 * Get the actual asset path for asset manifests.
396
+	 * If there is no asset path found for the given $chunk_name, then the $chunk_name is returned.
397
+	 *
398
+	 * @param string $namespace  The namespace associated with the manifest file hosting the map of chunk_name to actual
399
+	 *                           asset file location.
400
+	 * @param string $chunk_name
401
+	 * @param string $asset_type
402
+	 * @return string
403
+	 * @since 4.9.59.p
404
+	 */
405
+	public function getAssetUrl($namespace, $chunk_name, $asset_type)
406
+	{
407
+		$url = isset(
408
+			$this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ],
409
+			$this->manifest_data[ $namespace ]['url_base']
410
+		)
411
+			? $this->manifest_data[ $namespace ]['url_base']
412
+			  . $this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ]
413
+			: $chunk_name;
414
+
415
+		return apply_filters(
416
+			'FHEE__EventEspresso_core_services_assets_Registry__getAssetUrl',
417
+			$url,
418
+			$namespace,
419
+			$chunk_name,
420
+			$asset_type
421
+		);
422
+	}
423
+
424
+
425
+
426
+	/**
427
+	 * Return the url to a js file for the given namespace and chunk name.
428
+	 *
429
+	 * @param string $namespace
430
+	 * @param string $chunk_name
431
+	 * @return string
432
+	 */
433
+	public function getJsUrl($namespace, $chunk_name)
434
+	{
435
+		return $this->getAssetUrl($namespace, $chunk_name, Asset::TYPE_JS);
436
+	}
437
+
438
+
439
+	/**
440
+	 * Return the url to a css file for the given namespace and chunk name.
441
+	 *
442
+	 * @param string $namespace
443
+	 * @param string $chunk_name
444
+	 * @return string
445
+	 */
446
+	public function getCssUrl($namespace, $chunk_name)
447
+	{
448
+		return $this->getAssetUrl($namespace, $chunk_name, Asset::TYPE_CSS);
449
+	}
450
+
451
+
452
+	/**
453
+	 * @since 4.9.62.p
454
+	 * @throws InvalidArgumentException
455
+	 * @throws InvalidFilePathException
456
+	 */
457
+	public function registerManifestFiles()
458
+	{
459
+		$manifest_files = $this->assets->getManifestFiles();
460
+		foreach ($manifest_files as $manifest_file) {
461
+			$this->registerManifestFile(
462
+				$manifest_file->assetNamespace(),
463
+				$manifest_file->urlBase(),
464
+				$manifest_file->filepath() . Registry::FILE_NAME_BUILD_MANIFEST
465
+			);
466
+		}
467
+	}
468
+
469
+
470
+	/**
471
+	 * Used to register a js/css manifest file with the registered_manifest_files property.
472
+	 *
473
+	 * @param string $namespace     Provided to associate the manifest file with a specific namespace.
474
+	 * @param string $url_base      The url base for the manifest file location.
475
+	 * @param string $manifest_file The absolute path to the manifest file.
476
+	 * @throws InvalidArgumentException
477
+	 * @throws InvalidFilePathException
478
+	 * @since 4.9.59.p
479
+	 */
480
+	public function registerManifestFile($namespace, $url_base, $manifest_file)
481
+	{
482
+		if (isset($this->manifest_data[ $namespace ])) {
483
+			if (! $this->debug()) {
484
+				return;
485
+			}
486
+			throw new InvalidArgumentException(
487
+				sprintf(
488
+					esc_html__(
489
+						'The namespace for this manifest file has already been registered, choose a namespace other than %s',
490
+						'event_espresso'
491
+					),
492
+					$namespace
493
+				)
494
+			);
495
+		}
496
+		if (filter_var($url_base, FILTER_VALIDATE_URL) === false) {
497
+			if (is_admin()) {
498
+				EE_Error::add_error(
499
+					sprintf(
500
+						esc_html__(
501
+							'The url given for %1$s assets is invalid.  The url provided was: "%2$s". This usually happens when another plugin or theme on a site is using the "%3$s" filter or has an invalid url set for the "%4$s" constant',
502
+							'event_espresso'
503
+						),
504
+						'Event Espresso',
505
+						$url_base,
506
+						'plugins_url',
507
+						'WP_PLUGIN_URL'
508
+					),
509
+					__FILE__,
510
+					__FUNCTION__,
511
+					__LINE__
512
+				);
513
+			}
514
+			return;
515
+		}
516
+		$this->manifest_data[ $namespace ] = $this->decodeManifestFile($manifest_file);
517
+		if (! isset($this->manifest_data[ $namespace ]['url_base'])) {
518
+			$this->manifest_data[ $namespace ]['url_base'] = trailingslashit($url_base);
519
+		}
520
+	}
521
+
522
+
523
+	/**
524
+	 * Decodes json from the provided manifest file.
525
+	 *
526
+	 * @since 4.9.59.p
527
+	 * @param string $manifest_file Path to manifest file.
528
+	 * @return array
529
+	 * @throws InvalidFilePathException
530
+	 */
531
+	private function decodeManifestFile($manifest_file)
532
+	{
533
+		if (! file_exists($manifest_file)) {
534
+			throw new InvalidFilePathException($manifest_file);
535
+		}
536
+		return json_decode(file_get_contents($manifest_file), true);
537
+	}
538
+
539
+
540
+	/**
541
+	 * This is used to set registered script handles that have data.
542
+	 *
543
+	 * @param string $script_handle
544
+	 */
545
+	private function addRegisteredScriptHandlesWithData($script_handle)
546
+	{
547
+		$this->script_handles_with_data[ $script_handle ] = $script_handle;
548
+	}
549
+
550
+
551
+	/**i
552 552
      * Checks WP_Scripts for all of each script handle registered internally as having data and unsets from the
553 553
      * Dependency stored in WP_Scripts if its set.
554 554
      */
555
-    private function removeAlreadyRegisteredDataForScriptHandles()
556
-    {
557
-        if (empty($this->script_handles_with_data)) {
558
-            return;
559
-        }
560
-        foreach ($this->script_handles_with_data as $script_handle) {
561
-            $this->removeAlreadyRegisteredDataForScriptHandle($script_handle);
562
-        }
563
-    }
564
-
565
-
566
-    /**
567
-     * Removes any data dependency registered in WP_Scripts if its set.
568
-     *
569
-     * @param string $script_handle
570
-     */
571
-    private function removeAlreadyRegisteredDataForScriptHandle($script_handle)
572
-    {
573
-        if (isset($this->script_handles_with_data[ $script_handle ])) {
574
-            global $wp_scripts;
575
-            $unset_handle = false;
576
-            if ($wp_scripts->get_data($script_handle, 'data')) {
577
-                unset($wp_scripts->registered[ $script_handle ]->extra['data']);
578
-                $unset_handle = true;
579
-            }
580
-            //deal with inline_scripts
581
-            if ($wp_scripts->get_data($script_handle, 'before')) {
582
-                unset($wp_scripts->registered[ $script_handle ]->extra['before']);
583
-                $unset_handle = true;
584
-            }
585
-            if ($wp_scripts->get_data($script_handle, 'after')) {
586
-                unset($wp_scripts->registered[ $script_handle ]->extra['after']);
587
-            }
588
-            if ($unset_handle) {
589
-                unset($this->script_handles_with_data[ $script_handle ]);
590
-            }
591
-        }
592
-    }
593
-
594
-
595
-    /**
596
-     * register translations for a registered script
597
-     *
598
-     * @param string $handle
599
-     */
600
-    public function registerTranslation($handle)
601
-    {
602
-        $this->i18n_registry->registerScriptI18n($handle);
603
-    }
604
-
605
-
606
-    /**
607
-     * @since 4.9.63.p
608
-     * @return bool
609
-     */
610
-    private function debug()
611
-    {
612
-        return apply_filters(
613
-            'FHEE__EventEspresso_core_services_assets_Registry__debug',
614
-            defined('EE_DEBUG') && EE_DEBUG
615
-        );
616
-    }
555
+	private function removeAlreadyRegisteredDataForScriptHandles()
556
+	{
557
+		if (empty($this->script_handles_with_data)) {
558
+			return;
559
+		}
560
+		foreach ($this->script_handles_with_data as $script_handle) {
561
+			$this->removeAlreadyRegisteredDataForScriptHandle($script_handle);
562
+		}
563
+	}
564
+
565
+
566
+	/**
567
+	 * Removes any data dependency registered in WP_Scripts if its set.
568
+	 *
569
+	 * @param string $script_handle
570
+	 */
571
+	private function removeAlreadyRegisteredDataForScriptHandle($script_handle)
572
+	{
573
+		if (isset($this->script_handles_with_data[ $script_handle ])) {
574
+			global $wp_scripts;
575
+			$unset_handle = false;
576
+			if ($wp_scripts->get_data($script_handle, 'data')) {
577
+				unset($wp_scripts->registered[ $script_handle ]->extra['data']);
578
+				$unset_handle = true;
579
+			}
580
+			//deal with inline_scripts
581
+			if ($wp_scripts->get_data($script_handle, 'before')) {
582
+				unset($wp_scripts->registered[ $script_handle ]->extra['before']);
583
+				$unset_handle = true;
584
+			}
585
+			if ($wp_scripts->get_data($script_handle, 'after')) {
586
+				unset($wp_scripts->registered[ $script_handle ]->extra['after']);
587
+			}
588
+			if ($unset_handle) {
589
+				unset($this->script_handles_with_data[ $script_handle ]);
590
+			}
591
+		}
592
+	}
593
+
594
+
595
+	/**
596
+	 * register translations for a registered script
597
+	 *
598
+	 * @param string $handle
599
+	 */
600
+	public function registerTranslation($handle)
601
+	{
602
+		$this->i18n_registry->registerScriptI18n($handle);
603
+	}
604
+
605
+
606
+	/**
607
+	 * @since 4.9.63.p
608
+	 * @return bool
609
+	 */
610
+	private function debug()
611
+	{
612
+		return apply_filters(
613
+			'FHEE__EventEspresso_core_services_assets_Registry__debug',
614
+			defined('EE_DEBUG') && EE_DEBUG
615
+		);
616
+	}
617 617
 }
Please login to merge, or discard this patch.
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
                 $script->version(),
148 148
                 $script->loadInFooter()
149 149
             );
150
-            if (! $registered && $this->debug()) {
150
+            if ( ! $registered && $this->debug()) {
151 151
                 throw new AssetRegistrationException($script->handle());
152 152
             }
153 153
             $script->setRegistered($registered);
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
         $this->removeAlreadyRegisteredDataForScriptHandles();
208 208
         wp_add_inline_script(
209 209
             'eejs-core',
210
-            'var eejsdata=' . wp_json_encode(array('data' => $this->jsdata)),
210
+            'var eejsdata='.wp_json_encode(array('data' => $this->jsdata)),
211 211
             'before'
212 212
         );
213 213
         $scripts = $this->assets->getJavascriptAssetsWithData();
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
     public function addData($key, $value)
238 238
     {
239 239
         if ($this->verifyDataNotExisting($key)) {
240
-            $this->jsdata[ $key ] = $value;
240
+            $this->jsdata[$key] = $value;
241 241
         }
242 242
     }
243 243
 
@@ -262,10 +262,10 @@  discard block
 block discarded – undo
262 262
      */
263 263
     public function pushData($key, $value)
264 264
     {
265
-        if (isset($this->jsdata[ $key ])
266
-            && ! is_array($this->jsdata[ $key ])
265
+        if (isset($this->jsdata[$key])
266
+            && ! is_array($this->jsdata[$key])
267 267
         ) {
268
-            if (! $this->debug()) {
268
+            if ( ! $this->debug()) {
269 269
                 return;
270 270
             }
271 271
             throw new InvalidArgumentException(
@@ -280,10 +280,10 @@  discard block
 block discarded – undo
280 280
                 )
281 281
             );
282 282
         }
283
-        if ( ! isset( $this->jsdata[ $key ] ) ) {
284
-            $this->jsdata[ $key ] = is_array($value) ? $value : [$value];
283
+        if ( ! isset($this->jsdata[$key])) {
284
+            $this->jsdata[$key] = is_array($value) ? $value : [$value];
285 285
         } else {
286
-            $this->jsdata[ $key ] = array_merge( $this->jsdata[$key], (array) $value);
286
+            $this->jsdata[$key] = array_merge($this->jsdata[$key], (array) $value);
287 287
         }
288 288
     }
289 289
 
@@ -298,12 +298,12 @@  discard block
 block discarded – undo
298 298
      */
299 299
     public function addTemplate($template_reference, $template_content)
300 300
     {
301
-        if (! isset($this->jsdata['templates'])) {
301
+        if ( ! isset($this->jsdata['templates'])) {
302 302
             $this->jsdata['templates'] = array();
303 303
         }
304 304
         //no overrides allowed.
305
-        if (isset($this->jsdata['templates'][ $template_reference ])) {
306
-            if (! $this->debug()) {
305
+        if (isset($this->jsdata['templates'][$template_reference])) {
306
+            if ( ! $this->debug()) {
307 307
                 return;
308 308
             }
309 309
             throw new InvalidArgumentException(
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
                 )
317 317
             );
318 318
         }
319
-        $this->jsdata['templates'][ $template_reference ] = $template_content;
319
+        $this->jsdata['templates'][$template_reference] = $template_content;
320 320
     }
321 321
 
322 322
 
@@ -328,8 +328,8 @@  discard block
 block discarded – undo
328 328
      */
329 329
     public function getTemplate($template_reference)
330 330
     {
331
-        return isset($this->jsdata['templates'][ $template_reference ])
332
-            ? $this->jsdata['templates'][ $template_reference ]
331
+        return isset($this->jsdata['templates'][$template_reference])
332
+            ? $this->jsdata['templates'][$template_reference]
333 333
             : '';
334 334
     }
335 335
 
@@ -342,8 +342,8 @@  discard block
 block discarded – undo
342 342
      */
343 343
     public function getData($key)
344 344
     {
345
-        return isset($this->jsdata[ $key ])
346
-            ? $this->jsdata[ $key ]
345
+        return isset($this->jsdata[$key])
346
+            ? $this->jsdata[$key]
347 347
             : false;
348 348
     }
349 349
 
@@ -358,11 +358,11 @@  discard block
 block discarded – undo
358 358
      */
359 359
     protected function verifyDataNotExisting($key)
360 360
     {
361
-        if (isset($this->jsdata[ $key ])) {
362
-            if (! $this->debug()) {
361
+        if (isset($this->jsdata[$key])) {
362
+            if ( ! $this->debug()) {
363 363
                 return false;
364 364
             }
365
-            if (is_array($this->jsdata[ $key ])) {
365
+            if (is_array($this->jsdata[$key])) {
366 366
                 throw new InvalidArgumentException(
367 367
                     sprintf(
368 368
                         __(
@@ -405,11 +405,11 @@  discard block
 block discarded – undo
405 405
     public function getAssetUrl($namespace, $chunk_name, $asset_type)
406 406
     {
407 407
         $url = isset(
408
-            $this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ],
409
-            $this->manifest_data[ $namespace ]['url_base']
408
+            $this->manifest_data[$namespace][$chunk_name.'.'.$asset_type],
409
+            $this->manifest_data[$namespace]['url_base']
410 410
         )
411
-            ? $this->manifest_data[ $namespace ]['url_base']
412
-              . $this->manifest_data[ $namespace ][ $chunk_name . '.' . $asset_type ]
411
+            ? $this->manifest_data[$namespace]['url_base']
412
+              . $this->manifest_data[$namespace][$chunk_name.'.'.$asset_type]
413 413
             : $chunk_name;
414 414
 
415 415
         return apply_filters(
@@ -461,7 +461,7 @@  discard block
 block discarded – undo
461 461
             $this->registerManifestFile(
462 462
                 $manifest_file->assetNamespace(),
463 463
                 $manifest_file->urlBase(),
464
-                $manifest_file->filepath() . Registry::FILE_NAME_BUILD_MANIFEST
464
+                $manifest_file->filepath().Registry::FILE_NAME_BUILD_MANIFEST
465 465
             );
466 466
         }
467 467
     }
@@ -479,8 +479,8 @@  discard block
 block discarded – undo
479 479
      */
480 480
     public function registerManifestFile($namespace, $url_base, $manifest_file)
481 481
     {
482
-        if (isset($this->manifest_data[ $namespace ])) {
483
-            if (! $this->debug()) {
482
+        if (isset($this->manifest_data[$namespace])) {
483
+            if ( ! $this->debug()) {
484 484
                 return;
485 485
             }
486 486
             throw new InvalidArgumentException(
@@ -513,9 +513,9 @@  discard block
 block discarded – undo
513 513
             }
514 514
             return;
515 515
         }
516
-        $this->manifest_data[ $namespace ] = $this->decodeManifestFile($manifest_file);
517
-        if (! isset($this->manifest_data[ $namespace ]['url_base'])) {
518
-            $this->manifest_data[ $namespace ]['url_base'] = trailingslashit($url_base);
516
+        $this->manifest_data[$namespace] = $this->decodeManifestFile($manifest_file);
517
+        if ( ! isset($this->manifest_data[$namespace]['url_base'])) {
518
+            $this->manifest_data[$namespace]['url_base'] = trailingslashit($url_base);
519 519
         }
520 520
     }
521 521
 
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
      */
531 531
     private function decodeManifestFile($manifest_file)
532 532
     {
533
-        if (! file_exists($manifest_file)) {
533
+        if ( ! file_exists($manifest_file)) {
534 534
             throw new InvalidFilePathException($manifest_file);
535 535
         }
536 536
         return json_decode(file_get_contents($manifest_file), true);
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
      */
545 545
     private function addRegisteredScriptHandlesWithData($script_handle)
546 546
     {
547
-        $this->script_handles_with_data[ $script_handle ] = $script_handle;
547
+        $this->script_handles_with_data[$script_handle] = $script_handle;
548 548
     }
549 549
 
550 550
 
@@ -570,23 +570,23 @@  discard block
 block discarded – undo
570 570
      */
571 571
     private function removeAlreadyRegisteredDataForScriptHandle($script_handle)
572 572
     {
573
-        if (isset($this->script_handles_with_data[ $script_handle ])) {
573
+        if (isset($this->script_handles_with_data[$script_handle])) {
574 574
             global $wp_scripts;
575 575
             $unset_handle = false;
576 576
             if ($wp_scripts->get_data($script_handle, 'data')) {
577
-                unset($wp_scripts->registered[ $script_handle ]->extra['data']);
577
+                unset($wp_scripts->registered[$script_handle]->extra['data']);
578 578
                 $unset_handle = true;
579 579
             }
580 580
             //deal with inline_scripts
581 581
             if ($wp_scripts->get_data($script_handle, 'before')) {
582
-                unset($wp_scripts->registered[ $script_handle ]->extra['before']);
582
+                unset($wp_scripts->registered[$script_handle]->extra['before']);
583 583
                 $unset_handle = true;
584 584
             }
585 585
             if ($wp_scripts->get_data($script_handle, 'after')) {
586
-                unset($wp_scripts->registered[ $script_handle ]->extra['after']);
586
+                unset($wp_scripts->registered[$script_handle]->extra['after']);
587 587
             }
588 588
             if ($unset_handle) {
589
-                unset($this->script_handles_with_data[ $script_handle ]);
589
+                unset($this->script_handles_with_data[$script_handle]);
590 590
             }
591 591
         }
592 592
     }
Please login to merge, or discard this patch.