Completed
Branch FET/337/reserved-instance-inte... (8ac9b7)
by
unknown
73:19 queued 58:57
created
core/helpers/EEH_Activation.helper.php 1 patch
Indentation   +1581 added lines, -1581 removed lines patch added patch discarded remove patch
@@ -19,233 +19,233 @@  discard block
 block discarded – undo
19 19
 class EEH_Activation implements ResettableInterface
20 20
 {
21 21
 
22
-    /**
23
-     * constant used to indicate a cron task is no longer in use
24
-     */
25
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
26
-
27
-    /**
28
-     * WP_User->ID
29
-     *
30
-     * @var int
31
-     */
32
-    private static $_default_creator_id;
33
-
34
-    /**
35
-     * indicates whether or not we've already verified core's default data during this request,
36
-     * because after migrations are done, any addons activated while in maintenance mode
37
-     * will want to setup their own default data, and they might hook into core's default data
38
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
39
-     * This prevents doing that for EVERY single addon.
40
-     *
41
-     * @var boolean
42
-     */
43
-    protected static $_initialized_db_content_already_in_this_request = false;
44
-
45
-    /**
46
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
47
-     */
48
-    private static $table_analysis;
49
-
50
-    /**
51
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
52
-     */
53
-    private static $table_manager;
54
-
55
-
56
-    /**
57
-     * @return \EventEspresso\core\services\database\TableAnalysis
58
-     */
59
-    public static function getTableAnalysis()
60
-    {
61
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
62
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
63
-        }
64
-        return self::$table_analysis;
65
-    }
66
-
67
-
68
-    /**
69
-     * @return \EventEspresso\core\services\database\TableManager
70
-     */
71
-    public static function getTableManager()
72
-    {
73
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
74
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
75
-        }
76
-        return self::$table_manager;
77
-    }
78
-
79
-
80
-    /**
81
-     *    _ensure_table_name_has_prefix
82
-     *
83
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
84
-     * @access     public
85
-     * @static
86
-     * @param $table_name
87
-     * @return string
88
-     */
89
-    public static function ensure_table_name_has_prefix($table_name)
90
-    {
91
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
92
-    }
93
-
94
-
95
-    /**
96
-     *    system_initialization
97
-     *    ensures the EE configuration settings are loaded with at least default options set
98
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
99
-     *
100
-     * @access public
101
-     * @static
102
-     * @return void
103
-     */
104
-    public static function system_initialization()
105
-    {
106
-        EEH_Activation::reset_and_update_config();
107
-        //which is fired BEFORE activation of plugin anyways
108
-        EEH_Activation::verify_default_pages_exist();
109
-    }
110
-
111
-
112
-    /**
113
-     * Sets the database schema and creates folders. This should
114
-     * be called on plugin activation and reactivation
115
-     *
116
-     * @return boolean success, whether the database and folders are setup properly
117
-     * @throws \EE_Error
118
-     */
119
-    public static function initialize_db_and_folders()
120
-    {
121
-        return EEH_Activation::create_database_tables();
122
-    }
123
-
124
-
125
-    /**
126
-     * assuming we have an up-to-date database schema, this will populate it
127
-     * with default and initial data. This should be called
128
-     * upon activation of a new plugin, reactivation, and at the end
129
-     * of running migration scripts
130
-     *
131
-     * @throws \EE_Error
132
-     */
133
-    public static function initialize_db_content()
134
-    {
135
-        //let's avoid doing all this logic repeatedly, especially when addons are requesting it
136
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
137
-            return;
138
-        }
139
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
140
-
141
-        EEH_Activation::initialize_system_questions();
142
-        EEH_Activation::insert_default_status_codes();
143
-        EEH_Activation::generate_default_message_templates();
144
-        EEH_Activation::create_no_ticket_prices_array();
145
-
146
-        EEH_Activation::validate_messages_system();
147
-        EEH_Activation::insert_default_payment_methods();
148
-        //in case we've
149
-        EEH_Activation::remove_cron_tasks();
150
-        EEH_Activation::create_cron_tasks();
151
-        // remove all TXN locks since that is being done via extra meta now
152
-        delete_option('ee_locked_transactions');
153
-        //also, check for CAF default db content
154
-        do_action('AHEE__EEH_Activation__initialize_db_content');
155
-        //also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
156
-        //which users really won't care about on initial activation
157
-        EE_Error::overwrite_success();
158
-    }
159
-
160
-
161
-    /**
162
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
163
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
164
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
165
-     * (null)
166
-     *
167
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
168
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
169
-     * @return array
170
-     * @throws \EE_Error
171
-     */
172
-    public static function get_cron_tasks($which_to_include)
173
-    {
174
-        $cron_tasks = apply_filters(
175
-            'FHEE__EEH_Activation__get_cron_tasks',
176
-            array(
177
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
22
+	/**
23
+	 * constant used to indicate a cron task is no longer in use
24
+	 */
25
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
26
+
27
+	/**
28
+	 * WP_User->ID
29
+	 *
30
+	 * @var int
31
+	 */
32
+	private static $_default_creator_id;
33
+
34
+	/**
35
+	 * indicates whether or not we've already verified core's default data during this request,
36
+	 * because after migrations are done, any addons activated while in maintenance mode
37
+	 * will want to setup their own default data, and they might hook into core's default data
38
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
39
+	 * This prevents doing that for EVERY single addon.
40
+	 *
41
+	 * @var boolean
42
+	 */
43
+	protected static $_initialized_db_content_already_in_this_request = false;
44
+
45
+	/**
46
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
47
+	 */
48
+	private static $table_analysis;
49
+
50
+	/**
51
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
52
+	 */
53
+	private static $table_manager;
54
+
55
+
56
+	/**
57
+	 * @return \EventEspresso\core\services\database\TableAnalysis
58
+	 */
59
+	public static function getTableAnalysis()
60
+	{
61
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
62
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
63
+		}
64
+		return self::$table_analysis;
65
+	}
66
+
67
+
68
+	/**
69
+	 * @return \EventEspresso\core\services\database\TableManager
70
+	 */
71
+	public static function getTableManager()
72
+	{
73
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
74
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
75
+		}
76
+		return self::$table_manager;
77
+	}
78
+
79
+
80
+	/**
81
+	 *    _ensure_table_name_has_prefix
82
+	 *
83
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
84
+	 * @access     public
85
+	 * @static
86
+	 * @param $table_name
87
+	 * @return string
88
+	 */
89
+	public static function ensure_table_name_has_prefix($table_name)
90
+	{
91
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
92
+	}
93
+
94
+
95
+	/**
96
+	 *    system_initialization
97
+	 *    ensures the EE configuration settings are loaded with at least default options set
98
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
99
+	 *
100
+	 * @access public
101
+	 * @static
102
+	 * @return void
103
+	 */
104
+	public static function system_initialization()
105
+	{
106
+		EEH_Activation::reset_and_update_config();
107
+		//which is fired BEFORE activation of plugin anyways
108
+		EEH_Activation::verify_default_pages_exist();
109
+	}
110
+
111
+
112
+	/**
113
+	 * Sets the database schema and creates folders. This should
114
+	 * be called on plugin activation and reactivation
115
+	 *
116
+	 * @return boolean success, whether the database and folders are setup properly
117
+	 * @throws \EE_Error
118
+	 */
119
+	public static function initialize_db_and_folders()
120
+	{
121
+		return EEH_Activation::create_database_tables();
122
+	}
123
+
124
+
125
+	/**
126
+	 * assuming we have an up-to-date database schema, this will populate it
127
+	 * with default and initial data. This should be called
128
+	 * upon activation of a new plugin, reactivation, and at the end
129
+	 * of running migration scripts
130
+	 *
131
+	 * @throws \EE_Error
132
+	 */
133
+	public static function initialize_db_content()
134
+	{
135
+		//let's avoid doing all this logic repeatedly, especially when addons are requesting it
136
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
137
+			return;
138
+		}
139
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
140
+
141
+		EEH_Activation::initialize_system_questions();
142
+		EEH_Activation::insert_default_status_codes();
143
+		EEH_Activation::generate_default_message_templates();
144
+		EEH_Activation::create_no_ticket_prices_array();
145
+
146
+		EEH_Activation::validate_messages_system();
147
+		EEH_Activation::insert_default_payment_methods();
148
+		//in case we've
149
+		EEH_Activation::remove_cron_tasks();
150
+		EEH_Activation::create_cron_tasks();
151
+		// remove all TXN locks since that is being done via extra meta now
152
+		delete_option('ee_locked_transactions');
153
+		//also, check for CAF default db content
154
+		do_action('AHEE__EEH_Activation__initialize_db_content');
155
+		//also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
156
+		//which users really won't care about on initial activation
157
+		EE_Error::overwrite_success();
158
+	}
159
+
160
+
161
+	/**
162
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
163
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
164
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
165
+	 * (null)
166
+	 *
167
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
168
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
169
+	 * @return array
170
+	 * @throws \EE_Error
171
+	 */
172
+	public static function get_cron_tasks($which_to_include)
173
+	{
174
+		$cron_tasks = apply_filters(
175
+			'FHEE__EEH_Activation__get_cron_tasks',
176
+			array(
177
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
178 178
 //				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
179
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
180
-                //there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
181
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
182
-            )
183
-        );
184
-        if ($which_to_include === 'old') {
185
-            $cron_tasks = array_filter(
186
-                $cron_tasks,
187
-                function ($value) {
188
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
189
-                }
190
-            );
191
-        } elseif ($which_to_include === 'current') {
192
-            $cron_tasks = array_filter($cron_tasks);
193
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
194
-            throw new EE_Error(
195
-                sprintf(
196
-                    __(
197
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
198
-                        'event_espresso'
199
-                    ),
200
-                    $which_to_include
201
-                )
202
-            );
203
-        }
204
-        return $cron_tasks;
205
-    }
206
-
207
-
208
-    /**
209
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
210
-     *
211
-     * @throws \EE_Error
212
-     */
213
-    public static function create_cron_tasks()
214
-    {
215
-
216
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
217
-            if (! wp_next_scheduled($hook_name)) {
218
-                /**
219
-                 * This allows client code to define the initial start timestamp for this schedule.
220
-                 */
221
-                if (is_array($frequency)
222
-                    && count($frequency) === 2
223
-                    && isset($frequency[0], $frequency[1])
224
-                ) {
225
-                    $start_timestamp = $frequency[0];
226
-                    $frequency = $frequency[1];
227
-                } else {
228
-                    $start_timestamp = time();
229
-                }
230
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
231
-            }
232
-        }
233
-
234
-    }
235
-
236
-
237
-    /**
238
-     * Remove the currently-existing and now-removed cron tasks.
239
-     *
240
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
241
-     * @throws \EE_Error
242
-     */
243
-    public static function remove_cron_tasks($remove_all = true)
244
-    {
245
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
246
-        $crons                = _get_cron_array();
247
-        $crons                = is_array($crons) ? $crons : array();
248
-        /* reminder of what $crons look like:
179
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
180
+				//there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
181
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
182
+			)
183
+		);
184
+		if ($which_to_include === 'old') {
185
+			$cron_tasks = array_filter(
186
+				$cron_tasks,
187
+				function ($value) {
188
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
189
+				}
190
+			);
191
+		} elseif ($which_to_include === 'current') {
192
+			$cron_tasks = array_filter($cron_tasks);
193
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
194
+			throw new EE_Error(
195
+				sprintf(
196
+					__(
197
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
198
+						'event_espresso'
199
+					),
200
+					$which_to_include
201
+				)
202
+			);
203
+		}
204
+		return $cron_tasks;
205
+	}
206
+
207
+
208
+	/**
209
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
210
+	 *
211
+	 * @throws \EE_Error
212
+	 */
213
+	public static function create_cron_tasks()
214
+	{
215
+
216
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
217
+			if (! wp_next_scheduled($hook_name)) {
218
+				/**
219
+				 * This allows client code to define the initial start timestamp for this schedule.
220
+				 */
221
+				if (is_array($frequency)
222
+					&& count($frequency) === 2
223
+					&& isset($frequency[0], $frequency[1])
224
+				) {
225
+					$start_timestamp = $frequency[0];
226
+					$frequency = $frequency[1];
227
+				} else {
228
+					$start_timestamp = time();
229
+				}
230
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
231
+			}
232
+		}
233
+
234
+	}
235
+
236
+
237
+	/**
238
+	 * Remove the currently-existing and now-removed cron tasks.
239
+	 *
240
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
241
+	 * @throws \EE_Error
242
+	 */
243
+	public static function remove_cron_tasks($remove_all = true)
244
+	{
245
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
246
+		$crons                = _get_cron_array();
247
+		$crons                = is_array($crons) ? $crons : array();
248
+		/* reminder of what $crons look like:
249 249
          * Top-level keys are timestamps, and their values are arrays.
250 250
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
251 251
          * and their values are arrays.
@@ -262,911 +262,911 @@  discard block
 block discarded – undo
262 262
          *					...
263 263
          *      ...
264 264
          */
265
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
266
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
267
-            if (is_array($hooks_to_fire_at_time)) {
268
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
269
-                    if (isset($ee_cron_tasks_to_remove[$hook_name])
270
-                        && is_array($ee_cron_tasks_to_remove[$hook_name])
271
-                    ) {
272
-                        unset($crons[$timestamp][$hook_name]);
273
-                    }
274
-                }
275
-                //also take care of any empty cron timestamps.
276
-                if (empty($hooks_to_fire_at_time)) {
277
-                    unset($crons[$timestamp]);
278
-                }
279
-            }
280
-        }
281
-        _set_cron_array($crons);
282
-    }
283
-
284
-
285
-    /**
286
-     *    CPT_initialization
287
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
288
-     *
289
-     * @access public
290
-     * @static
291
-     * @return void
292
-     */
293
-    public static function CPT_initialization()
294
-    {
295
-        // register Custom Post Types
296
-        EE_Registry::instance()->load_core('Register_CPTs');
297
-        flush_rewrite_rules();
298
-    }
299
-
300
-
301
-
302
-    /**
303
-     *    reset_and_update_config
304
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
305
-     * If there is old calendar config data saved, then it will get converted on activation.
306
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
307
-     *
308
-     * @access public
309
-     * @static
310
-     * @return void
311
-     */
312
-    public static function reset_and_update_config()
313
-    {
314
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
315
-        add_filter(
316
-            'FHEE__EE_Config___load_core_config__config_settings',
317
-            array('EEH_Activation', 'migrate_old_config_data'),
318
-            10,
319
-            3
320
-        );
321
-        //EE_Config::reset();
322
-        if (! EE_Config::logging_enabled()) {
323
-            delete_option(EE_Config::LOG_NAME);
324
-        }
325
-    }
326
-
327
-
328
-    /**
329
-     *    load_calendar_config
330
-     *
331
-     * @access    public
332
-     * @return    void
333
-     */
334
-    public static function load_calendar_config()
335
-    {
336
-        // grab array of all plugin folders and loop thru it
337
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
338
-        if (empty($plugins)) {
339
-            return;
340
-        }
341
-        foreach ($plugins as $plugin_path) {
342
-            // grab plugin folder name from path
343
-            $plugin = basename($plugin_path);
344
-            // drill down to Espresso plugins
345
-            // then to calendar related plugins
346
-            if (
347
-                strpos($plugin, 'espresso') !== false
348
-                || strpos($plugin, 'Espresso') !== false
349
-                || strpos($plugin, 'ee4') !== false
350
-                || strpos($plugin, 'EE4') !== false
351
-                || strpos($plugin, 'calendar') !== false
352
-            ) {
353
-                // this is what we are looking for
354
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
355
-                // does it exist in this folder ?
356
-                if (is_readable($calendar_config)) {
357
-                    // YEAH! let's load it
358
-                    require_once($calendar_config);
359
-                }
360
-            }
361
-        }
362
-    }
363
-
364
-
365
-
366
-    /**
367
-     *    _migrate_old_config_data
368
-     *
369
-     * @access    public
370
-     * @param array|stdClass $settings
371
-     * @param string         $config
372
-     * @param \EE_Config     $EE_Config
373
-     * @return \stdClass
374
-     */
375
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
376
-    {
377
-        $convert_from_array = array('addons');
378
-        // in case old settings were saved as an array
379
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
380
-            // convert existing settings to an object
381
-            $config_array = $settings;
382
-            $settings = new stdClass();
383
-            foreach ($config_array as $key => $value) {
384
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
385
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
386
-                } else {
387
-                    $settings->{$key} = $value;
388
-                }
389
-            }
390
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
391
-        }
392
-        return $settings;
393
-    }
394
-
395
-
396
-    /**
397
-     * deactivate_event_espresso
398
-     *
399
-     * @access public
400
-     * @static
401
-     * @return void
402
-     */
403
-    public static function deactivate_event_espresso()
404
-    {
405
-        // check permissions
406
-        if (current_user_can('activate_plugins')) {
407
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
408
-        }
409
-    }
410
-
411
-
412
-
413
-    /**
414
-     * verify_default_pages_exist
415
-     *
416
-     * @access public
417
-     * @static
418
-     * @return void
419
-     * @throws InvalidDataTypeException
420
-     */
421
-    public static function verify_default_pages_exist()
422
-    {
423
-        $critical_page_problem = false;
424
-        $critical_pages = array(
425
-            array(
426
-                'id'   => 'reg_page_id',
427
-                'name' => __('Registration Checkout', 'event_espresso'),
428
-                'post' => null,
429
-                'code' => 'ESPRESSO_CHECKOUT',
430
-            ),
431
-            array(
432
-                'id'   => 'txn_page_id',
433
-                'name' => __('Transactions', 'event_espresso'),
434
-                'post' => null,
435
-                'code' => 'ESPRESSO_TXN_PAGE',
436
-            ),
437
-            array(
438
-                'id'   => 'thank_you_page_id',
439
-                'name' => __('Thank You', 'event_espresso'),
440
-                'post' => null,
441
-                'code' => 'ESPRESSO_THANK_YOU',
442
-            ),
443
-            array(
444
-                'id'   => 'cancel_page_id',
445
-                'name' => __('Registration Cancelled', 'event_espresso'),
446
-                'post' => null,
447
-                'code' => 'ESPRESSO_CANCELLED',
448
-            ),
449
-        );
450
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
451
-        foreach ($critical_pages as $critical_page) {
452
-            // is critical page ID set in config ?
453
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
454
-                // attempt to find post by ID
455
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
456
-            }
457
-            // no dice?
458
-            if ($critical_page['post'] === null) {
459
-                // attempt to find post by title
460
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
461
-                // still nothing?
462
-                if ($critical_page['post'] === null) {
463
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
464
-                    // REALLY? Still nothing ??!?!?
465
-                    if ($critical_page['post'] === null) {
466
-                        $msg = __(
467
-                            'The Event Espresso critical page configuration settings could not be updated.',
468
-                            'event_espresso'
469
-                        );
470
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
471
-                        break;
472
-                    }
473
-                }
474
-            }
475
-            // check that Post ID matches critical page ID in config
476
-            if (
477
-                isset($critical_page['post']->ID)
478
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
479
-            ) {
480
-                //update Config with post ID
481
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
482
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
483
-                    $msg = __(
484
-                        'The Event Espresso critical page configuration settings could not be updated.',
485
-                        'event_espresso'
486
-                    );
487
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
488
-                }
489
-            }
490
-            $critical_page_problem =
491
-                ! isset($critical_page['post']->post_status)
492
-                || $critical_page['post']->post_status !== 'publish'
493
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
494
-                    ? true
495
-                    : $critical_page_problem;
496
-        }
497
-        if ($critical_page_problem) {
498
-            new PersistentAdminNotice(
499
-                'critical_page_problem',
500
-                sprintf(
501
-                    esc_html__(
502
-                        'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
503
-                        'event_espresso'
504
-                    ),
505
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
506
-                    . __('Event Espresso Critical Pages Settings', 'event_espresso')
507
-                    . '</a>'
508
-                )
509
-            );
510
-        }
511
-        if (EE_Error::has_notices()) {
512
-            EE_Error::get_notices(false, true, true);
513
-        }
514
-    }
515
-
516
-
517
-
518
-    /**
519
-     * Returns the first post which uses the specified shortcode
520
-     *
521
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
522
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
523
-     *                             "[ESPRESSO_THANK_YOU"
524
-     *                             (we don't search for the closing shortcode bracket because they might have added
525
-     *                             parameter to the shortcode
526
-     * @return WP_Post or NULl
527
-     */
528
-    public static function get_page_by_ee_shortcode($ee_shortcode)
529
-    {
530
-        global $wpdb;
531
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
532
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
533
-        if ($post_id) {
534
-            return get_post($post_id);
535
-        } else {
536
-            return null;
537
-        }
538
-    }
539
-
540
-
541
-    /**
542
-     *    This function generates a post for critical espresso pages
543
-     *
544
-     * @access public
545
-     * @static
546
-     * @param array $critical_page
547
-     * @return array
548
-     */
549
-    public static function create_critical_page($critical_page)
550
-    {
551
-
552
-        $post_args = array(
553
-            'post_title'     => $critical_page['name'],
554
-            'post_status'    => 'publish',
555
-            'post_type'      => 'page',
556
-            'comment_status' => 'closed',
557
-            'post_content'   => '[' . $critical_page['code'] . ']',
558
-        );
559
-
560
-        $post_id = wp_insert_post($post_args);
561
-        if (! $post_id) {
562
-            $msg = sprintf(
563
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
564
-                $critical_page['name']
565
-            );
566
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
567
-            return $critical_page;
568
-        }
569
-        // get newly created post's details
570
-        if (! $critical_page['post'] = get_post($post_id)) {
571
-            $msg = sprintf(
572
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
573
-                $critical_page['name']
574
-            );
575
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
576
-        }
577
-
578
-        return $critical_page;
579
-
580
-    }
581
-
582
-
583
-
584
-
585
-    /**
586
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
587
-     * The role being used to check is filterable.
588
-     *
589
-     * @since  4.6.0
590
-     * @global WPDB $wpdb
591
-     * @return mixed null|int WP_user ID or NULL
592
-     */
593
-    public static function get_default_creator_id()
594
-    {
595
-        global $wpdb;
596
-        if ( ! empty(self::$_default_creator_id)) {
597
-            return self::$_default_creator_id;
598
-        }/**/
599
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
600
-        //let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
601
-        $pre_filtered_id = apply_filters(
602
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
603
-            false,
604
-            $role_to_check
605
-        );
606
-        if ($pre_filtered_id !== false) {
607
-            return (int)$pre_filtered_id;
608
-        }
609
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
610
-        $query = $wpdb->prepare(
611
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
612
-            '%' . $role_to_check . '%'
613
-        );
614
-        $user_id = $wpdb->get_var($query);
615
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
616
-        if ($user_id && (int)$user_id) {
617
-            self::$_default_creator_id = (int)$user_id;
618
-            return self::$_default_creator_id;
619
-        } else {
620
-            return null;
621
-        }
622
-    }
623
-
624
-
625
-
626
-    /**
627
-     * used by EE and EE addons during plugin activation to create tables.
628
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
629
-     * but includes extra logic regarding activations.
630
-     *
631
-     * @access public
632
-     * @static
633
-     * @param string  $table_name              without the $wpdb->prefix
634
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
635
-     *                                         table query)
636
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
637
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
638
-     *                                         and new once this function is done (ie, you really do want to CREATE a
639
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
640
-     *                                         you just want to verify the table exists and matches this definition
641
-     *                                         (and if it HAS data in it you want to leave it be)
642
-     * @return void
643
-     * @throws EE_Error if there are database errors
644
-     */
645
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
646
-    {
647
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
648
-            return;
649
-        }
650
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
651
-        if ( ! function_exists('dbDelta')) {
652
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
653
-        }
654
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
655
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
656
-        // do we need to first delete an existing version of this table ?
657
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
658
-            // ok, delete the table... but ONLY if it's empty
659
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
660
-            // table is NOT empty, are you SURE you want to delete this table ???
661
-            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
662
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
663
-            } else if ( ! $deleted_safely) {
664
-                // so we should be more cautious rather than just dropping tables so easily
665
-                error_log(
666
-                    sprintf(
667
-                        __(
668
-                            'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
669
-                            'event_espresso'
670
-                        ),
671
-                        $wp_table_name,
672
-                        '<br/>',
673
-                        'espresso_db_update'
674
-                    )
675
-                );
676
-            }
677
-        }
678
-        $engine = str_replace('ENGINE=', '', $engine);
679
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
680
-    }
681
-
682
-
683
-
684
-    /**
685
-     *    add_column_if_it_doesn't_exist
686
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
687
-     *
688
-     * @access     public
689
-     * @static
690
-     * @deprecated instead use TableManager::addColumn()
691
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
692
-     * @param string $column_name
693
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
694
-     *                            'VARCHAR(10)'
695
-     * @return bool|int
696
-     */
697
-    public static function add_column_if_it_doesnt_exist(
698
-        $table_name,
699
-        $column_name,
700
-        $column_info = 'INT UNSIGNED NOT NULL'
701
-    ) {
702
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
703
-    }
704
-
705
-
706
-    /**
707
-     * get_fields_on_table
708
-     * Gets all the fields on the database table.
709
-     *
710
-     * @access     public
711
-     * @deprecated instead use TableManager::getTableColumns()
712
-     * @static
713
-     * @param string $table_name , without prefixed $wpdb->prefix
714
-     * @return array of database column names
715
-     */
716
-    public static function get_fields_on_table($table_name = null)
717
-    {
718
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
719
-    }
720
-
721
-
722
-    /**
723
-     * db_table_is_empty
724
-     *
725
-     * @access     public\
726
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
727
-     * @static
728
-     * @param string $table_name
729
-     * @return bool
730
-     */
731
-    public static function db_table_is_empty($table_name)
732
-    {
733
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
734
-    }
735
-
736
-
737
-    /**
738
-     * delete_db_table_if_empty
739
-     *
740
-     * @access public
741
-     * @static
742
-     * @param string $table_name
743
-     * @return bool | int
744
-     */
745
-    public static function delete_db_table_if_empty($table_name)
746
-    {
747
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
748
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
749
-        }
750
-        return false;
751
-    }
752
-
753
-
754
-    /**
755
-     * delete_unused_db_table
756
-     *
757
-     * @access     public
758
-     * @static
759
-     * @deprecated instead use TableManager::dropTable()
760
-     * @param string $table_name
761
-     * @return bool | int
762
-     */
763
-    public static function delete_unused_db_table($table_name)
764
-    {
765
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
766
-    }
767
-
768
-
769
-    /**
770
-     * drop_index
771
-     *
772
-     * @access     public
773
-     * @static
774
-     * @deprecated instead use TableManager::dropIndex()
775
-     * @param string $table_name
776
-     * @param string $index_name
777
-     * @return bool | int
778
-     */
779
-    public static function drop_index($table_name, $index_name)
780
-    {
781
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
782
-    }
783
-
784
-
785
-
786
-    /**
787
-     * create_database_tables
788
-     *
789
-     * @access public
790
-     * @static
791
-     * @throws EE_Error
792
-     * @return boolean success (whether database is setup properly or not)
793
-     */
794
-    public static function create_database_tables()
795
-    {
796
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
797
-        //find the migration script that sets the database to be compatible with the code
798
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
799
-        if ($dms_name) {
800
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
801
-            $current_data_migration_script->set_migrating(false);
802
-            $current_data_migration_script->schema_changes_before_migration();
803
-            $current_data_migration_script->schema_changes_after_migration();
804
-            if ($current_data_migration_script->get_errors()) {
805
-                if (WP_DEBUG) {
806
-                    foreach ($current_data_migration_script->get_errors() as $error) {
807
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
808
-                    }
809
-                } else {
810
-                    EE_Error::add_error(
811
-                        __(
812
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
265
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
266
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
267
+			if (is_array($hooks_to_fire_at_time)) {
268
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
269
+					if (isset($ee_cron_tasks_to_remove[$hook_name])
270
+						&& is_array($ee_cron_tasks_to_remove[$hook_name])
271
+					) {
272
+						unset($crons[$timestamp][$hook_name]);
273
+					}
274
+				}
275
+				//also take care of any empty cron timestamps.
276
+				if (empty($hooks_to_fire_at_time)) {
277
+					unset($crons[$timestamp]);
278
+				}
279
+			}
280
+		}
281
+		_set_cron_array($crons);
282
+	}
283
+
284
+
285
+	/**
286
+	 *    CPT_initialization
287
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
288
+	 *
289
+	 * @access public
290
+	 * @static
291
+	 * @return void
292
+	 */
293
+	public static function CPT_initialization()
294
+	{
295
+		// register Custom Post Types
296
+		EE_Registry::instance()->load_core('Register_CPTs');
297
+		flush_rewrite_rules();
298
+	}
299
+
300
+
301
+
302
+	/**
303
+	 *    reset_and_update_config
304
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
305
+	 * If there is old calendar config data saved, then it will get converted on activation.
306
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
307
+	 *
308
+	 * @access public
309
+	 * @static
310
+	 * @return void
311
+	 */
312
+	public static function reset_and_update_config()
313
+	{
314
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
315
+		add_filter(
316
+			'FHEE__EE_Config___load_core_config__config_settings',
317
+			array('EEH_Activation', 'migrate_old_config_data'),
318
+			10,
319
+			3
320
+		);
321
+		//EE_Config::reset();
322
+		if (! EE_Config::logging_enabled()) {
323
+			delete_option(EE_Config::LOG_NAME);
324
+		}
325
+	}
326
+
327
+
328
+	/**
329
+	 *    load_calendar_config
330
+	 *
331
+	 * @access    public
332
+	 * @return    void
333
+	 */
334
+	public static function load_calendar_config()
335
+	{
336
+		// grab array of all plugin folders and loop thru it
337
+		$plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
338
+		if (empty($plugins)) {
339
+			return;
340
+		}
341
+		foreach ($plugins as $plugin_path) {
342
+			// grab plugin folder name from path
343
+			$plugin = basename($plugin_path);
344
+			// drill down to Espresso plugins
345
+			// then to calendar related plugins
346
+			if (
347
+				strpos($plugin, 'espresso') !== false
348
+				|| strpos($plugin, 'Espresso') !== false
349
+				|| strpos($plugin, 'ee4') !== false
350
+				|| strpos($plugin, 'EE4') !== false
351
+				|| strpos($plugin, 'calendar') !== false
352
+			) {
353
+				// this is what we are looking for
354
+				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
355
+				// does it exist in this folder ?
356
+				if (is_readable($calendar_config)) {
357
+					// YEAH! let's load it
358
+					require_once($calendar_config);
359
+				}
360
+			}
361
+		}
362
+	}
363
+
364
+
365
+
366
+	/**
367
+	 *    _migrate_old_config_data
368
+	 *
369
+	 * @access    public
370
+	 * @param array|stdClass $settings
371
+	 * @param string         $config
372
+	 * @param \EE_Config     $EE_Config
373
+	 * @return \stdClass
374
+	 */
375
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
376
+	{
377
+		$convert_from_array = array('addons');
378
+		// in case old settings were saved as an array
379
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
380
+			// convert existing settings to an object
381
+			$config_array = $settings;
382
+			$settings = new stdClass();
383
+			foreach ($config_array as $key => $value) {
384
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
385
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
386
+				} else {
387
+					$settings->{$key} = $value;
388
+				}
389
+			}
390
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
391
+		}
392
+		return $settings;
393
+	}
394
+
395
+
396
+	/**
397
+	 * deactivate_event_espresso
398
+	 *
399
+	 * @access public
400
+	 * @static
401
+	 * @return void
402
+	 */
403
+	public static function deactivate_event_espresso()
404
+	{
405
+		// check permissions
406
+		if (current_user_can('activate_plugins')) {
407
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
408
+		}
409
+	}
410
+
411
+
412
+
413
+	/**
414
+	 * verify_default_pages_exist
415
+	 *
416
+	 * @access public
417
+	 * @static
418
+	 * @return void
419
+	 * @throws InvalidDataTypeException
420
+	 */
421
+	public static function verify_default_pages_exist()
422
+	{
423
+		$critical_page_problem = false;
424
+		$critical_pages = array(
425
+			array(
426
+				'id'   => 'reg_page_id',
427
+				'name' => __('Registration Checkout', 'event_espresso'),
428
+				'post' => null,
429
+				'code' => 'ESPRESSO_CHECKOUT',
430
+			),
431
+			array(
432
+				'id'   => 'txn_page_id',
433
+				'name' => __('Transactions', 'event_espresso'),
434
+				'post' => null,
435
+				'code' => 'ESPRESSO_TXN_PAGE',
436
+			),
437
+			array(
438
+				'id'   => 'thank_you_page_id',
439
+				'name' => __('Thank You', 'event_espresso'),
440
+				'post' => null,
441
+				'code' => 'ESPRESSO_THANK_YOU',
442
+			),
443
+			array(
444
+				'id'   => 'cancel_page_id',
445
+				'name' => __('Registration Cancelled', 'event_espresso'),
446
+				'post' => null,
447
+				'code' => 'ESPRESSO_CANCELLED',
448
+			),
449
+		);
450
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
451
+		foreach ($critical_pages as $critical_page) {
452
+			// is critical page ID set in config ?
453
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
454
+				// attempt to find post by ID
455
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
456
+			}
457
+			// no dice?
458
+			if ($critical_page['post'] === null) {
459
+				// attempt to find post by title
460
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
461
+				// still nothing?
462
+				if ($critical_page['post'] === null) {
463
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
464
+					// REALLY? Still nothing ??!?!?
465
+					if ($critical_page['post'] === null) {
466
+						$msg = __(
467
+							'The Event Espresso critical page configuration settings could not be updated.',
468
+							'event_espresso'
469
+						);
470
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
471
+						break;
472
+					}
473
+				}
474
+			}
475
+			// check that Post ID matches critical page ID in config
476
+			if (
477
+				isset($critical_page['post']->ID)
478
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
479
+			) {
480
+				//update Config with post ID
481
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
482
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
483
+					$msg = __(
484
+						'The Event Espresso critical page configuration settings could not be updated.',
485
+						'event_espresso'
486
+					);
487
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
488
+				}
489
+			}
490
+			$critical_page_problem =
491
+				! isset($critical_page['post']->post_status)
492
+				|| $critical_page['post']->post_status !== 'publish'
493
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
494
+					? true
495
+					: $critical_page_problem;
496
+		}
497
+		if ($critical_page_problem) {
498
+			new PersistentAdminNotice(
499
+				'critical_page_problem',
500
+				sprintf(
501
+					esc_html__(
502
+						'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
503
+						'event_espresso'
504
+					),
505
+					'<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
506
+					. __('Event Espresso Critical Pages Settings', 'event_espresso')
507
+					. '</a>'
508
+				)
509
+			);
510
+		}
511
+		if (EE_Error::has_notices()) {
512
+			EE_Error::get_notices(false, true, true);
513
+		}
514
+	}
515
+
516
+
517
+
518
+	/**
519
+	 * Returns the first post which uses the specified shortcode
520
+	 *
521
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
522
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
523
+	 *                             "[ESPRESSO_THANK_YOU"
524
+	 *                             (we don't search for the closing shortcode bracket because they might have added
525
+	 *                             parameter to the shortcode
526
+	 * @return WP_Post or NULl
527
+	 */
528
+	public static function get_page_by_ee_shortcode($ee_shortcode)
529
+	{
530
+		global $wpdb;
531
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
532
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
533
+		if ($post_id) {
534
+			return get_post($post_id);
535
+		} else {
536
+			return null;
537
+		}
538
+	}
539
+
540
+
541
+	/**
542
+	 *    This function generates a post for critical espresso pages
543
+	 *
544
+	 * @access public
545
+	 * @static
546
+	 * @param array $critical_page
547
+	 * @return array
548
+	 */
549
+	public static function create_critical_page($critical_page)
550
+	{
551
+
552
+		$post_args = array(
553
+			'post_title'     => $critical_page['name'],
554
+			'post_status'    => 'publish',
555
+			'post_type'      => 'page',
556
+			'comment_status' => 'closed',
557
+			'post_content'   => '[' . $critical_page['code'] . ']',
558
+		);
559
+
560
+		$post_id = wp_insert_post($post_args);
561
+		if (! $post_id) {
562
+			$msg = sprintf(
563
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
564
+				$critical_page['name']
565
+			);
566
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
567
+			return $critical_page;
568
+		}
569
+		// get newly created post's details
570
+		if (! $critical_page['post'] = get_post($post_id)) {
571
+			$msg = sprintf(
572
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
573
+				$critical_page['name']
574
+			);
575
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
576
+		}
577
+
578
+		return $critical_page;
579
+
580
+	}
581
+
582
+
583
+
584
+
585
+	/**
586
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
587
+	 * The role being used to check is filterable.
588
+	 *
589
+	 * @since  4.6.0
590
+	 * @global WPDB $wpdb
591
+	 * @return mixed null|int WP_user ID or NULL
592
+	 */
593
+	public static function get_default_creator_id()
594
+	{
595
+		global $wpdb;
596
+		if ( ! empty(self::$_default_creator_id)) {
597
+			return self::$_default_creator_id;
598
+		}/**/
599
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
600
+		//let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
601
+		$pre_filtered_id = apply_filters(
602
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
603
+			false,
604
+			$role_to_check
605
+		);
606
+		if ($pre_filtered_id !== false) {
607
+			return (int)$pre_filtered_id;
608
+		}
609
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
610
+		$query = $wpdb->prepare(
611
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
612
+			'%' . $role_to_check . '%'
613
+		);
614
+		$user_id = $wpdb->get_var($query);
615
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
616
+		if ($user_id && (int)$user_id) {
617
+			self::$_default_creator_id = (int)$user_id;
618
+			return self::$_default_creator_id;
619
+		} else {
620
+			return null;
621
+		}
622
+	}
623
+
624
+
625
+
626
+	/**
627
+	 * used by EE and EE addons during plugin activation to create tables.
628
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
629
+	 * but includes extra logic regarding activations.
630
+	 *
631
+	 * @access public
632
+	 * @static
633
+	 * @param string  $table_name              without the $wpdb->prefix
634
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
635
+	 *                                         table query)
636
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
637
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
638
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
639
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
640
+	 *                                         you just want to verify the table exists and matches this definition
641
+	 *                                         (and if it HAS data in it you want to leave it be)
642
+	 * @return void
643
+	 * @throws EE_Error if there are database errors
644
+	 */
645
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
646
+	{
647
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
648
+			return;
649
+		}
650
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
651
+		if ( ! function_exists('dbDelta')) {
652
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
653
+		}
654
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
655
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
656
+		// do we need to first delete an existing version of this table ?
657
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
658
+			// ok, delete the table... but ONLY if it's empty
659
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
660
+			// table is NOT empty, are you SURE you want to delete this table ???
661
+			if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
662
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
663
+			} else if ( ! $deleted_safely) {
664
+				// so we should be more cautious rather than just dropping tables so easily
665
+				error_log(
666
+					sprintf(
667
+						__(
668
+							'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
669
+							'event_espresso'
670
+						),
671
+						$wp_table_name,
672
+						'<br/>',
673
+						'espresso_db_update'
674
+					)
675
+				);
676
+			}
677
+		}
678
+		$engine = str_replace('ENGINE=', '', $engine);
679
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
680
+	}
681
+
682
+
683
+
684
+	/**
685
+	 *    add_column_if_it_doesn't_exist
686
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
687
+	 *
688
+	 * @access     public
689
+	 * @static
690
+	 * @deprecated instead use TableManager::addColumn()
691
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
692
+	 * @param string $column_name
693
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
694
+	 *                            'VARCHAR(10)'
695
+	 * @return bool|int
696
+	 */
697
+	public static function add_column_if_it_doesnt_exist(
698
+		$table_name,
699
+		$column_name,
700
+		$column_info = 'INT UNSIGNED NOT NULL'
701
+	) {
702
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
703
+	}
704
+
705
+
706
+	/**
707
+	 * get_fields_on_table
708
+	 * Gets all the fields on the database table.
709
+	 *
710
+	 * @access     public
711
+	 * @deprecated instead use TableManager::getTableColumns()
712
+	 * @static
713
+	 * @param string $table_name , without prefixed $wpdb->prefix
714
+	 * @return array of database column names
715
+	 */
716
+	public static function get_fields_on_table($table_name = null)
717
+	{
718
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
719
+	}
720
+
721
+
722
+	/**
723
+	 * db_table_is_empty
724
+	 *
725
+	 * @access     public\
726
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
727
+	 * @static
728
+	 * @param string $table_name
729
+	 * @return bool
730
+	 */
731
+	public static function db_table_is_empty($table_name)
732
+	{
733
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
734
+	}
735
+
736
+
737
+	/**
738
+	 * delete_db_table_if_empty
739
+	 *
740
+	 * @access public
741
+	 * @static
742
+	 * @param string $table_name
743
+	 * @return bool | int
744
+	 */
745
+	public static function delete_db_table_if_empty($table_name)
746
+	{
747
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
748
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
749
+		}
750
+		return false;
751
+	}
752
+
753
+
754
+	/**
755
+	 * delete_unused_db_table
756
+	 *
757
+	 * @access     public
758
+	 * @static
759
+	 * @deprecated instead use TableManager::dropTable()
760
+	 * @param string $table_name
761
+	 * @return bool | int
762
+	 */
763
+	public static function delete_unused_db_table($table_name)
764
+	{
765
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
766
+	}
767
+
768
+
769
+	/**
770
+	 * drop_index
771
+	 *
772
+	 * @access     public
773
+	 * @static
774
+	 * @deprecated instead use TableManager::dropIndex()
775
+	 * @param string $table_name
776
+	 * @param string $index_name
777
+	 * @return bool | int
778
+	 */
779
+	public static function drop_index($table_name, $index_name)
780
+	{
781
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
782
+	}
783
+
784
+
785
+
786
+	/**
787
+	 * create_database_tables
788
+	 *
789
+	 * @access public
790
+	 * @static
791
+	 * @throws EE_Error
792
+	 * @return boolean success (whether database is setup properly or not)
793
+	 */
794
+	public static function create_database_tables()
795
+	{
796
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
797
+		//find the migration script that sets the database to be compatible with the code
798
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
799
+		if ($dms_name) {
800
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
801
+			$current_data_migration_script->set_migrating(false);
802
+			$current_data_migration_script->schema_changes_before_migration();
803
+			$current_data_migration_script->schema_changes_after_migration();
804
+			if ($current_data_migration_script->get_errors()) {
805
+				if (WP_DEBUG) {
806
+					foreach ($current_data_migration_script->get_errors() as $error) {
807
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
808
+					}
809
+				} else {
810
+					EE_Error::add_error(
811
+						__(
812
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
813 813
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
814
-                            'event_espresso'
815
-                        )
816
-                    );
817
-                }
818
-                return false;
819
-            }
820
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
821
-        } else {
822
-            EE_Error::add_error(
823
-                __(
824
-                    'Could not determine most up-to-date data migration script from which to pull database schema
814
+							'event_espresso'
815
+						)
816
+					);
817
+				}
818
+				return false;
819
+			}
820
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
821
+		} else {
822
+			EE_Error::add_error(
823
+				__(
824
+					'Could not determine most up-to-date data migration script from which to pull database schema
825 825
                      structure. So database is probably not setup properly',
826
-                    'event_espresso'
827
-                ),
828
-                __FILE__,
829
-                __FUNCTION__,
830
-                __LINE__
831
-            );
832
-            return false;
833
-        }
834
-        return true;
835
-    }
836
-
837
-
838
-
839
-    /**
840
-     * initialize_system_questions
841
-     *
842
-     * @access public
843
-     * @static
844
-     * @return void
845
-     */
846
-    public static function initialize_system_questions()
847
-    {
848
-        // QUESTION GROUPS
849
-        global $wpdb;
850
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
851
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
852
-        // what we have
853
-        $question_groups = $wpdb->get_col($SQL);
854
-        // check the response
855
-        $question_groups = is_array($question_groups) ? $question_groups : array();
856
-        // what we should have
857
-        $QSG_systems = array(1, 2);
858
-        // loop thru what we should have and compare to what we have
859
-        foreach ($QSG_systems as $QSG_system) {
860
-            // reset values array
861
-            $QSG_values = array();
862
-            // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
863
-            if (! in_array("$QSG_system", $question_groups)) {
864
-                // add it
865
-                switch ($QSG_system) {
866
-                    case 1:
867
-                        $QSG_values = array(
868
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
869
-                            'QSG_identifier'      => 'personal-information-' . time(),
870
-                            'QSG_desc'            => '',
871
-                            'QSG_order'           => 1,
872
-                            'QSG_show_group_name' => 1,
873
-                            'QSG_show_group_desc' => 1,
874
-                            'QSG_system'          => EEM_Question_Group::system_personal,
875
-                            'QSG_deleted'         => 0,
876
-                        );
877
-                        break;
878
-                    case 2:
879
-                        $QSG_values = array(
880
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
881
-                            'QSG_identifier'      => 'address-information-' . time(),
882
-                            'QSG_desc'            => '',
883
-                            'QSG_order'           => 2,
884
-                            'QSG_show_group_name' => 1,
885
-                            'QSG_show_group_desc' => 1,
886
-                            'QSG_system'          => EEM_Question_Group::system_address,
887
-                            'QSG_deleted'         => 0,
888
-                        );
889
-                        break;
890
-                }
891
-                // make sure we have some values before inserting them
892
-                if (! empty($QSG_values)) {
893
-                    // insert system question
894
-                    $wpdb->insert(
895
-                        $table_name,
896
-                        $QSG_values,
897
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
898
-                    );
899
-                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
900
-                }
901
-            }
902
-        }
903
-        // QUESTIONS
904
-        global $wpdb;
905
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
906
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
907
-        // what we have
908
-        $questions = $wpdb->get_col($SQL);
909
-        // what we should have
910
-        $QST_systems = array(
911
-            'fname',
912
-            'lname',
913
-            'email',
914
-            'address',
915
-            'address2',
916
-            'city',
917
-            'country',
918
-            'state',
919
-            'zip',
920
-            'phone',
921
-        );
922
-        $order_for_group_1 = 1;
923
-        $order_for_group_2 = 1;
924
-        // loop thru what we should have and compare to what we have
925
-        foreach ($QST_systems as $QST_system) {
926
-            // reset values array
927
-            $QST_values = array();
928
-            // if we don't have what we should have
929
-            if (! in_array($QST_system, $questions)) {
930
-                // add it
931
-                switch ($QST_system) {
932
-                    case 'fname':
933
-                        $QST_values = array(
934
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
935
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
936
-                            'QST_system'        => 'fname',
937
-                            'QST_type'          => 'TEXT',
938
-                            'QST_required'      => 1,
939
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
940
-                            'QST_order'         => 1,
941
-                            'QST_admin_only'    => 0,
942
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
943
-                            'QST_wp_user'       => self::get_default_creator_id(),
944
-                            'QST_deleted'       => 0,
945
-                        );
946
-                        break;
947
-                    case 'lname':
948
-                        $QST_values = array(
949
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
950
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
951
-                            'QST_system'        => 'lname',
952
-                            'QST_type'          => 'TEXT',
953
-                            'QST_required'      => 1,
954
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
955
-                            'QST_order'         => 2,
956
-                            'QST_admin_only'    => 0,
957
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
958
-                            'QST_wp_user'       => self::get_default_creator_id(),
959
-                            'QST_deleted'       => 0,
960
-                        );
961
-                        break;
962
-                    case 'email':
963
-                        $QST_values = array(
964
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
965
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
966
-                            'QST_system'        => 'email',
967
-                            'QST_type'          => 'EMAIL',
968
-                            'QST_required'      => 1,
969
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
970
-                            'QST_order'         => 3,
971
-                            'QST_admin_only'    => 0,
972
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
973
-                            'QST_wp_user'       => self::get_default_creator_id(),
974
-                            'QST_deleted'       => 0,
975
-                        );
976
-                        break;
977
-                    case 'address':
978
-                        $QST_values = array(
979
-                            'QST_display_text'  => __('Address', 'event_espresso'),
980
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
981
-                            'QST_system'        => 'address',
982
-                            'QST_type'          => 'TEXT',
983
-                            'QST_required'      => 0,
984
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
985
-                            'QST_order'         => 4,
986
-                            'QST_admin_only'    => 0,
987
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
988
-                            'QST_wp_user'       => self::get_default_creator_id(),
989
-                            'QST_deleted'       => 0,
990
-                        );
991
-                        break;
992
-                    case 'address2':
993
-                        $QST_values = array(
994
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
995
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
996
-                            'QST_system'        => 'address2',
997
-                            'QST_type'          => 'TEXT',
998
-                            'QST_required'      => 0,
999
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1000
-                            'QST_order'         => 5,
1001
-                            'QST_admin_only'    => 0,
1002
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1003
-                            'QST_wp_user'       => self::get_default_creator_id(),
1004
-                            'QST_deleted'       => 0,
1005
-                        );
1006
-                        break;
1007
-                    case 'city':
1008
-                        $QST_values = array(
1009
-                            'QST_display_text'  => __('City', 'event_espresso'),
1010
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1011
-                            'QST_system'        => 'city',
1012
-                            'QST_type'          => 'TEXT',
1013
-                            'QST_required'      => 0,
1014
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1015
-                            'QST_order'         => 6,
1016
-                            'QST_admin_only'    => 0,
1017
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1018
-                            'QST_wp_user'       => self::get_default_creator_id(),
1019
-                            'QST_deleted'       => 0,
1020
-                        );
1021
-                        break;
1022
-                    case 'country':
1023
-                        $QST_values = array(
1024
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1025
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1026
-                            'QST_system'        => 'country',
1027
-                            'QST_type'          => 'COUNTRY',
1028
-                            'QST_required'      => 0,
1029
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1030
-                            'QST_order'         => 7,
1031
-                            'QST_admin_only'    => 0,
1032
-                            'QST_wp_user'       => self::get_default_creator_id(),
1033
-                            'QST_deleted'       => 0,
1034
-                        );
1035
-                        break;
1036
-                    case 'state':
1037
-                        $QST_values = array(
1038
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1039
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1040
-                            'QST_system'        => 'state',
1041
-                            'QST_type'          => 'STATE',
1042
-                            'QST_required'      => 0,
1043
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1044
-                            'QST_order'         => 8,
1045
-                            'QST_admin_only'    => 0,
1046
-                            'QST_wp_user'       => self::get_default_creator_id(),
1047
-                            'QST_deleted'       => 0,
1048
-                        );
1049
-                        break;
1050
-                    case 'zip':
1051
-                        $QST_values = array(
1052
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1053
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1054
-                            'QST_system'        => 'zip',
1055
-                            'QST_type'          => 'TEXT',
1056
-                            'QST_required'      => 0,
1057
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1058
-                            'QST_order'         => 9,
1059
-                            'QST_admin_only'    => 0,
1060
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1061
-                            'QST_wp_user'       => self::get_default_creator_id(),
1062
-                            'QST_deleted'       => 0,
1063
-                        );
1064
-                        break;
1065
-                    case 'phone':
1066
-                        $QST_values = array(
1067
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1068
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1069
-                            'QST_system'        => 'phone',
1070
-                            'QST_type'          => 'TEXT',
1071
-                            'QST_required'      => 0,
1072
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1073
-                            'QST_order'         => 10,
1074
-                            'QST_admin_only'    => 0,
1075
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1076
-                            'QST_wp_user'       => self::get_default_creator_id(),
1077
-                            'QST_deleted'       => 0,
1078
-                        );
1079
-                        break;
1080
-                }
1081
-                if (! empty($QST_values)) {
1082
-                    // insert system question
1083
-                    $wpdb->insert(
1084
-                        $table_name,
1085
-                        $QST_values,
1086
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1087
-                    );
1088
-                    $QST_ID = $wpdb->insert_id;
1089
-                    // QUESTION GROUP QUESTIONS
1090
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1091
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1092
-                    } else {
1093
-                        $system_question_we_want = EEM_Question_Group::system_address;
1094
-                    }
1095
-                    if (isset($QSG_IDs[$system_question_we_want])) {
1096
-                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1097
-                    } else {
1098
-                        $id_col = EEM_Question_Group::instance()
1099
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1100
-                        if (is_array($id_col)) {
1101
-                            $QSG_ID = reset($id_col);
1102
-                        } else {
1103
-                            //ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1104
-                            EE_Log::instance()->log(
1105
-                                __FILE__,
1106
-                                __FUNCTION__,
1107
-                                sprintf(
1108
-                                    __(
1109
-                                        'Could not associate question %1$s to a question group because no system question
826
+					'event_espresso'
827
+				),
828
+				__FILE__,
829
+				__FUNCTION__,
830
+				__LINE__
831
+			);
832
+			return false;
833
+		}
834
+		return true;
835
+	}
836
+
837
+
838
+
839
+	/**
840
+	 * initialize_system_questions
841
+	 *
842
+	 * @access public
843
+	 * @static
844
+	 * @return void
845
+	 */
846
+	public static function initialize_system_questions()
847
+	{
848
+		// QUESTION GROUPS
849
+		global $wpdb;
850
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
851
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
852
+		// what we have
853
+		$question_groups = $wpdb->get_col($SQL);
854
+		// check the response
855
+		$question_groups = is_array($question_groups) ? $question_groups : array();
856
+		// what we should have
857
+		$QSG_systems = array(1, 2);
858
+		// loop thru what we should have and compare to what we have
859
+		foreach ($QSG_systems as $QSG_system) {
860
+			// reset values array
861
+			$QSG_values = array();
862
+			// if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
863
+			if (! in_array("$QSG_system", $question_groups)) {
864
+				// add it
865
+				switch ($QSG_system) {
866
+					case 1:
867
+						$QSG_values = array(
868
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
869
+							'QSG_identifier'      => 'personal-information-' . time(),
870
+							'QSG_desc'            => '',
871
+							'QSG_order'           => 1,
872
+							'QSG_show_group_name' => 1,
873
+							'QSG_show_group_desc' => 1,
874
+							'QSG_system'          => EEM_Question_Group::system_personal,
875
+							'QSG_deleted'         => 0,
876
+						);
877
+						break;
878
+					case 2:
879
+						$QSG_values = array(
880
+							'QSG_name'            => __('Address Information', 'event_espresso'),
881
+							'QSG_identifier'      => 'address-information-' . time(),
882
+							'QSG_desc'            => '',
883
+							'QSG_order'           => 2,
884
+							'QSG_show_group_name' => 1,
885
+							'QSG_show_group_desc' => 1,
886
+							'QSG_system'          => EEM_Question_Group::system_address,
887
+							'QSG_deleted'         => 0,
888
+						);
889
+						break;
890
+				}
891
+				// make sure we have some values before inserting them
892
+				if (! empty($QSG_values)) {
893
+					// insert system question
894
+					$wpdb->insert(
895
+						$table_name,
896
+						$QSG_values,
897
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
898
+					);
899
+					$QSG_IDs[$QSG_system] = $wpdb->insert_id;
900
+				}
901
+			}
902
+		}
903
+		// QUESTIONS
904
+		global $wpdb;
905
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
906
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
907
+		// what we have
908
+		$questions = $wpdb->get_col($SQL);
909
+		// what we should have
910
+		$QST_systems = array(
911
+			'fname',
912
+			'lname',
913
+			'email',
914
+			'address',
915
+			'address2',
916
+			'city',
917
+			'country',
918
+			'state',
919
+			'zip',
920
+			'phone',
921
+		);
922
+		$order_for_group_1 = 1;
923
+		$order_for_group_2 = 1;
924
+		// loop thru what we should have and compare to what we have
925
+		foreach ($QST_systems as $QST_system) {
926
+			// reset values array
927
+			$QST_values = array();
928
+			// if we don't have what we should have
929
+			if (! in_array($QST_system, $questions)) {
930
+				// add it
931
+				switch ($QST_system) {
932
+					case 'fname':
933
+						$QST_values = array(
934
+							'QST_display_text'  => __('First Name', 'event_espresso'),
935
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
936
+							'QST_system'        => 'fname',
937
+							'QST_type'          => 'TEXT',
938
+							'QST_required'      => 1,
939
+							'QST_required_text' => __('This field is required', 'event_espresso'),
940
+							'QST_order'         => 1,
941
+							'QST_admin_only'    => 0,
942
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
943
+							'QST_wp_user'       => self::get_default_creator_id(),
944
+							'QST_deleted'       => 0,
945
+						);
946
+						break;
947
+					case 'lname':
948
+						$QST_values = array(
949
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
950
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
951
+							'QST_system'        => 'lname',
952
+							'QST_type'          => 'TEXT',
953
+							'QST_required'      => 1,
954
+							'QST_required_text' => __('This field is required', 'event_espresso'),
955
+							'QST_order'         => 2,
956
+							'QST_admin_only'    => 0,
957
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
958
+							'QST_wp_user'       => self::get_default_creator_id(),
959
+							'QST_deleted'       => 0,
960
+						);
961
+						break;
962
+					case 'email':
963
+						$QST_values = array(
964
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
965
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
966
+							'QST_system'        => 'email',
967
+							'QST_type'          => 'EMAIL',
968
+							'QST_required'      => 1,
969
+							'QST_required_text' => __('This field is required', 'event_espresso'),
970
+							'QST_order'         => 3,
971
+							'QST_admin_only'    => 0,
972
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
973
+							'QST_wp_user'       => self::get_default_creator_id(),
974
+							'QST_deleted'       => 0,
975
+						);
976
+						break;
977
+					case 'address':
978
+						$QST_values = array(
979
+							'QST_display_text'  => __('Address', 'event_espresso'),
980
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
981
+							'QST_system'        => 'address',
982
+							'QST_type'          => 'TEXT',
983
+							'QST_required'      => 0,
984
+							'QST_required_text' => __('This field is required', 'event_espresso'),
985
+							'QST_order'         => 4,
986
+							'QST_admin_only'    => 0,
987
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
988
+							'QST_wp_user'       => self::get_default_creator_id(),
989
+							'QST_deleted'       => 0,
990
+						);
991
+						break;
992
+					case 'address2':
993
+						$QST_values = array(
994
+							'QST_display_text'  => __('Address2', 'event_espresso'),
995
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
996
+							'QST_system'        => 'address2',
997
+							'QST_type'          => 'TEXT',
998
+							'QST_required'      => 0,
999
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1000
+							'QST_order'         => 5,
1001
+							'QST_admin_only'    => 0,
1002
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1003
+							'QST_wp_user'       => self::get_default_creator_id(),
1004
+							'QST_deleted'       => 0,
1005
+						);
1006
+						break;
1007
+					case 'city':
1008
+						$QST_values = array(
1009
+							'QST_display_text'  => __('City', 'event_espresso'),
1010
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1011
+							'QST_system'        => 'city',
1012
+							'QST_type'          => 'TEXT',
1013
+							'QST_required'      => 0,
1014
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1015
+							'QST_order'         => 6,
1016
+							'QST_admin_only'    => 0,
1017
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1018
+							'QST_wp_user'       => self::get_default_creator_id(),
1019
+							'QST_deleted'       => 0,
1020
+						);
1021
+						break;
1022
+					case 'country':
1023
+						$QST_values = array(
1024
+							'QST_display_text'  => __('Country', 'event_espresso'),
1025
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1026
+							'QST_system'        => 'country',
1027
+							'QST_type'          => 'COUNTRY',
1028
+							'QST_required'      => 0,
1029
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1030
+							'QST_order'         => 7,
1031
+							'QST_admin_only'    => 0,
1032
+							'QST_wp_user'       => self::get_default_creator_id(),
1033
+							'QST_deleted'       => 0,
1034
+						);
1035
+						break;
1036
+					case 'state':
1037
+						$QST_values = array(
1038
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1039
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1040
+							'QST_system'        => 'state',
1041
+							'QST_type'          => 'STATE',
1042
+							'QST_required'      => 0,
1043
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1044
+							'QST_order'         => 8,
1045
+							'QST_admin_only'    => 0,
1046
+							'QST_wp_user'       => self::get_default_creator_id(),
1047
+							'QST_deleted'       => 0,
1048
+						);
1049
+						break;
1050
+					case 'zip':
1051
+						$QST_values = array(
1052
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1053
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1054
+							'QST_system'        => 'zip',
1055
+							'QST_type'          => 'TEXT',
1056
+							'QST_required'      => 0,
1057
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1058
+							'QST_order'         => 9,
1059
+							'QST_admin_only'    => 0,
1060
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1061
+							'QST_wp_user'       => self::get_default_creator_id(),
1062
+							'QST_deleted'       => 0,
1063
+						);
1064
+						break;
1065
+					case 'phone':
1066
+						$QST_values = array(
1067
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1068
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1069
+							'QST_system'        => 'phone',
1070
+							'QST_type'          => 'TEXT',
1071
+							'QST_required'      => 0,
1072
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1073
+							'QST_order'         => 10,
1074
+							'QST_admin_only'    => 0,
1075
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1076
+							'QST_wp_user'       => self::get_default_creator_id(),
1077
+							'QST_deleted'       => 0,
1078
+						);
1079
+						break;
1080
+				}
1081
+				if (! empty($QST_values)) {
1082
+					// insert system question
1083
+					$wpdb->insert(
1084
+						$table_name,
1085
+						$QST_values,
1086
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1087
+					);
1088
+					$QST_ID = $wpdb->insert_id;
1089
+					// QUESTION GROUP QUESTIONS
1090
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1091
+						$system_question_we_want = EEM_Question_Group::system_personal;
1092
+					} else {
1093
+						$system_question_we_want = EEM_Question_Group::system_address;
1094
+					}
1095
+					if (isset($QSG_IDs[$system_question_we_want])) {
1096
+						$QSG_ID = $QSG_IDs[$system_question_we_want];
1097
+					} else {
1098
+						$id_col = EEM_Question_Group::instance()
1099
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1100
+						if (is_array($id_col)) {
1101
+							$QSG_ID = reset($id_col);
1102
+						} else {
1103
+							//ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1104
+							EE_Log::instance()->log(
1105
+								__FILE__,
1106
+								__FUNCTION__,
1107
+								sprintf(
1108
+									__(
1109
+										'Could not associate question %1$s to a question group because no system question
1110 1110
                                          group existed',
1111
-                                        'event_espresso'
1112
-                                    ),
1113
-                                    $QST_ID),
1114
-                                'error');
1115
-                            continue;
1116
-                        }
1117
-                    }
1118
-                    // add system questions to groups
1119
-                    $wpdb->insert(
1120
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1121
-                        array(
1122
-                            'QSG_ID'    => $QSG_ID,
1123
-                            'QST_ID'    => $QST_ID,
1124
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1125
-                        ),
1126
-                        array('%d', '%d', '%d')
1127
-                    );
1128
-                }
1129
-            }
1130
-        }
1131
-    }
1132
-
1133
-
1134
-    /**
1135
-     * Makes sure the default payment method (Invoice) is active.
1136
-     * This used to be done automatically as part of constructing the old gateways config
1137
-     *
1138
-     * @throws \EE_Error
1139
-     */
1140
-    public static function insert_default_payment_methods()
1141
-    {
1142
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1143
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1144
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1145
-        } else {
1146
-            EEM_Payment_Method::instance()->verify_button_urls();
1147
-        }
1148
-    }
1149
-
1150
-    /**
1151
-     * insert_default_status_codes
1152
-     *
1153
-     * @access public
1154
-     * @static
1155
-     * @return void
1156
-     */
1157
-    public static function insert_default_status_codes()
1158
-    {
1159
-
1160
-        global $wpdb;
1161
-
1162
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1163
-
1164
-            $table_name = EEM_Status::instance()->table();
1165
-
1166
-            $SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1167
-            $wpdb->query($SQL);
1168
-
1169
-            $SQL = "INSERT INTO $table_name
1111
+										'event_espresso'
1112
+									),
1113
+									$QST_ID),
1114
+								'error');
1115
+							continue;
1116
+						}
1117
+					}
1118
+					// add system questions to groups
1119
+					$wpdb->insert(
1120
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1121
+						array(
1122
+							'QSG_ID'    => $QSG_ID,
1123
+							'QST_ID'    => $QST_ID,
1124
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1125
+						),
1126
+						array('%d', '%d', '%d')
1127
+					);
1128
+				}
1129
+			}
1130
+		}
1131
+	}
1132
+
1133
+
1134
+	/**
1135
+	 * Makes sure the default payment method (Invoice) is active.
1136
+	 * This used to be done automatically as part of constructing the old gateways config
1137
+	 *
1138
+	 * @throws \EE_Error
1139
+	 */
1140
+	public static function insert_default_payment_methods()
1141
+	{
1142
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1143
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1144
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1145
+		} else {
1146
+			EEM_Payment_Method::instance()->verify_button_urls();
1147
+		}
1148
+	}
1149
+
1150
+	/**
1151
+	 * insert_default_status_codes
1152
+	 *
1153
+	 * @access public
1154
+	 * @static
1155
+	 * @return void
1156
+	 */
1157
+	public static function insert_default_status_codes()
1158
+	{
1159
+
1160
+		global $wpdb;
1161
+
1162
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1163
+
1164
+			$table_name = EEM_Status::instance()->table();
1165
+
1166
+			$SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1167
+			$wpdb->query($SQL);
1168
+
1169
+			$SQL = "INSERT INTO $table_name
1170 1170
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1171 1171
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1172 1172
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1206,462 +1206,462 @@  discard block
 block discarded – undo
1206 1206
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1207 1207
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1208 1208
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1209
-            $wpdb->query($SQL);
1210
-
1211
-        }
1212
-
1213
-    }
1214
-
1215
-
1216
-    /**
1217
-     * generate_default_message_templates
1218
-     *
1219
-     * @static
1220
-     * @throws EE_Error
1221
-     * @return bool     true means new templates were created.
1222
-     *                  false means no templates were created.
1223
-     *                  This is NOT an error flag. To check for errors you will want
1224
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1225
-     */
1226
-    public static function generate_default_message_templates()
1227
-    {
1228
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1229
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1230
-        /*
1209
+			$wpdb->query($SQL);
1210
+
1211
+		}
1212
+
1213
+	}
1214
+
1215
+
1216
+	/**
1217
+	 * generate_default_message_templates
1218
+	 *
1219
+	 * @static
1220
+	 * @throws EE_Error
1221
+	 * @return bool     true means new templates were created.
1222
+	 *                  false means no templates were created.
1223
+	 *                  This is NOT an error flag. To check for errors you will want
1224
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1225
+	 */
1226
+	public static function generate_default_message_templates()
1227
+	{
1228
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1229
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1230
+		/*
1231 1231
          * This first method is taking care of ensuring any default messengers
1232 1232
          * that should be made active and have templates generated are done.
1233 1233
          */
1234
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1235
-            $message_resource_manager
1236
-        );
1237
-        /**
1238
-         * This method is verifying there are no NEW default message types
1239
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1240
-         */
1241
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1242
-            $message_resource_manager
1243
-        );
1244
-        //after all is done, let's persist these changes to the db.
1245
-        $message_resource_manager->update_has_activated_messengers_option();
1246
-        $message_resource_manager->update_active_messengers_option();
1247
-        // will return true if either of these are true.  Otherwise will return false.
1248
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1249
-    }
1250
-
1251
-
1252
-
1253
-    /**
1254
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1255
-     * @return array|bool
1256
-     * @throws \EE_Error
1257
-     */
1258
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1259
-        EE_Message_Resource_Manager $message_resource_manager
1260
-    ) {
1261
-        /** @type EE_messenger[] $active_messengers */
1262
-        $active_messengers = $message_resource_manager->active_messengers();
1263
-        $installed_message_types = $message_resource_manager->installed_message_types();
1264
-        $templates_created = false;
1265
-        foreach ($active_messengers as $active_messenger) {
1266
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1267
-            $default_message_type_names_to_activate = array();
1268
-            // looping through each default message type reported by the messenger
1269
-            // and setup the actual message types to activate.
1270
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1271
-                // if already active or has already been activated before we skip
1272
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1273
-                // we also skip if the message type is not installed.
1274
-                if (
1275
-                    $message_resource_manager->has_message_type_been_activated_for_messenger(
1276
-                        $default_message_type_name_for_messenger,
1277
-                        $active_messenger->name
1278
-                    )
1279
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1280
-                        $active_messenger->name,
1281
-                        $default_message_type_name_for_messenger
1282
-                    )
1283
-                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1284
-                ) {
1285
-                    continue;
1286
-                }
1287
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1288
-            }
1289
-            //let's activate!
1290
-            $message_resource_manager->ensure_message_types_are_active(
1291
-                $default_message_type_names_to_activate,
1292
-                $active_messenger->name,
1293
-                false
1294
-            );
1295
-            //activate the templates for these message types
1296
-            if ( ! empty($default_message_type_names_to_activate)) {
1297
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1298
-                    $active_messenger->name,
1299
-                    $default_message_type_names_for_messenger,
1300
-                    '',
1301
-                    true
1302
-                );
1303
-            }
1304
-        }
1305
-        return $templates_created;
1306
-    }
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * This will activate and generate default messengers and default message types for those messengers.
1312
-     *
1313
-     * @param EE_message_Resource_Manager $message_resource_manager
1314
-     * @return array|bool  True means there were default messengers and message type templates generated.
1315
-     *                     False means that there were no templates generated
1316
-     *                     (which could simply mean there are no default message types for a messenger).
1317
-     * @throws EE_Error
1318
-     */
1319
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1320
-        EE_Message_Resource_Manager $message_resource_manager
1321
-    ) {
1322
-        /** @type EE_messenger[] $messengers_to_generate */
1323
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1324
-        $installed_message_types = $message_resource_manager->installed_message_types();
1325
-        $templates_generated = false;
1326
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1327
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1328
-            //verify the default message types match an installed message type.
1329
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1330
-                if (
1331
-                    ! isset($installed_message_types[$name])
1332
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1333
-                        $name,
1334
-                        $messenger_to_generate->name
1335
-                    )
1336
-                ) {
1337
-                    unset($default_message_type_names_for_messenger[$key]);
1338
-                }
1339
-            }
1340
-            // in previous iterations, the active_messengers option in the db
1341
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1342
-            // This comment is left here just in case we discover that we _do_ need to update before
1343
-            // passing off to create templates (after the refactor is done).
1344
-            // @todo remove this comment when determined not necessary.
1345
-            $message_resource_manager->activate_messenger(
1346
-                $messenger_to_generate->name,
1347
-                $default_message_type_names_for_messenger,
1348
-                false
1349
-            );
1350
-            //create any templates needing created (or will reactivate templates already generated as necessary).
1351
-            if ( ! empty($default_message_type_names_for_messenger)) {
1352
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1353
-                    $messenger_to_generate->name,
1354
-                    $default_message_type_names_for_messenger,
1355
-                    '',
1356
-                    true
1357
-                );
1358
-            }
1359
-        }
1360
-        return $templates_generated;
1361
-    }
1362
-
1363
-
1364
-    /**
1365
-     * This returns the default messengers to generate templates for on activation of EE.
1366
-     * It considers:
1367
-     * - whether a messenger is already active in the db.
1368
-     * - whether a messenger has been made active at any time in the past.
1369
-     *
1370
-     * @static
1371
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1372
-     * @return EE_messenger[]
1373
-     */
1374
-    protected static function _get_default_messengers_to_generate_on_activation(
1375
-        EE_Message_Resource_Manager $message_resource_manager
1376
-    ) {
1377
-        $active_messengers    = $message_resource_manager->active_messengers();
1378
-        $installed_messengers = $message_resource_manager->installed_messengers();
1379
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1380
-
1381
-        $messengers_to_generate = array();
1382
-        foreach ($installed_messengers as $installed_messenger) {
1383
-            //if installed messenger is a messenger that should be activated on install
1384
-            //and is not already active
1385
-            //and has never been activated
1386
-            if (
1387
-                ! $installed_messenger->activate_on_install
1388
-                || isset($active_messengers[$installed_messenger->name])
1389
-                || isset($has_activated[$installed_messenger->name])
1390
-            ) {
1391
-                continue;
1392
-            }
1393
-            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1394
-        }
1395
-        return $messengers_to_generate;
1396
-    }
1397
-
1398
-
1399
-    /**
1400
-     * This simply validates active message types to ensure they actually match installed
1401
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1402
-     * rows are set inactive.
1403
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1404
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1405
-     * are still handled in here.
1406
-     *
1407
-     * @since 4.3.1
1408
-     * @return void
1409
-     */
1410
-    public static function validate_messages_system()
1411
-    {
1412
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1413
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1414
-        $message_resource_manager->validate_active_message_types_are_installed();
1415
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1416
-    }
1417
-
1418
-
1419
-    /**
1420
-     * create_no_ticket_prices_array
1421
-     *
1422
-     * @access public
1423
-     * @static
1424
-     * @return void
1425
-     */
1426
-    public static function create_no_ticket_prices_array()
1427
-    {
1428
-        // this creates an array for tracking events that have no active ticket prices created
1429
-        // this allows us to warn admins of the situation so that it can be corrected
1430
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1431
-        if (! $espresso_no_ticket_prices) {
1432
-            add_option('ee_no_ticket_prices', array(), '', false);
1433
-        }
1434
-    }
1435
-
1436
-
1437
-    /**
1438
-     * plugin_deactivation
1439
-     *
1440
-     * @access public
1441
-     * @static
1442
-     * @return void
1443
-     */
1444
-    public static function plugin_deactivation()
1445
-    {
1446
-    }
1447
-
1448
-
1449
-    /**
1450
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1451
-     * (like post meta or term relations)
1452
-     *
1453
-     * @global wpdb $wpdb
1454
-     * @throws \EE_Error
1455
-     */
1456
-    public static function delete_all_espresso_cpt_data()
1457
-    {
1458
-        global $wpdb;
1459
-        //get all the CPT post_types
1460
-        $ee_post_types = array();
1461
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1462
-            if (method_exists($model_name, 'instance')) {
1463
-                $model_obj = call_user_func(array($model_name, 'instance'));
1464
-                if ($model_obj instanceof EEM_CPT_Base) {
1465
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1466
-                }
1467
-            }
1468
-        }
1469
-        //get all our CPTs
1470
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1471
-        $cpt_ids = $wpdb->get_col($query);
1472
-        //delete each post meta and term relations too
1473
-        foreach ($cpt_ids as $post_id) {
1474
-            wp_delete_post($post_id, true);
1475
-        }
1476
-    }
1477
-
1478
-    /**
1479
-     * Deletes all EE custom tables
1480
-     *
1481
-     * @return array
1482
-     */
1483
-    public static function drop_espresso_tables()
1484
-    {
1485
-        $tables = array();
1486
-        // load registry
1487
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1488
-            if (method_exists($model_name, 'instance')) {
1489
-                $model_obj = call_user_func(array($model_name, 'instance'));
1490
-                if ($model_obj instanceof EEM_Base) {
1491
-                    foreach ($model_obj->get_tables() as $table) {
1492
-                        if (strpos($table->get_table_name(), 'esp_')
1493
-                            &&
1494
-                            (
1495
-                                is_main_site()//main site? nuke them all
1496
-                                || ! $table->is_global()//not main site,but not global either. nuke it
1497
-                            )
1498
-                        ) {
1499
-                            $tables[$table->get_table_name()] = $table->get_table_name();
1500
-                        }
1501
-                    }
1502
-                }
1503
-            }
1504
-        }
1505
-
1506
-        //there are some tables whose models were removed.
1507
-        //they should be removed when removing all EE core's data
1508
-        $tables_without_models = array(
1509
-            'esp_promotion',
1510
-            'esp_promotion_applied',
1511
-            'esp_promotion_object',
1512
-            'esp_promotion_rule',
1513
-            'esp_rule',
1514
-        );
1515
-        foreach ($tables_without_models as $table) {
1516
-            $tables[$table] = $table;
1517
-        }
1518
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1519
-    }
1520
-
1521
-
1522
-
1523
-    /**
1524
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1525
-     * each table name provided has a wpdb prefix attached, and that it exists.
1526
-     * Returns the list actually deleted
1527
-     *
1528
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1529
-     * @global WPDB $wpdb
1530
-     * @param array $table_names
1531
-     * @return array of table names which we deleted
1532
-     */
1533
-    public static function drop_tables($table_names)
1534
-    {
1535
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1536
-    }
1537
-
1538
-
1539
-
1540
-    /**
1541
-     * plugin_uninstall
1542
-     *
1543
-     * @access public
1544
-     * @static
1545
-     * @param bool $remove_all
1546
-     * @return void
1547
-     */
1548
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1549
-    {
1550
-        global $wpdb;
1551
-        self::drop_espresso_tables();
1552
-        $wp_options_to_delete = array(
1553
-            'ee_no_ticket_prices'                => true,
1554
-            'ee_active_messengers'               => true,
1555
-            'ee_has_activated_messenger'         => true,
1556
-            RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1557
-            'ee_config'                          => false,
1558
-            'ee_data_migration_current_db_state' => true,
1559
-            'ee_data_migration_mapping_'         => false,
1560
-            'ee_data_migration_script_'          => false,
1561
-            'ee_data_migrations'                 => true,
1562
-            'ee_dms_map'                         => false,
1563
-            'ee_notices'                         => true,
1564
-            'lang_file_check_'                   => false,
1565
-            'ee_maintenance_mode'                => true,
1566
-            'ee_ueip_optin'                      => true,
1567
-            'ee_ueip_has_notified'               => true,
1568
-            'ee_plugin_activation_errors'        => true,
1569
-            'ee_id_mapping_from'                 => false,
1570
-            'espresso_persistent_admin_notices'  => true,
1571
-            'ee_encryption_key'                  => true,
1572
-            'pue_force_upgrade_'                 => false,
1573
-            'pue_json_error_'                    => false,
1574
-            'pue_install_key_'                   => false,
1575
-            'pue_verification_error_'            => false,
1576
-            'pu_dismissed_upgrade_'              => false,
1577
-            'external_updates-'                  => false,
1578
-            'ee_extra_data'                      => true,
1579
-            'ee_ssn_'                            => false,
1580
-            'ee_rss_'                            => false,
1581
-            'ee_rte_n_tx_'                       => false,
1582
-            'ee_pers_admin_notices'              => true,
1583
-            'ee_job_parameters_'                 => false,
1584
-            'ee_upload_directories_incomplete'   => true,
1585
-            'ee_verified_db_collations'          => true,
1586
-        );
1587
-        if (is_main_site()) {
1588
-            $wp_options_to_delete['ee_network_config'] = true;
1589
-        }
1590
-        $undeleted_options = array();
1591
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1592
-            if ($no_wildcard) {
1593
-                if ( ! delete_option($option_name)) {
1594
-                    $undeleted_options[] = $option_name;
1595
-                }
1596
-            } else {
1597
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1598
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1599
-                    if ( ! delete_option($option_name_from_wildcard)) {
1600
-                        $undeleted_options[] = $option_name_from_wildcard;
1601
-                    }
1602
-                }
1603
-            }
1604
-        }
1605
-        //also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1606
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1607
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1608
-            $db_update_sans_ee4 = array();
1609
-            foreach ($espresso_db_update as $version => $times_activated) {
1610
-                if ((string)$version[0] === '3') {//if its NON EE4
1611
-                    $db_update_sans_ee4[$version] = $times_activated;
1612
-                }
1613
-            }
1614
-            update_option('espresso_db_update', $db_update_sans_ee4);
1615
-        }
1616
-        $errors = '';
1617
-        if ( ! empty($undeleted_options)) {
1618
-            $errors .= sprintf(
1619
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1620
-                '<br/>',
1621
-                implode(',<br/>', $undeleted_options)
1622
-            );
1623
-        }
1624
-        if ( ! empty($errors)) {
1625
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1626
-        }
1627
-    }
1628
-
1629
-    /**
1630
-     * Gets the mysql error code from the last used query by wpdb
1631
-     *
1632
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1633
-     */
1634
-    public static function last_wpdb_error_code()
1635
-    {
1636
-        global $wpdb;
1637
-        if ($wpdb->use_mysqli) {
1638
-            return mysqli_errno($wpdb->dbh);
1639
-        } else {
1640
-            return mysql_errno($wpdb->dbh);
1641
-        }
1642
-    }
1643
-
1644
-    /**
1645
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1646
-     *
1647
-     * @global wpdb  $wpdb
1648
-     * @deprecated instead use TableAnalysis::tableExists()
1649
-     * @param string $table_name with or without $wpdb->prefix
1650
-     * @return boolean
1651
-     */
1652
-    public static function table_exists($table_name)
1653
-    {
1654
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1655
-    }
1656
-
1657
-    /**
1658
-     * Resets the cache on EEH_Activation
1659
-     */
1660
-    public static function reset()
1661
-    {
1662
-        self::$_default_creator_id                             = null;
1663
-        self::$_initialized_db_content_already_in_this_request = false;
1664
-    }
1234
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1235
+			$message_resource_manager
1236
+		);
1237
+		/**
1238
+		 * This method is verifying there are no NEW default message types
1239
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1240
+		 */
1241
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1242
+			$message_resource_manager
1243
+		);
1244
+		//after all is done, let's persist these changes to the db.
1245
+		$message_resource_manager->update_has_activated_messengers_option();
1246
+		$message_resource_manager->update_active_messengers_option();
1247
+		// will return true if either of these are true.  Otherwise will return false.
1248
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1249
+	}
1250
+
1251
+
1252
+
1253
+	/**
1254
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1255
+	 * @return array|bool
1256
+	 * @throws \EE_Error
1257
+	 */
1258
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1259
+		EE_Message_Resource_Manager $message_resource_manager
1260
+	) {
1261
+		/** @type EE_messenger[] $active_messengers */
1262
+		$active_messengers = $message_resource_manager->active_messengers();
1263
+		$installed_message_types = $message_resource_manager->installed_message_types();
1264
+		$templates_created = false;
1265
+		foreach ($active_messengers as $active_messenger) {
1266
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1267
+			$default_message_type_names_to_activate = array();
1268
+			// looping through each default message type reported by the messenger
1269
+			// and setup the actual message types to activate.
1270
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1271
+				// if already active or has already been activated before we skip
1272
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1273
+				// we also skip if the message type is not installed.
1274
+				if (
1275
+					$message_resource_manager->has_message_type_been_activated_for_messenger(
1276
+						$default_message_type_name_for_messenger,
1277
+						$active_messenger->name
1278
+					)
1279
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1280
+						$active_messenger->name,
1281
+						$default_message_type_name_for_messenger
1282
+					)
1283
+					|| ! isset($installed_message_types[$default_message_type_name_for_messenger])
1284
+				) {
1285
+					continue;
1286
+				}
1287
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1288
+			}
1289
+			//let's activate!
1290
+			$message_resource_manager->ensure_message_types_are_active(
1291
+				$default_message_type_names_to_activate,
1292
+				$active_messenger->name,
1293
+				false
1294
+			);
1295
+			//activate the templates for these message types
1296
+			if ( ! empty($default_message_type_names_to_activate)) {
1297
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1298
+					$active_messenger->name,
1299
+					$default_message_type_names_for_messenger,
1300
+					'',
1301
+					true
1302
+				);
1303
+			}
1304
+		}
1305
+		return $templates_created;
1306
+	}
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * This will activate and generate default messengers and default message types for those messengers.
1312
+	 *
1313
+	 * @param EE_message_Resource_Manager $message_resource_manager
1314
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1315
+	 *                     False means that there were no templates generated
1316
+	 *                     (which could simply mean there are no default message types for a messenger).
1317
+	 * @throws EE_Error
1318
+	 */
1319
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1320
+		EE_Message_Resource_Manager $message_resource_manager
1321
+	) {
1322
+		/** @type EE_messenger[] $messengers_to_generate */
1323
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1324
+		$installed_message_types = $message_resource_manager->installed_message_types();
1325
+		$templates_generated = false;
1326
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1327
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1328
+			//verify the default message types match an installed message type.
1329
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1330
+				if (
1331
+					! isset($installed_message_types[$name])
1332
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1333
+						$name,
1334
+						$messenger_to_generate->name
1335
+					)
1336
+				) {
1337
+					unset($default_message_type_names_for_messenger[$key]);
1338
+				}
1339
+			}
1340
+			// in previous iterations, the active_messengers option in the db
1341
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1342
+			// This comment is left here just in case we discover that we _do_ need to update before
1343
+			// passing off to create templates (after the refactor is done).
1344
+			// @todo remove this comment when determined not necessary.
1345
+			$message_resource_manager->activate_messenger(
1346
+				$messenger_to_generate->name,
1347
+				$default_message_type_names_for_messenger,
1348
+				false
1349
+			);
1350
+			//create any templates needing created (or will reactivate templates already generated as necessary).
1351
+			if ( ! empty($default_message_type_names_for_messenger)) {
1352
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1353
+					$messenger_to_generate->name,
1354
+					$default_message_type_names_for_messenger,
1355
+					'',
1356
+					true
1357
+				);
1358
+			}
1359
+		}
1360
+		return $templates_generated;
1361
+	}
1362
+
1363
+
1364
+	/**
1365
+	 * This returns the default messengers to generate templates for on activation of EE.
1366
+	 * It considers:
1367
+	 * - whether a messenger is already active in the db.
1368
+	 * - whether a messenger has been made active at any time in the past.
1369
+	 *
1370
+	 * @static
1371
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1372
+	 * @return EE_messenger[]
1373
+	 */
1374
+	protected static function _get_default_messengers_to_generate_on_activation(
1375
+		EE_Message_Resource_Manager $message_resource_manager
1376
+	) {
1377
+		$active_messengers    = $message_resource_manager->active_messengers();
1378
+		$installed_messengers = $message_resource_manager->installed_messengers();
1379
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1380
+
1381
+		$messengers_to_generate = array();
1382
+		foreach ($installed_messengers as $installed_messenger) {
1383
+			//if installed messenger is a messenger that should be activated on install
1384
+			//and is not already active
1385
+			//and has never been activated
1386
+			if (
1387
+				! $installed_messenger->activate_on_install
1388
+				|| isset($active_messengers[$installed_messenger->name])
1389
+				|| isset($has_activated[$installed_messenger->name])
1390
+			) {
1391
+				continue;
1392
+			}
1393
+			$messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1394
+		}
1395
+		return $messengers_to_generate;
1396
+	}
1397
+
1398
+
1399
+	/**
1400
+	 * This simply validates active message types to ensure they actually match installed
1401
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1402
+	 * rows are set inactive.
1403
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1404
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1405
+	 * are still handled in here.
1406
+	 *
1407
+	 * @since 4.3.1
1408
+	 * @return void
1409
+	 */
1410
+	public static function validate_messages_system()
1411
+	{
1412
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1413
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1414
+		$message_resource_manager->validate_active_message_types_are_installed();
1415
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1416
+	}
1417
+
1418
+
1419
+	/**
1420
+	 * create_no_ticket_prices_array
1421
+	 *
1422
+	 * @access public
1423
+	 * @static
1424
+	 * @return void
1425
+	 */
1426
+	public static function create_no_ticket_prices_array()
1427
+	{
1428
+		// this creates an array for tracking events that have no active ticket prices created
1429
+		// this allows us to warn admins of the situation so that it can be corrected
1430
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1431
+		if (! $espresso_no_ticket_prices) {
1432
+			add_option('ee_no_ticket_prices', array(), '', false);
1433
+		}
1434
+	}
1435
+
1436
+
1437
+	/**
1438
+	 * plugin_deactivation
1439
+	 *
1440
+	 * @access public
1441
+	 * @static
1442
+	 * @return void
1443
+	 */
1444
+	public static function plugin_deactivation()
1445
+	{
1446
+	}
1447
+
1448
+
1449
+	/**
1450
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1451
+	 * (like post meta or term relations)
1452
+	 *
1453
+	 * @global wpdb $wpdb
1454
+	 * @throws \EE_Error
1455
+	 */
1456
+	public static function delete_all_espresso_cpt_data()
1457
+	{
1458
+		global $wpdb;
1459
+		//get all the CPT post_types
1460
+		$ee_post_types = array();
1461
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1462
+			if (method_exists($model_name, 'instance')) {
1463
+				$model_obj = call_user_func(array($model_name, 'instance'));
1464
+				if ($model_obj instanceof EEM_CPT_Base) {
1465
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1466
+				}
1467
+			}
1468
+		}
1469
+		//get all our CPTs
1470
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1471
+		$cpt_ids = $wpdb->get_col($query);
1472
+		//delete each post meta and term relations too
1473
+		foreach ($cpt_ids as $post_id) {
1474
+			wp_delete_post($post_id, true);
1475
+		}
1476
+	}
1477
+
1478
+	/**
1479
+	 * Deletes all EE custom tables
1480
+	 *
1481
+	 * @return array
1482
+	 */
1483
+	public static function drop_espresso_tables()
1484
+	{
1485
+		$tables = array();
1486
+		// load registry
1487
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1488
+			if (method_exists($model_name, 'instance')) {
1489
+				$model_obj = call_user_func(array($model_name, 'instance'));
1490
+				if ($model_obj instanceof EEM_Base) {
1491
+					foreach ($model_obj->get_tables() as $table) {
1492
+						if (strpos($table->get_table_name(), 'esp_')
1493
+							&&
1494
+							(
1495
+								is_main_site()//main site? nuke them all
1496
+								|| ! $table->is_global()//not main site,but not global either. nuke it
1497
+							)
1498
+						) {
1499
+							$tables[$table->get_table_name()] = $table->get_table_name();
1500
+						}
1501
+					}
1502
+				}
1503
+			}
1504
+		}
1505
+
1506
+		//there are some tables whose models were removed.
1507
+		//they should be removed when removing all EE core's data
1508
+		$tables_without_models = array(
1509
+			'esp_promotion',
1510
+			'esp_promotion_applied',
1511
+			'esp_promotion_object',
1512
+			'esp_promotion_rule',
1513
+			'esp_rule',
1514
+		);
1515
+		foreach ($tables_without_models as $table) {
1516
+			$tables[$table] = $table;
1517
+		}
1518
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1519
+	}
1520
+
1521
+
1522
+
1523
+	/**
1524
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1525
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1526
+	 * Returns the list actually deleted
1527
+	 *
1528
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1529
+	 * @global WPDB $wpdb
1530
+	 * @param array $table_names
1531
+	 * @return array of table names which we deleted
1532
+	 */
1533
+	public static function drop_tables($table_names)
1534
+	{
1535
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1536
+	}
1537
+
1538
+
1539
+
1540
+	/**
1541
+	 * plugin_uninstall
1542
+	 *
1543
+	 * @access public
1544
+	 * @static
1545
+	 * @param bool $remove_all
1546
+	 * @return void
1547
+	 */
1548
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1549
+	{
1550
+		global $wpdb;
1551
+		self::drop_espresso_tables();
1552
+		$wp_options_to_delete = array(
1553
+			'ee_no_ticket_prices'                => true,
1554
+			'ee_active_messengers'               => true,
1555
+			'ee_has_activated_messenger'         => true,
1556
+			RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES => true,
1557
+			'ee_config'                          => false,
1558
+			'ee_data_migration_current_db_state' => true,
1559
+			'ee_data_migration_mapping_'         => false,
1560
+			'ee_data_migration_script_'          => false,
1561
+			'ee_data_migrations'                 => true,
1562
+			'ee_dms_map'                         => false,
1563
+			'ee_notices'                         => true,
1564
+			'lang_file_check_'                   => false,
1565
+			'ee_maintenance_mode'                => true,
1566
+			'ee_ueip_optin'                      => true,
1567
+			'ee_ueip_has_notified'               => true,
1568
+			'ee_plugin_activation_errors'        => true,
1569
+			'ee_id_mapping_from'                 => false,
1570
+			'espresso_persistent_admin_notices'  => true,
1571
+			'ee_encryption_key'                  => true,
1572
+			'pue_force_upgrade_'                 => false,
1573
+			'pue_json_error_'                    => false,
1574
+			'pue_install_key_'                   => false,
1575
+			'pue_verification_error_'            => false,
1576
+			'pu_dismissed_upgrade_'              => false,
1577
+			'external_updates-'                  => false,
1578
+			'ee_extra_data'                      => true,
1579
+			'ee_ssn_'                            => false,
1580
+			'ee_rss_'                            => false,
1581
+			'ee_rte_n_tx_'                       => false,
1582
+			'ee_pers_admin_notices'              => true,
1583
+			'ee_job_parameters_'                 => false,
1584
+			'ee_upload_directories_incomplete'   => true,
1585
+			'ee_verified_db_collations'          => true,
1586
+		);
1587
+		if (is_main_site()) {
1588
+			$wp_options_to_delete['ee_network_config'] = true;
1589
+		}
1590
+		$undeleted_options = array();
1591
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1592
+			if ($no_wildcard) {
1593
+				if ( ! delete_option($option_name)) {
1594
+					$undeleted_options[] = $option_name;
1595
+				}
1596
+			} else {
1597
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1598
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1599
+					if ( ! delete_option($option_name_from_wildcard)) {
1600
+						$undeleted_options[] = $option_name_from_wildcard;
1601
+					}
1602
+				}
1603
+			}
1604
+		}
1605
+		//also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1606
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1607
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1608
+			$db_update_sans_ee4 = array();
1609
+			foreach ($espresso_db_update as $version => $times_activated) {
1610
+				if ((string)$version[0] === '3') {//if its NON EE4
1611
+					$db_update_sans_ee4[$version] = $times_activated;
1612
+				}
1613
+			}
1614
+			update_option('espresso_db_update', $db_update_sans_ee4);
1615
+		}
1616
+		$errors = '';
1617
+		if ( ! empty($undeleted_options)) {
1618
+			$errors .= sprintf(
1619
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1620
+				'<br/>',
1621
+				implode(',<br/>', $undeleted_options)
1622
+			);
1623
+		}
1624
+		if ( ! empty($errors)) {
1625
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1626
+		}
1627
+	}
1628
+
1629
+	/**
1630
+	 * Gets the mysql error code from the last used query by wpdb
1631
+	 *
1632
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1633
+	 */
1634
+	public static function last_wpdb_error_code()
1635
+	{
1636
+		global $wpdb;
1637
+		if ($wpdb->use_mysqli) {
1638
+			return mysqli_errno($wpdb->dbh);
1639
+		} else {
1640
+			return mysql_errno($wpdb->dbh);
1641
+		}
1642
+	}
1643
+
1644
+	/**
1645
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1646
+	 *
1647
+	 * @global wpdb  $wpdb
1648
+	 * @deprecated instead use TableAnalysis::tableExists()
1649
+	 * @param string $table_name with or without $wpdb->prefix
1650
+	 * @return boolean
1651
+	 */
1652
+	public static function table_exists($table_name)
1653
+	{
1654
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1655
+	}
1656
+
1657
+	/**
1658
+	 * Resets the cache on EEH_Activation
1659
+	 */
1660
+	public static function reset()
1661
+	{
1662
+		self::$_default_creator_id                             = null;
1663
+		self::$_initialized_db_content_already_in_this_request = false;
1664
+	}
1665 1665
 }
1666 1666
 // End of file EEH_Activation.helper.php
1667 1667
 // Location: /helpers/EEH_Activation.core.php
Please login to merge, or discard this patch.
core/EE_Addon.core.php 1 patch
Indentation   +821 added lines, -821 removed lines patch added patch discarded remove patch
@@ -21,793 +21,793 @@  discard block
 block discarded – undo
21 21
 {
22 22
 
23 23
 
24
-    /**
25
-     * prefix to be added onto an addon's plugin slug to make a wp option name
26
-     * which will be used to store the plugin's activation history
27
-     */
28
-    const ee_addon_version_history_option_prefix = 'ee_version_history_';
29
-
30
-    /**
31
-     * @var $_version
32
-     * @type string
33
-     */
34
-    protected $_version = '';
35
-
36
-    /**
37
-     * @var $_min_core_version
38
-     * @type string
39
-     */
40
-    protected $_min_core_version = '';
41
-
42
-    /**
43
-     * derived from plugin 'main_file_path using plugin_basename()
44
-     *
45
-     * @type string $_plugin_basename
46
-     */
47
-    protected $_plugin_basename = '';
48
-
49
-    /**
50
-     * A non-internationalized name to identify this addon for use in URLs, etc
51
-     *
52
-     * @type string $_plugin_slug
53
-     */
54
-    protected $_plugin_slug = '';
55
-
56
-    /**
57
-     * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
58
-     *
59
-     * @type string _addon_name
60
-     */
61
-    protected $_addon_name = '';
62
-
63
-    /**
64
-     * one of the EE_System::req_type_* constants
65
-     *
66
-     * @type int $_req_type
67
-     */
68
-    protected $_req_type;
69
-
70
-    /**
71
-     * page slug to be used when generating the "Settings" link on the WP plugin page
72
-     *
73
-     * @type string $_plugin_action_slug
74
-     */
75
-    protected $_plugin_action_slug = '';
76
-
77
-    /**
78
-     * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
79
-     * that can be used for adding upgrading/marketing info
80
-     *
81
-     * @type array $_plugins_page_row
82
-     */
83
-    protected $_plugins_page_row = array();
84
-
85
-
86
-
87
-    /**
88
-     *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
89
-     *
90
-     * @type string
91
-     */
92
-    protected $_main_plugin_file;
93
-
94
-
95
-    /**
96
-     * @var EE_Dependency_Map $dependency_map
97
-     */
98
-    private $dependency_map;
99
-
100
-
101
-    /**
102
-     * @var DomainInterface $domain
103
-     */
104
-    private $domain;
105
-
106
-
107
-    /**
108
-     * @param EE_Dependency_Map $dependency_map [optional]
109
-     * @param DomainInterface   $domain         [optional]
110
-     */
111
-    public function __construct(EE_Dependency_Map $dependency_map = null, DomainInterface $domain = null)
112
-    {
113
-        if($dependency_map instanceof EE_Dependency_Map) {
114
-            $this->setDependencyMap($dependency_map);
115
-        }
116
-        if ($domain instanceof DomainInterface) {
117
-            $this->setDomain($domain);
118
-        }
119
-        add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
120
-    }
121
-
122
-
123
-    /**
124
-     * @param EE_Dependency_Map $dependency_map
125
-     */
126
-    public function setDependencyMap($dependency_map)
127
-    {
128
-        $this->dependency_map = $dependency_map;
129
-    }
130
-
131
-
132
-    /**
133
-     * @return EE_Dependency_Map
134
-     */
135
-    public function dependencyMap()
136
-    {
137
-        return $this->dependency_map;
138
-    }
139
-
140
-
141
-    /**
142
-     * @param DomainInterface $domain
143
-     */
144
-    public function setDomain(DomainInterface $domain)
145
-    {
146
-        $this->domain = $domain;
147
-    }
148
-
149
-    /**
150
-     * @return DomainInterface
151
-     */
152
-    public function domain()
153
-    {
154
-        return $this->domain;
155
-    }
156
-
157
-
158
-    /**
159
-     * @param mixed $version
160
-     */
161
-    public function set_version($version = null)
162
-    {
163
-        $this->_version = $version;
164
-    }
165
-
166
-
167
-    /**
168
-     * get__version
169
-     *
170
-     * @return string
171
-     */
172
-    public function version()
173
-    {
174
-        return $this->_version;
175
-    }
176
-
177
-
178
-    /**
179
-     * @param mixed $min_core_version
180
-     */
181
-    public function set_min_core_version($min_core_version = null)
182
-    {
183
-        $this->_min_core_version = $min_core_version;
184
-    }
185
-
186
-
187
-    /**
188
-     * get__min_core_version
189
-     *
190
-     * @return string
191
-     */
192
-    public function min_core_version()
193
-    {
194
-        return $this->_min_core_version;
195
-    }
196
-
197
-
198
-    /**
199
-     * Sets addon_name
200
-     *
201
-     * @param string $addon_name
202
-     * @return boolean
203
-     */
204
-    public function set_name($addon_name)
205
-    {
206
-        return $this->_addon_name = $addon_name;
207
-    }
208
-
209
-
210
-    /**
211
-     * Gets addon_name
212
-     *
213
-     * @return string
214
-     */
215
-    public function name()
216
-    {
217
-        return $this->_addon_name;
218
-    }
219
-
220
-
221
-    /**
222
-     * @return string
223
-     */
224
-    public function plugin_basename()
225
-    {
226
-
227
-        return $this->_plugin_basename;
228
-    }
229
-
230
-
231
-    /**
232
-     * @param string $plugin_basename
233
-     */
234
-    public function set_plugin_basename($plugin_basename)
235
-    {
236
-
237
-        $this->_plugin_basename = $plugin_basename;
238
-    }
239
-
240
-
241
-    /**
242
-     * @return string
243
-     */
244
-    public function plugin_slug()
245
-    {
246
-
247
-        return $this->_plugin_slug;
248
-    }
249
-
250
-
251
-    /**
252
-     * @param string $plugin_slug
253
-     */
254
-    public function set_plugin_slug($plugin_slug)
255
-    {
256
-
257
-        $this->_plugin_slug = $plugin_slug;
258
-    }
259
-
260
-
261
-    /**
262
-     * @return string
263
-     */
264
-    public function plugin_action_slug()
265
-    {
266
-
267
-        return $this->_plugin_action_slug;
268
-    }
269
-
270
-
271
-    /**
272
-     * @param string $plugin_action_slug
273
-     */
274
-    public function set_plugin_action_slug($plugin_action_slug)
275
-    {
276
-
277
-        $this->_plugin_action_slug = $plugin_action_slug;
278
-    }
279
-
280
-
281
-    /**
282
-     * @return array
283
-     */
284
-    public function get_plugins_page_row()
285
-    {
286
-
287
-        return $this->_plugins_page_row;
288
-    }
289
-
290
-
291
-    /**
292
-     * @param array $plugins_page_row
293
-     */
294
-    public function set_plugins_page_row($plugins_page_row = array())
295
-    {
296
-        // sigh.... check for example content that I stupidly merged to master and remove it if found
297
-        if (! is_array($plugins_page_row)
298
-            && strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
299
-        ) {
300
-            $plugins_page_row = array();
301
-        }
302
-        $this->_plugins_page_row = (array) $plugins_page_row;
303
-    }
304
-
305
-
306
-    /**
307
-     * Called when EE core detects this addon has been activated for the first time.
308
-     * If the site isn't in maintenance mode, should setup the addon's database
309
-     *
310
-     * @return void
311
-     */
312
-    public function new_install()
313
-    {
314
-        $classname = get_class($this);
315
-        do_action("AHEE__{$classname}__new_install");
316
-        do_action('AHEE__EE_Addon__new_install', $this);
317
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
318
-        add_action(
319
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
320
-            array($this, 'initialize_db_if_no_migrations_required')
321
-        );
322
-    }
323
-
324
-
325
-    /**
326
-     * Called when EE core detects this addon has been reactivated. When this happens,
327
-     * it's good to just check that your data is still intact
328
-     *
329
-     * @return void
330
-     */
331
-    public function reactivation()
332
-    {
333
-        $classname = get_class($this);
334
-        do_action("AHEE__{$classname}__reactivation");
335
-        do_action('AHEE__EE_Addon__reactivation', $this);
336
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
337
-        add_action(
338
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
339
-            array($this, 'initialize_db_if_no_migrations_required')
340
-        );
341
-    }
342
-
343
-
344
-    /**
345
-     * Called when the registered deactivation hook for this addon fires.
346
-     * @throws EE_Error
347
-     */
348
-    public function deactivation()
349
-    {
350
-        $classname = get_class($this);
351
-        do_action("AHEE__{$classname}__deactivation");
352
-        do_action('AHEE__EE_Addon__deactivation', $this);
353
-        //check if the site no longer needs to be in maintenance mode
354
-        EE_Register_Addon::deregister($this->name());
355
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
356
-    }
357
-
358
-
359
-    /**
360
-     * Takes care of double-checking that we're not in maintenance mode, and then
361
-     * initializing this addon's necessary initial data. This is called by default on new activations
362
-     * and reactivations.
363
-     *
364
-     * @param boolean $verify_schema whether to verify the database's schema for this addon, or just its data.
365
-     *                               This is a resource-intensive job so we prefer to only do it when necessary
366
-     * @return void
367
-     * @throws \EE_Error
368
-     * @throws InvalidInterfaceException
369
-     * @throws InvalidDataTypeException
370
-     * @throws InvalidArgumentException
371
-     */
372
-    public function initialize_db_if_no_migrations_required($verify_schema = true)
373
-    {
374
-        if ($verify_schema === '') {
375
-            //wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
376
-            //(ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
377
-            //calls them with an argument of an empty string (ie ""), which evaluates to false
378
-            //so we need to treat the empty string as if nothing had been passed, and should instead use the default
379
-            $verify_schema = true;
380
-        }
381
-        if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
382
-            if ($verify_schema) {
383
-                $this->initialize_db();
384
-            }
385
-            $this->initialize_default_data();
386
-            //@todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
387
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to(
388
-                array(
389
-                    'slug'    => $this->name(),
390
-                    'version' => $this->version(),
391
-                )
392
-            );
393
-            /* make sure core's data is a-ok
24
+	/**
25
+	 * prefix to be added onto an addon's plugin slug to make a wp option name
26
+	 * which will be used to store the plugin's activation history
27
+	 */
28
+	const ee_addon_version_history_option_prefix = 'ee_version_history_';
29
+
30
+	/**
31
+	 * @var $_version
32
+	 * @type string
33
+	 */
34
+	protected $_version = '';
35
+
36
+	/**
37
+	 * @var $_min_core_version
38
+	 * @type string
39
+	 */
40
+	protected $_min_core_version = '';
41
+
42
+	/**
43
+	 * derived from plugin 'main_file_path using plugin_basename()
44
+	 *
45
+	 * @type string $_plugin_basename
46
+	 */
47
+	protected $_plugin_basename = '';
48
+
49
+	/**
50
+	 * A non-internationalized name to identify this addon for use in URLs, etc
51
+	 *
52
+	 * @type string $_plugin_slug
53
+	 */
54
+	protected $_plugin_slug = '';
55
+
56
+	/**
57
+	 * A non-internationalized name to identify this addon. Eg 'Calendar','MailChimp',etc/
58
+	 *
59
+	 * @type string _addon_name
60
+	 */
61
+	protected $_addon_name = '';
62
+
63
+	/**
64
+	 * one of the EE_System::req_type_* constants
65
+	 *
66
+	 * @type int $_req_type
67
+	 */
68
+	protected $_req_type;
69
+
70
+	/**
71
+	 * page slug to be used when generating the "Settings" link on the WP plugin page
72
+	 *
73
+	 * @type string $_plugin_action_slug
74
+	 */
75
+	protected $_plugin_action_slug = '';
76
+
77
+	/**
78
+	 * if not empty, inserts a new table row after this plugin's row on the WP Plugins page
79
+	 * that can be used for adding upgrading/marketing info
80
+	 *
81
+	 * @type array $_plugins_page_row
82
+	 */
83
+	protected $_plugins_page_row = array();
84
+
85
+
86
+
87
+	/**
88
+	 *    filepath to the main file, which can be used for register_activation_hook, register_deactivation_hook, etc.
89
+	 *
90
+	 * @type string
91
+	 */
92
+	protected $_main_plugin_file;
93
+
94
+
95
+	/**
96
+	 * @var EE_Dependency_Map $dependency_map
97
+	 */
98
+	private $dependency_map;
99
+
100
+
101
+	/**
102
+	 * @var DomainInterface $domain
103
+	 */
104
+	private $domain;
105
+
106
+
107
+	/**
108
+	 * @param EE_Dependency_Map $dependency_map [optional]
109
+	 * @param DomainInterface   $domain         [optional]
110
+	 */
111
+	public function __construct(EE_Dependency_Map $dependency_map = null, DomainInterface $domain = null)
112
+	{
113
+		if($dependency_map instanceof EE_Dependency_Map) {
114
+			$this->setDependencyMap($dependency_map);
115
+		}
116
+		if ($domain instanceof DomainInterface) {
117
+			$this->setDomain($domain);
118
+		}
119
+		add_action('AHEE__EE_System__load_controllers__load_admin_controllers', array($this, 'admin_init'));
120
+	}
121
+
122
+
123
+	/**
124
+	 * @param EE_Dependency_Map $dependency_map
125
+	 */
126
+	public function setDependencyMap($dependency_map)
127
+	{
128
+		$this->dependency_map = $dependency_map;
129
+	}
130
+
131
+
132
+	/**
133
+	 * @return EE_Dependency_Map
134
+	 */
135
+	public function dependencyMap()
136
+	{
137
+		return $this->dependency_map;
138
+	}
139
+
140
+
141
+	/**
142
+	 * @param DomainInterface $domain
143
+	 */
144
+	public function setDomain(DomainInterface $domain)
145
+	{
146
+		$this->domain = $domain;
147
+	}
148
+
149
+	/**
150
+	 * @return DomainInterface
151
+	 */
152
+	public function domain()
153
+	{
154
+		return $this->domain;
155
+	}
156
+
157
+
158
+	/**
159
+	 * @param mixed $version
160
+	 */
161
+	public function set_version($version = null)
162
+	{
163
+		$this->_version = $version;
164
+	}
165
+
166
+
167
+	/**
168
+	 * get__version
169
+	 *
170
+	 * @return string
171
+	 */
172
+	public function version()
173
+	{
174
+		return $this->_version;
175
+	}
176
+
177
+
178
+	/**
179
+	 * @param mixed $min_core_version
180
+	 */
181
+	public function set_min_core_version($min_core_version = null)
182
+	{
183
+		$this->_min_core_version = $min_core_version;
184
+	}
185
+
186
+
187
+	/**
188
+	 * get__min_core_version
189
+	 *
190
+	 * @return string
191
+	 */
192
+	public function min_core_version()
193
+	{
194
+		return $this->_min_core_version;
195
+	}
196
+
197
+
198
+	/**
199
+	 * Sets addon_name
200
+	 *
201
+	 * @param string $addon_name
202
+	 * @return boolean
203
+	 */
204
+	public function set_name($addon_name)
205
+	{
206
+		return $this->_addon_name = $addon_name;
207
+	}
208
+
209
+
210
+	/**
211
+	 * Gets addon_name
212
+	 *
213
+	 * @return string
214
+	 */
215
+	public function name()
216
+	{
217
+		return $this->_addon_name;
218
+	}
219
+
220
+
221
+	/**
222
+	 * @return string
223
+	 */
224
+	public function plugin_basename()
225
+	{
226
+
227
+		return $this->_plugin_basename;
228
+	}
229
+
230
+
231
+	/**
232
+	 * @param string $plugin_basename
233
+	 */
234
+	public function set_plugin_basename($plugin_basename)
235
+	{
236
+
237
+		$this->_plugin_basename = $plugin_basename;
238
+	}
239
+
240
+
241
+	/**
242
+	 * @return string
243
+	 */
244
+	public function plugin_slug()
245
+	{
246
+
247
+		return $this->_plugin_slug;
248
+	}
249
+
250
+
251
+	/**
252
+	 * @param string $plugin_slug
253
+	 */
254
+	public function set_plugin_slug($plugin_slug)
255
+	{
256
+
257
+		$this->_plugin_slug = $plugin_slug;
258
+	}
259
+
260
+
261
+	/**
262
+	 * @return string
263
+	 */
264
+	public function plugin_action_slug()
265
+	{
266
+
267
+		return $this->_plugin_action_slug;
268
+	}
269
+
270
+
271
+	/**
272
+	 * @param string $plugin_action_slug
273
+	 */
274
+	public function set_plugin_action_slug($plugin_action_slug)
275
+	{
276
+
277
+		$this->_plugin_action_slug = $plugin_action_slug;
278
+	}
279
+
280
+
281
+	/**
282
+	 * @return array
283
+	 */
284
+	public function get_plugins_page_row()
285
+	{
286
+
287
+		return $this->_plugins_page_row;
288
+	}
289
+
290
+
291
+	/**
292
+	 * @param array $plugins_page_row
293
+	 */
294
+	public function set_plugins_page_row($plugins_page_row = array())
295
+	{
296
+		// sigh.... check for example content that I stupidly merged to master and remove it if found
297
+		if (! is_array($plugins_page_row)
298
+			&& strpos($plugins_page_row, '<h3>Promotions Addon Upsell Info</h3>') !== false
299
+		) {
300
+			$plugins_page_row = array();
301
+		}
302
+		$this->_plugins_page_row = (array) $plugins_page_row;
303
+	}
304
+
305
+
306
+	/**
307
+	 * Called when EE core detects this addon has been activated for the first time.
308
+	 * If the site isn't in maintenance mode, should setup the addon's database
309
+	 *
310
+	 * @return void
311
+	 */
312
+	public function new_install()
313
+	{
314
+		$classname = get_class($this);
315
+		do_action("AHEE__{$classname}__new_install");
316
+		do_action('AHEE__EE_Addon__new_install', $this);
317
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
318
+		add_action(
319
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
320
+			array($this, 'initialize_db_if_no_migrations_required')
321
+		);
322
+	}
323
+
324
+
325
+	/**
326
+	 * Called when EE core detects this addon has been reactivated. When this happens,
327
+	 * it's good to just check that your data is still intact
328
+	 *
329
+	 * @return void
330
+	 */
331
+	public function reactivation()
332
+	{
333
+		$classname = get_class($this);
334
+		do_action("AHEE__{$classname}__reactivation");
335
+		do_action('AHEE__EE_Addon__reactivation', $this);
336
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
337
+		add_action(
338
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
339
+			array($this, 'initialize_db_if_no_migrations_required')
340
+		);
341
+	}
342
+
343
+
344
+	/**
345
+	 * Called when the registered deactivation hook for this addon fires.
346
+	 * @throws EE_Error
347
+	 */
348
+	public function deactivation()
349
+	{
350
+		$classname = get_class($this);
351
+		do_action("AHEE__{$classname}__deactivation");
352
+		do_action('AHEE__EE_Addon__deactivation', $this);
353
+		//check if the site no longer needs to be in maintenance mode
354
+		EE_Register_Addon::deregister($this->name());
355
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
356
+	}
357
+
358
+
359
+	/**
360
+	 * Takes care of double-checking that we're not in maintenance mode, and then
361
+	 * initializing this addon's necessary initial data. This is called by default on new activations
362
+	 * and reactivations.
363
+	 *
364
+	 * @param boolean $verify_schema whether to verify the database's schema for this addon, or just its data.
365
+	 *                               This is a resource-intensive job so we prefer to only do it when necessary
366
+	 * @return void
367
+	 * @throws \EE_Error
368
+	 * @throws InvalidInterfaceException
369
+	 * @throws InvalidDataTypeException
370
+	 * @throws InvalidArgumentException
371
+	 */
372
+	public function initialize_db_if_no_migrations_required($verify_schema = true)
373
+	{
374
+		if ($verify_schema === '') {
375
+			//wp core bug imo: if no args are passed to `do_action('some_hook_name')` besides the hook's name
376
+			//(ie, no 2nd or 3rd arguments), instead of calling the registered callbacks with no arguments, it
377
+			//calls them with an argument of an empty string (ie ""), which evaluates to false
378
+			//so we need to treat the empty string as if nothing had been passed, and should instead use the default
379
+			$verify_schema = true;
380
+		}
381
+		if (EE_Maintenance_Mode::instance()->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
382
+			if ($verify_schema) {
383
+				$this->initialize_db();
384
+			}
385
+			$this->initialize_default_data();
386
+			//@todo: this will probably need to be adjusted in 4.4 as the array changed formats I believe
387
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to(
388
+				array(
389
+					'slug'    => $this->name(),
390
+					'version' => $this->version(),
391
+				)
392
+			);
393
+			/* make sure core's data is a-ok
394 394
              * (at the time of writing, we especially want to verify all the caps are present
395 395
              * because payment method type capabilities are added dynamically, and it's
396 396
              * possible this addon added a payment method. But it's also possible
397 397
              * other data needs to be verified)
398 398
              */
399
-            EEH_Activation::initialize_db_content();
400
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
401
-            $rewrite_rules = LoaderFactory::getLoader()->getShared(
402
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
403
-            );
404
-            $rewrite_rules->flushRewriteRules();
405
-            //in case there are lots of addons being activated at once, let's force garbage collection
406
-            //to help avoid memory limit errors
407
-            //EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
408
-            gc_collect_cycles();
409
-        } else {
410
-            //ask the data migration manager to init this addon's data
411
-            //when migrations are finished because we can't do it now
412
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
413
-        }
414
-    }
415
-
416
-
417
-    /**
418
-     * Used to setup this addon's database tables, but not necessarily any default
419
-     * data in them. The default is to actually use the most up-to-date data migration script
420
-     * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
421
-     * methods to setup the db.
422
-     */
423
-    public function initialize_db()
424
-    {
425
-        //find the migration script that sets the database to be compatible with the code
426
-        $current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
427
-        if ($current_dms_name) {
428
-            $current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
429
-            $current_data_migration_script->set_migrating(false);
430
-            $current_data_migration_script->schema_changes_before_migration();
431
-            $current_data_migration_script->schema_changes_after_migration();
432
-            if ($current_data_migration_script->get_errors()) {
433
-                foreach ($current_data_migration_script->get_errors() as $error) {
434
-                    EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
435
-                }
436
-            }
437
-        }
438
-        //if not DMS was found that should be ok. This addon just doesn't require any database changes
439
-        EE_Data_Migration_Manager::instance()->update_current_database_state_to(
440
-            array(
441
-                'slug'    => $this->name(),
442
-                'version' => $this->version(),
443
-            )
444
-        );
445
-    }
446
-
447
-
448
-    /**
449
-     * If you want to setup default data for the addon, override this method, and call
450
-     * parent::initialize_default_data() from within it. This is normally called
451
-     * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
452
-     * and should verify default data is present (but this is also called
453
-     * on reactivations and just after migrations, so please verify you actually want
454
-     * to ADD default data, because it may already be present).
455
-     * However, please call this parent (currently it just fires a hook which other
456
-     * addons may be depending on)
457
-     */
458
-    public function initialize_default_data()
459
-    {
460
-        /**
461
-         * Called when an addon is ensuring its default data is set (possibly called
462
-         * on a reactivation, so first check for the absence of other data before setting
463
-         * default data)
464
-         *
465
-         * @param EE_Addon $addon the addon that called this
466
-         */
467
-        do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
468
-        //override to insert default data. It is safe to use the models here
469
-        //because the site should not be in maintenance mode
470
-    }
471
-
472
-
473
-    /**
474
-     * EE Core detected that this addon has been upgraded. We should check if there
475
-     * are any new migration scripts, and if so put the site into maintenance mode until
476
-     * they're ran
477
-     *
478
-     * @return void
479
-     */
480
-    public function upgrade()
481
-    {
482
-        $classname = get_class($this);
483
-        do_action("AHEE__{$classname}__upgrade");
484
-        do_action('AHEE__EE_Addon__upgrade', $this);
485
-        EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
486
-        //also it's possible there is new default data that needs to be added
487
-        add_action(
488
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
489
-            array($this, 'initialize_db_if_no_migrations_required')
490
-        );
491
-    }
492
-
493
-
494
-    /**
495
-     * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
496
-     */
497
-    public function downgrade()
498
-    {
499
-        $classname = get_class($this);
500
-        do_action("AHEE__{$classname}__downgrade");
501
-        do_action('AHEE__EE_Addon__downgrade', $this);
502
-        //it's possible there's old default data that needs to be double-checked
503
-        add_action(
504
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
505
-            array($this, 'initialize_db_if_no_migrations_required')
506
-        );
507
-    }
508
-
509
-
510
-    /**
511
-     * set_db_update_option_name
512
-     * Until we do something better, we'll just check for migration scripts upon
513
-     * plugin activation only. In the future, we'll want to do it on plugin updates too
514
-     *
515
-     * @return bool
516
-     */
517
-    public function set_db_update_option_name()
518
-    {
519
-        EE_Error::doing_it_wrong(
520
-            __FUNCTION__,
521
-            esc_html__(
522
-                'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
523
-                'event_espresso'
524
-            ),
525
-            '4.3.0.alpha.016'
526
-        );
527
-        //let's just handle this on the next request, ok? right now we're just not really ready
528
-        return $this->set_activation_indicator_option();
529
-    }
530
-
531
-
532
-    /**
533
-     * Returns the name of the activation indicator option
534
-     * (an option which is set temporarily to indicate that this addon was just activated)
535
-     *
536
-     * @deprecated since version 4.3.0.alpha.016
537
-     * @return string
538
-     */
539
-    public function get_db_update_option_name()
540
-    {
541
-        EE_Error::doing_it_wrong(
542
-            __FUNCTION__,
543
-            esc_html__(
544
-                'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
545
-                'event_espresso'
546
-            ),
547
-            '4.3.0.alpha.016'
548
-        );
549
-        return $this->get_activation_indicator_option_name();
550
-    }
551
-
552
-
553
-    /**
554
-     * When the addon is activated, this should be called to set a wordpress option that
555
-     * indicates it was activated. This is especially useful for detecting reactivations.
556
-     *
557
-     * @return bool
558
-     */
559
-    public function set_activation_indicator_option()
560
-    {
561
-        // let's just handle this on the next request, ok? right now we're just not really ready
562
-        return update_option($this->get_activation_indicator_option_name(), true);
563
-    }
564
-
565
-
566
-    /**
567
-     * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
568
-     *
569
-     * @return string
570
-     */
571
-    public function get_activation_indicator_option_name()
572
-    {
573
-        return 'ee_activation_' . $this->name();
574
-    }
575
-
576
-
577
-    /**
578
-     * Used by EE_System to set the request type of this addon. Should not be used by addon developers
579
-     *
580
-     * @param int $req_type
581
-     */
582
-    public function set_req_type($req_type)
583
-    {
584
-        $this->_req_type = $req_type;
585
-    }
586
-
587
-
588
-    /**
589
-     * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
590
-     * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
591
-     * EE_System when it is checking for new install or upgrades of addons
592
-     */
593
-    public function detect_req_type()
594
-    {
595
-        if (! $this->_req_type) {
596
-            $this->detect_activation_or_upgrade();
597
-        }
598
-        return $this->_req_type;
599
-    }
600
-
601
-
602
-    /**
603
-     * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
604
-     * Should only be called once per request
605
-     *
606
-     * @return void
607
-     */
608
-    public function detect_activation_or_upgrade()
609
-    {
610
-        $activation_history_for_addon = $this->get_activation_history();
399
+			EEH_Activation::initialize_db_content();
400
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
401
+			$rewrite_rules = LoaderFactory::getLoader()->getShared(
402
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
403
+			);
404
+			$rewrite_rules->flushRewriteRules();
405
+			//in case there are lots of addons being activated at once, let's force garbage collection
406
+			//to help avoid memory limit errors
407
+			//EEH_Debug_Tools::instance()->measure_memory( 'db content initialized for ' . get_class( $this), true );
408
+			gc_collect_cycles();
409
+		} else {
410
+			//ask the data migration manager to init this addon's data
411
+			//when migrations are finished because we can't do it now
412
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for($this->name());
413
+		}
414
+	}
415
+
416
+
417
+	/**
418
+	 * Used to setup this addon's database tables, but not necessarily any default
419
+	 * data in them. The default is to actually use the most up-to-date data migration script
420
+	 * for this addon, and just use its schema_changes_before_migration() and schema_changes_after_migration()
421
+	 * methods to setup the db.
422
+	 */
423
+	public function initialize_db()
424
+	{
425
+		//find the migration script that sets the database to be compatible with the code
426
+		$current_dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms($this->name());
427
+		if ($current_dms_name) {
428
+			$current_data_migration_script = EE_Registry::instance()->load_dms($current_dms_name);
429
+			$current_data_migration_script->set_migrating(false);
430
+			$current_data_migration_script->schema_changes_before_migration();
431
+			$current_data_migration_script->schema_changes_after_migration();
432
+			if ($current_data_migration_script->get_errors()) {
433
+				foreach ($current_data_migration_script->get_errors() as $error) {
434
+					EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
435
+				}
436
+			}
437
+		}
438
+		//if not DMS was found that should be ok. This addon just doesn't require any database changes
439
+		EE_Data_Migration_Manager::instance()->update_current_database_state_to(
440
+			array(
441
+				'slug'    => $this->name(),
442
+				'version' => $this->version(),
443
+			)
444
+		);
445
+	}
446
+
447
+
448
+	/**
449
+	 * If you want to setup default data for the addon, override this method, and call
450
+	 * parent::initialize_default_data() from within it. This is normally called
451
+	 * from EE_Addon::initialize_db_if_no_migrations_required(), just after EE_Addon::initialize_db()
452
+	 * and should verify default data is present (but this is also called
453
+	 * on reactivations and just after migrations, so please verify you actually want
454
+	 * to ADD default data, because it may already be present).
455
+	 * However, please call this parent (currently it just fires a hook which other
456
+	 * addons may be depending on)
457
+	 */
458
+	public function initialize_default_data()
459
+	{
460
+		/**
461
+		 * Called when an addon is ensuring its default data is set (possibly called
462
+		 * on a reactivation, so first check for the absence of other data before setting
463
+		 * default data)
464
+		 *
465
+		 * @param EE_Addon $addon the addon that called this
466
+		 */
467
+		do_action('AHEE__EE_Addon__initialize_default_data__begin', $this);
468
+		//override to insert default data. It is safe to use the models here
469
+		//because the site should not be in maintenance mode
470
+	}
471
+
472
+
473
+	/**
474
+	 * EE Core detected that this addon has been upgraded. We should check if there
475
+	 * are any new migration scripts, and if so put the site into maintenance mode until
476
+	 * they're ran
477
+	 *
478
+	 * @return void
479
+	 */
480
+	public function upgrade()
481
+	{
482
+		$classname = get_class($this);
483
+		do_action("AHEE__{$classname}__upgrade");
484
+		do_action('AHEE__EE_Addon__upgrade', $this);
485
+		EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
486
+		//also it's possible there is new default data that needs to be added
487
+		add_action(
488
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
489
+			array($this, 'initialize_db_if_no_migrations_required')
490
+		);
491
+	}
492
+
493
+
494
+	/**
495
+	 * If Core detects this addon has been downgraded, you may want to invoke some special logic here.
496
+	 */
497
+	public function downgrade()
498
+	{
499
+		$classname = get_class($this);
500
+		do_action("AHEE__{$classname}__downgrade");
501
+		do_action('AHEE__EE_Addon__downgrade', $this);
502
+		//it's possible there's old default data that needs to be double-checked
503
+		add_action(
504
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
505
+			array($this, 'initialize_db_if_no_migrations_required')
506
+		);
507
+	}
508
+
509
+
510
+	/**
511
+	 * set_db_update_option_name
512
+	 * Until we do something better, we'll just check for migration scripts upon
513
+	 * plugin activation only. In the future, we'll want to do it on plugin updates too
514
+	 *
515
+	 * @return bool
516
+	 */
517
+	public function set_db_update_option_name()
518
+	{
519
+		EE_Error::doing_it_wrong(
520
+			__FUNCTION__,
521
+			esc_html__(
522
+				'EE_Addon::set_db_update_option_name was renamed to EE_Addon::set_activation_indicator_option',
523
+				'event_espresso'
524
+			),
525
+			'4.3.0.alpha.016'
526
+		);
527
+		//let's just handle this on the next request, ok? right now we're just not really ready
528
+		return $this->set_activation_indicator_option();
529
+	}
530
+
531
+
532
+	/**
533
+	 * Returns the name of the activation indicator option
534
+	 * (an option which is set temporarily to indicate that this addon was just activated)
535
+	 *
536
+	 * @deprecated since version 4.3.0.alpha.016
537
+	 * @return string
538
+	 */
539
+	public function get_db_update_option_name()
540
+	{
541
+		EE_Error::doing_it_wrong(
542
+			__FUNCTION__,
543
+			esc_html__(
544
+				'EE_Addon::get_db_update_option was renamed to EE_Addon::get_activation_indicator_option_name',
545
+				'event_espresso'
546
+			),
547
+			'4.3.0.alpha.016'
548
+		);
549
+		return $this->get_activation_indicator_option_name();
550
+	}
551
+
552
+
553
+	/**
554
+	 * When the addon is activated, this should be called to set a wordpress option that
555
+	 * indicates it was activated. This is especially useful for detecting reactivations.
556
+	 *
557
+	 * @return bool
558
+	 */
559
+	public function set_activation_indicator_option()
560
+	{
561
+		// let's just handle this on the next request, ok? right now we're just not really ready
562
+		return update_option($this->get_activation_indicator_option_name(), true);
563
+	}
564
+
565
+
566
+	/**
567
+	 * Gets the name of the wp option which is used to temporarily indicate that this addon was activated
568
+	 *
569
+	 * @return string
570
+	 */
571
+	public function get_activation_indicator_option_name()
572
+	{
573
+		return 'ee_activation_' . $this->name();
574
+	}
575
+
576
+
577
+	/**
578
+	 * Used by EE_System to set the request type of this addon. Should not be used by addon developers
579
+	 *
580
+	 * @param int $req_type
581
+	 */
582
+	public function set_req_type($req_type)
583
+	{
584
+		$this->_req_type = $req_type;
585
+	}
586
+
587
+
588
+	/**
589
+	 * Returns the request type of this addon (ie, EE_System::req_type_normal, EE_System::req_type_new_activation,
590
+	 * EE_System::req_type_reactivation, EE_System::req_type_upgrade, or EE_System::req_type_downgrade). This is set by
591
+	 * EE_System when it is checking for new install or upgrades of addons
592
+	 */
593
+	public function detect_req_type()
594
+	{
595
+		if (! $this->_req_type) {
596
+			$this->detect_activation_or_upgrade();
597
+		}
598
+		return $this->_req_type;
599
+	}
600
+
601
+
602
+	/**
603
+	 * Detects the request type for this addon (whether it was just activated, upgrades, a normal request, etc.)
604
+	 * Should only be called once per request
605
+	 *
606
+	 * @return void
607
+	 */
608
+	public function detect_activation_or_upgrade()
609
+	{
610
+		$activation_history_for_addon = $this->get_activation_history();
611 611
 //		d($activation_history_for_addon);
612
-        $request_type = EE_System::detect_req_type_given_activation_history(
613
-            $activation_history_for_addon,
614
-            $this->get_activation_indicator_option_name(),
615
-            $this->version()
616
-        );
617
-        $this->set_req_type($request_type);
618
-        $classname = get_class($this);
619
-        switch ($request_type) {
620
-            case EE_System::req_type_new_activation:
621
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
622
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
623
-                $this->new_install();
624
-                $this->update_list_of_installed_versions($activation_history_for_addon);
625
-                break;
626
-            case EE_System::req_type_reactivation:
627
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
628
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
629
-                $this->reactivation();
630
-                $this->update_list_of_installed_versions($activation_history_for_addon);
631
-                break;
632
-            case EE_System::req_type_upgrade:
633
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
634
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
635
-                $this->upgrade();
636
-                $this->update_list_of_installed_versions($activation_history_for_addon);
637
-                break;
638
-            case EE_System::req_type_downgrade:
639
-                do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
640
-                do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
641
-                $this->downgrade();
642
-                $this->update_list_of_installed_versions($activation_history_for_addon);
643
-                break;
644
-            case EE_System::req_type_normal:
645
-            default:
612
+		$request_type = EE_System::detect_req_type_given_activation_history(
613
+			$activation_history_for_addon,
614
+			$this->get_activation_indicator_option_name(),
615
+			$this->version()
616
+		);
617
+		$this->set_req_type($request_type);
618
+		$classname = get_class($this);
619
+		switch ($request_type) {
620
+			case EE_System::req_type_new_activation:
621
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__new_activation");
622
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__new_activation', $this);
623
+				$this->new_install();
624
+				$this->update_list_of_installed_versions($activation_history_for_addon);
625
+				break;
626
+			case EE_System::req_type_reactivation:
627
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__reactivation");
628
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__reactivation', $this);
629
+				$this->reactivation();
630
+				$this->update_list_of_installed_versions($activation_history_for_addon);
631
+				break;
632
+			case EE_System::req_type_upgrade:
633
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__upgrade");
634
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__upgrade', $this);
635
+				$this->upgrade();
636
+				$this->update_list_of_installed_versions($activation_history_for_addon);
637
+				break;
638
+			case EE_System::req_type_downgrade:
639
+				do_action("AHEE__{$classname}__detect_activations_or_upgrades__downgrade");
640
+				do_action('AHEE__EE_Addon__detect_activations_or_upgrades__downgrade', $this);
641
+				$this->downgrade();
642
+				$this->update_list_of_installed_versions($activation_history_for_addon);
643
+				break;
644
+			case EE_System::req_type_normal:
645
+			default:
646 646
 //				$this->_maybe_redirect_to_ee_about();
647
-                break;
648
-        }
649
-
650
-        do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
651
-    }
652
-
653
-    /**
654
-     * Updates the version history for this addon
655
-     *
656
-     * @param array  $version_history
657
-     * @param string $current_version_to_add
658
-     * @return boolean success
659
-     */
660
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
661
-    {
662
-        if (! $version_history) {
663
-            $version_history = $this->get_activation_history();
664
-        }
665
-        if ($current_version_to_add === null) {
666
-            $current_version_to_add = $this->version();
667
-        }
668
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
669
-        // resave
647
+				break;
648
+		}
649
+
650
+		do_action("AHEE__{$classname}__detect_if_activation_or_upgrade__complete");
651
+	}
652
+
653
+	/**
654
+	 * Updates the version history for this addon
655
+	 *
656
+	 * @param array  $version_history
657
+	 * @param string $current_version_to_add
658
+	 * @return boolean success
659
+	 */
660
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
661
+	{
662
+		if (! $version_history) {
663
+			$version_history = $this->get_activation_history();
664
+		}
665
+		if ($current_version_to_add === null) {
666
+			$current_version_to_add = $this->version();
667
+		}
668
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
669
+		// resave
670 670
 //		echo "updating list of installed versions:".$this->get_activation_history_option_name();d($version_history);
671
-        return update_option($this->get_activation_history_option_name(), $version_history);
672
-    }
673
-
674
-    /**
675
-     * Gets the name of the wp option that stores the activation history
676
-     * of this addon
677
-     *
678
-     * @return string
679
-     */
680
-    public function get_activation_history_option_name()
681
-    {
682
-        return self::ee_addon_version_history_option_prefix . $this->name();
683
-    }
684
-
685
-
686
-    /**
687
-     * Gets the wp option which stores the activation history for this addon
688
-     *
689
-     * @return array
690
-     */
691
-    public function get_activation_history()
692
-    {
693
-        return get_option($this->get_activation_history_option_name(), null);
694
-    }
695
-
696
-
697
-    /**
698
-     * @param string $config_section
699
-     */
700
-    public function set_config_section($config_section = '')
701
-    {
702
-        $this->_config_section = ! empty($config_section) ? $config_section : 'addons';
703
-    }
704
-
705
-    /**
706
-     * Sets the filepath to the main plugin file
707
-     *
708
-     * @param string $filepath
709
-     */
710
-    public function set_main_plugin_file($filepath)
711
-    {
712
-        $this->_main_plugin_file = $filepath;
713
-    }
714
-
715
-    /**
716
-     * gets the filepath to teh main file
717
-     *
718
-     * @return string
719
-     */
720
-    public function get_main_plugin_file()
721
-    {
722
-        return $this->_main_plugin_file;
723
-    }
724
-
725
-    /**
726
-     * Gets the filename (no path) of the main file (the main file loaded
727
-     * by WP)
728
-     *
729
-     * @return string
730
-     */
731
-    public function get_main_plugin_file_basename()
732
-    {
733
-        return plugin_basename($this->get_main_plugin_file());
734
-    }
735
-
736
-    /**
737
-     * Gets the folder name which contains the main plugin file
738
-     *
739
-     * @return string
740
-     */
741
-    public function get_main_plugin_file_dirname()
742
-    {
743
-        return dirname($this->get_main_plugin_file());
744
-    }
745
-
746
-
747
-    /**
748
-     * sets hooks used in the admin
749
-     *
750
-     * @return void
751
-     */
752
-    public function admin_init()
753
-    {
754
-        // is admin and not in M-Mode ?
755
-        if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
756
-            add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
757
-            add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
758
-        }
759
-    }
760
-
761
-
762
-    /**
763
-     * plugin_actions
764
-     * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
765
-     *
766
-     * @param $links
767
-     * @param $file
768
-     * @return array
769
-     */
770
-    public function plugin_action_links($links, $file)
771
-    {
772
-        if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
773
-            // before other links
774
-            array_unshift(
775
-                $links,
776
-                '<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
777
-                . esc_html__('Settings', 'event_espresso')
778
-                . '</a>'
779
-            );
780
-        }
781
-        return $links;
782
-    }
783
-
784
-
785
-    /**
786
-     * after_plugin_row
787
-     * Add additional content to the plugins page plugin row
788
-     * Inserts another row
789
-     *
790
-     * @param $plugin_file
791
-     * @param $plugin_data
792
-     * @param $status
793
-     * @return void
794
-     */
795
-    public function after_plugin_row($plugin_file, $plugin_data, $status)
796
-    {
797
-        $after_plugin_row = '';
798
-        $plugins_page_row = $this->get_plugins_page_row();
799
-        if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
800
-            $class            = $status ? 'active' : 'inactive';
801
-            $link_text        = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
802
-            $link_url         = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
803
-            $description      = isset($plugins_page_row['description'])
804
-                ? $plugins_page_row['description']
805
-                : '';
806
-            if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
807
-                $after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
808
-                $after_plugin_row .= '<th class="check-column" scope="row"></th>';
809
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
810
-                $after_plugin_row .= '<style>
671
+		return update_option($this->get_activation_history_option_name(), $version_history);
672
+	}
673
+
674
+	/**
675
+	 * Gets the name of the wp option that stores the activation history
676
+	 * of this addon
677
+	 *
678
+	 * @return string
679
+	 */
680
+	public function get_activation_history_option_name()
681
+	{
682
+		return self::ee_addon_version_history_option_prefix . $this->name();
683
+	}
684
+
685
+
686
+	/**
687
+	 * Gets the wp option which stores the activation history for this addon
688
+	 *
689
+	 * @return array
690
+	 */
691
+	public function get_activation_history()
692
+	{
693
+		return get_option($this->get_activation_history_option_name(), null);
694
+	}
695
+
696
+
697
+	/**
698
+	 * @param string $config_section
699
+	 */
700
+	public function set_config_section($config_section = '')
701
+	{
702
+		$this->_config_section = ! empty($config_section) ? $config_section : 'addons';
703
+	}
704
+
705
+	/**
706
+	 * Sets the filepath to the main plugin file
707
+	 *
708
+	 * @param string $filepath
709
+	 */
710
+	public function set_main_plugin_file($filepath)
711
+	{
712
+		$this->_main_plugin_file = $filepath;
713
+	}
714
+
715
+	/**
716
+	 * gets the filepath to teh main file
717
+	 *
718
+	 * @return string
719
+	 */
720
+	public function get_main_plugin_file()
721
+	{
722
+		return $this->_main_plugin_file;
723
+	}
724
+
725
+	/**
726
+	 * Gets the filename (no path) of the main file (the main file loaded
727
+	 * by WP)
728
+	 *
729
+	 * @return string
730
+	 */
731
+	public function get_main_plugin_file_basename()
732
+	{
733
+		return plugin_basename($this->get_main_plugin_file());
734
+	}
735
+
736
+	/**
737
+	 * Gets the folder name which contains the main plugin file
738
+	 *
739
+	 * @return string
740
+	 */
741
+	public function get_main_plugin_file_dirname()
742
+	{
743
+		return dirname($this->get_main_plugin_file());
744
+	}
745
+
746
+
747
+	/**
748
+	 * sets hooks used in the admin
749
+	 *
750
+	 * @return void
751
+	 */
752
+	public function admin_init()
753
+	{
754
+		// is admin and not in M-Mode ?
755
+		if (is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
756
+			add_filter('plugin_action_links', array($this, 'plugin_action_links'), 10, 2);
757
+			add_filter('after_plugin_row_' . $this->_plugin_basename, array($this, 'after_plugin_row'), 10, 3);
758
+		}
759
+	}
760
+
761
+
762
+	/**
763
+	 * plugin_actions
764
+	 * Add a settings link to the Plugins page, so people can go straight from the plugin page to the settings page.
765
+	 *
766
+	 * @param $links
767
+	 * @param $file
768
+	 * @return array
769
+	 */
770
+	public function plugin_action_links($links, $file)
771
+	{
772
+		if ($file === $this->plugin_basename() && $this->plugin_action_slug() !== '') {
773
+			// before other links
774
+			array_unshift(
775
+				$links,
776
+				'<a href="admin.php?page=' . $this->plugin_action_slug() . '">'
777
+				. esc_html__('Settings', 'event_espresso')
778
+				. '</a>'
779
+			);
780
+		}
781
+		return $links;
782
+	}
783
+
784
+
785
+	/**
786
+	 * after_plugin_row
787
+	 * Add additional content to the plugins page plugin row
788
+	 * Inserts another row
789
+	 *
790
+	 * @param $plugin_file
791
+	 * @param $plugin_data
792
+	 * @param $status
793
+	 * @return void
794
+	 */
795
+	public function after_plugin_row($plugin_file, $plugin_data, $status)
796
+	{
797
+		$after_plugin_row = '';
798
+		$plugins_page_row = $this->get_plugins_page_row();
799
+		if (! empty($plugins_page_row) && $plugin_file === $this->plugin_basename()) {
800
+			$class            = $status ? 'active' : 'inactive';
801
+			$link_text        = isset($plugins_page_row['link_text']) ? $plugins_page_row['link_text'] : '';
802
+			$link_url         = isset($plugins_page_row['link_url']) ? $plugins_page_row['link_url'] : '';
803
+			$description      = isset($plugins_page_row['description'])
804
+				? $plugins_page_row['description']
805
+				: '';
806
+			if (! empty($link_text) && ! empty($link_url) && ! empty($description)) {
807
+				$after_plugin_row .= '<tr id="' . sanitize_title($plugin_file) . '-ee-addon" class="' . $class . '">';
808
+				$after_plugin_row .= '<th class="check-column" scope="row"></th>';
809
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-title-td plugin-title column-primary">';
810
+				$after_plugin_row .= '<style>
811 811
 .ee-button,
812 812
 .ee-button:active,
813 813
 .ee-button:visited {
@@ -844,49 +844,49 @@  discard block
 block discarded – undo
844 844
 }
845 845
 .ee-button:active { top:0; }
846 846
 </style>';
847
-                $after_plugin_row .= '
847
+				$after_plugin_row .= '
848 848
 <p class="ee-addon-upsell-info-dv">
849 849
 	<a class="ee-button" href="' . $link_url . '">'
850
-                . $link_text
851
-                . ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
852
-                . '</a>
850
+				. $link_text
851
+				. ' &nbsp;<span class="dashicons dashicons-arrow-right-alt2" style="margin:0;"></span>'
852
+				. '</a>
853 853
 </p>';
854
-                $after_plugin_row .= '</td>';
855
-                $after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
856
-                $after_plugin_row .= $description;
857
-                $after_plugin_row .= '</td>';
858
-                $after_plugin_row .= '</tr>';
859
-            } else {
860
-                $after_plugin_row .= $description;
861
-            }
862
-        }
863
-
864
-        echo $after_plugin_row;
865
-    }
866
-
867
-
868
-    /**
869
-     * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
870
-     * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
871
-     * for back compat reasons.
872
-     *
873
-     * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
874
-     *
875
-     * It is recommended, if client code is `de-registering` an add-on, then do it on the
876
-     * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
877
-     * callback does not get run/set in that request.
878
-     *
879
-     * Also, keep in mind that if a registered add-on happens to be deactivated via
880
-     * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
881
-     * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
882
-     * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
883
-     * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
884
-     * to call `parent::deactivation`.
885
-     *
886
-     * @since 4.9.26
887
-     */
888
-    public function after_registration()
889
-    {
890
-        // cricket chirp... cricket chirp...
891
-    }
854
+				$after_plugin_row .= '</td>';
855
+				$after_plugin_row .= '<td class="ee-addon-upsell-info-desc-td column-description desc">';
856
+				$after_plugin_row .= $description;
857
+				$after_plugin_row .= '</td>';
858
+				$after_plugin_row .= '</tr>';
859
+			} else {
860
+				$after_plugin_row .= $description;
861
+			}
862
+		}
863
+
864
+		echo $after_plugin_row;
865
+	}
866
+
867
+
868
+	/**
869
+	 * A safe space for addons to add additional logic like setting hooks that need to be set early in the request.
870
+	 * Child classes that have logic like that to run can override this method declaration.  This was not made abstract
871
+	 * for back compat reasons.
872
+	 *
873
+	 * This will fire on the `AHEE__EE_System__load_espresso_addons__complete` hook at priority 999.
874
+	 *
875
+	 * It is recommended, if client code is `de-registering` an add-on, then do it on the
876
+	 * `AHEE__EE_System__load_espresso_addons__complete` hook before priority 999 so as to ensure any code logic in this
877
+	 * callback does not get run/set in that request.
878
+	 *
879
+	 * Also, keep in mind that if a registered add-on happens to be deactivated via
880
+	 * EE_System::_deactivate_incompatible_addons() because its incompatible, any code executed in this method
881
+	 * (including setting hooks etc) will have executed before the plugin was deactivated.  If you use
882
+	 * `after_registration` to set any filter and/or action hooks and want to ensure they are removed on this add-on's
883
+	 * deactivation, you can override `EE_Addon::deactivation` and unset your hooks and filters there.  Just remember
884
+	 * to call `parent::deactivation`.
885
+	 *
886
+	 * @since 4.9.26
887
+	 */
888
+	public function after_registration()
889
+	{
890
+		// cricket chirp... cricket chirp...
891
+	}
892 892
 }
Please login to merge, or discard this patch.
core/CPTs/EE_Register_CPTs.core.php 2 patches
Indentation   +314 added lines, -314 removed lines patch added patch discarded remove patch
@@ -8,7 +8,7 @@  discard block
 block discarded – undo
8 8
 use EventEspresso\core\services\loaders\LoaderFactory;
9 9
 
10 10
 if (! defined('EVENT_ESPRESSO_VERSION')) {
11
-    exit('No direct script access allowed');
11
+	exit('No direct script access allowed');
12 12
 }
13 13
 
14 14
 
@@ -25,303 +25,303 @@  discard block
 block discarded – undo
25 25
 {
26 26
 
27 27
 
28
-    /**
29
-     * instantiated at init priority 5
30
-     *
31
-     * @deprecated $VID:$
32
-     */
33
-    public function __construct()
34
-    {
35
-        do_action('AHEE__EE_Register_CPTs__construct_end', $this);
36
-    }
37
-
38
-
39
-    /**
40
-     * This will flush rewrite rules on demand.  This actually gets called around wp init priority level 100.
41
-     *
42
-     * @deprecated $VID:$
43
-     * @return void
44
-     * @throws InvalidInterfaceException
45
-     * @throws InvalidDataTypeException
46
-     * @throws InvalidArgumentException
47
-     */
48
-    public static function maybe_flush_rewrite_rules()
49
-    {
50
-        /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
51
-        $rewrite_rules = LoaderFactory::getLoader()->getShared(
52
-            'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
53
-        );
54
-        $rewrite_rules->flushRewriteRules();
55
-    }
56
-
57
-
58
-    /**
59
-     * @return CustomTaxonomyDefinitions
60
-     * @throws InvalidArgumentException
61
-     * @throws InvalidDataTypeException
62
-     * @throws InvalidInterfaceException
63
-     */
64
-    public static function getTaxonomyDefinitions()
65
-    {
66
-        return LoaderFactory::getLoader()->getShared(
67
-            'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions'
68
-        );
69
-    }
70
-
71
-
72
-    /**
73
-     * @deprecated $VID:$
74
-     * @param string $description The description content.
75
-     * @param string $taxonomy    The taxonomy name for the taxonomy being filtered.
76
-     * @return string
77
-     * @throws InvalidArgumentException
78
-     * @throws InvalidDataTypeException
79
-     * @throws InvalidInterfaceException
80
-     */
81
-    public function ee_filter_ee_term_description_not_wp($description, $taxonomy)
82
-    {
83
-        $taxonomies = EE_Register_CPTs::getTaxonomyDefinitions();
84
-        return $taxonomies->filterCustomTermDescription($description, $taxonomy);
85
-    }
86
-
87
-
88
-    /**
89
-     * @deprecated $VID:$
90
-     * @return array
91
-     * @throws InvalidArgumentException
92
-     * @throws InvalidDataTypeException
93
-     * @throws InvalidInterfaceException
94
-     */
95
-    public static function get_taxonomies()
96
-    {
97
-        $taxonomies = EE_Register_CPTs::getTaxonomyDefinitions();
98
-        return $taxonomies->getCustomTaxonomyDefinitions();
99
-    }
100
-
101
-
102
-    /**
103
-     * @return CustomPostTypeDefinitions
104
-     * @throws InvalidArgumentException
105
-     * @throws InvalidDataTypeException
106
-     * @throws InvalidInterfaceException
107
-     */
108
-    public static function getCustomPostTypeDefinitions()
109
-    {
110
-        return LoaderFactory::getLoader()->getShared(
111
-            'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
112
-        );
113
-    }
114
-
115
-
116
-    /**
117
-     * @deprecated $VID:$
118
-     * @return array
119
-     * @throws InvalidArgumentException
120
-     * @throws InvalidDataTypeException
121
-     * @throws InvalidInterfaceException
122
-     */
123
-    public static function get_CPTs()
124
-    {
125
-        $custom_post_types = EE_Register_CPTs::getCustomPostTypeDefinitions();
126
-        return $custom_post_types->getDefinitions();
127
-    }
128
-
129
-
130
-    /**
131
-     * @deprecated $VID:$
132
-     * @return array
133
-     * @throws InvalidArgumentException
134
-     * @throws InvalidDataTypeException
135
-     * @throws InvalidInterfaceException
136
-     */
137
-    public static function get_private_CPTs()
138
-    {
139
-        $custom_post_types = EE_Register_CPTs::getCustomPostTypeDefinitions();
140
-        return $custom_post_types->getPrivateCustomPostTypes();
141
-    }
142
-
143
-
144
-    /**
145
-     * @deprecated $VID:$
146
-     * @param string $post_type_slug              If a slug is included, then attempt to retrieve the model name for
147
-     *                                            the given cpt slug.  Otherwise if empty, then we'll return all cpt
148
-     *                                            model names for cpts registered in EE.
149
-     * @return array           Empty array if no matching model names for the given slug or an array of model
150
-     *                                            names indexed by post type slug.
151
-     * @throws InvalidArgumentException
152
-     * @throws InvalidDataTypeException
153
-     * @throws InvalidInterfaceException
154
-     */
155
-    public static function get_cpt_model_names($post_type_slug = '')
156
-    {
157
-        $custom_post_types = EE_Register_CPTs::getCustomPostTypeDefinitions();
158
-        return $custom_post_types->getCustomPostTypeModelNames($post_type_slug);
159
-    }
160
-
161
-
162
-    /**
163
-     * @deprecated $VID:$
164
-     * @param string $post_type_slug If valid slug is provided, then will instantiate the model only for
165
-     *                               the cpt matching the given slug.  Otherwise all cpt models will be
166
-     *                               instantiated (if possible).
167
-     * @return EEM_CPT_Base[]        successful instantiation will return an array of successfully instantiated
168
-     *                               EEM models indexed by post slug.
169
-     * @throws InvalidArgumentException
170
-     * @throws InvalidDataTypeException
171
-     * @throws InvalidInterfaceException
172
-     */
173
-    public static function instantiate_cpt_models($post_type_slug = '')
174
-    {
175
-        $custom_post_types = EE_Register_CPTs::getCustomPostTypeDefinitions();
176
-        return $custom_post_types->getCustomPostTypeModels($post_type_slug);
177
-    }
178
-
179
-
180
-    /**
181
-     * @deprecated $VID:$
182
-     * @param string $taxonomy_name , eg 'books'
183
-     * @param string $singular_name internationalized singular name
184
-     * @param string $plural_name   internationalized plural name
185
-     * @param array  $override_args like $args on http://codex.wordpress.org/Function_Reference/register_taxonomy
186
-     * @throws InvalidArgumentException
187
-     * @throws InvalidDataTypeException
188
-     * @throws InvalidInterfaceException
189
-     * @throws DomainException
190
-     */
191
-    public function register_taxonomy($taxonomy_name, $singular_name, $plural_name, $override_args = array())
192
-    {
193
-        /** @var \EventEspresso\core\domain\services\custom_post_types\registerCustomTaxonomies $taxonomies */
194
-        $taxonomies = LoaderFactory::getLoader()->getShared(
195
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'
196
-        );
197
-        $taxonomies->registerCustomTaxonomy(
198
-            $taxonomy_name,
199
-            $singular_name,
200
-            $plural_name,
201
-            $override_args
202
-        );
203
-    }
204
-
205
-
206
-    /**
207
-     * @deprecated $VID:$
208
-     * @param string $post_type     the actual post type name
209
-     *                              (VERY IMPORTANT: this much match what the slug is for admin pages related to this
210
-     *                              cpt Also any models must use this slug as well)
211
-     * @param string $singular_name a pre-internationalized string for the singular name of the objects
212
-     * @param string $plural_name   a pre-internalized string for the plural name of the objects
213
-     * @param array  $override_args exactly like $args as described in
214
-     *                              http://codex.wordpress.org/Function_Reference/register_post_type The default values
215
-     *                              set in this function will be overridden by whatever you set in $override_args
216
-     * @param string $singular_slug
217
-     * @param string $plural_slug
218
-     * @return void , but registers the custom post type
219
-     * @throws InvalidArgumentException
220
-     * @throws InvalidDataTypeException
221
-     * @throws InvalidInterfaceException
222
-     * @throws DomainException
223
-     */
224
-    public function register_CPT(
225
-        $post_type,
226
-        $singular_name,
227
-        $plural_name,
228
-        $override_args = array(),
229
-        $singular_slug = '',
230
-        $plural_slug = ''
231
-    ) {
232
-        /** @var \EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes $register_custom_post_types */
233
-        $register_custom_post_types = LoaderFactory::getLoader()->getShared(
234
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'
235
-        );
236
-        $register_custom_post_types->registerCustomPostType(
237
-            $post_type,
238
-            $singular_name,
239
-            $plural_name,
240
-            $singular_slug,
241
-            $plural_slug,
242
-            $override_args
243
-        );
244
-    }
245
-
246
-
247
-    /**
248
-     * @return RegisterCustomTaxonomyTerms
249
-     * @throws InvalidArgumentException
250
-     * @throws InvalidDataTypeException
251
-     * @throws InvalidInterfaceException
252
-     */
253
-    public static function getRegisterCustomTaxonomyTerms()
254
-    {
255
-        return LoaderFactory::getLoader()->getShared(
256
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms'
257
-        );
258
-    }
259
-
260
-
261
-    /**
262
-     * @deprecated $VID:$
263
-     * @throws InvalidArgumentException
264
-     * @throws InvalidDataTypeException
265
-     * @throws InvalidInterfaceException
266
-     */
267
-    public function set_must_use_event_types()
268
-    {
269
-        $register_custom_taxonomy_terms = EE_Register_CPTs::getRegisterCustomTaxonomyTerms();
270
-        $register_custom_taxonomy_terms->setMustUseEventTypes();
271
-    }
272
-
273
-
274
-    /**
275
-     * @deprecated $VID:$
276
-     * @param string $taxonomy     The name of the taxonomy
277
-     * @param array  $term_details An array of term details indexed by slug and containing Name of term, and
278
-     *                             description as the elements in the array
279
-     * @return void
280
-     * @throws InvalidArgumentException
281
-     * @throws InvalidDataTypeException
282
-     * @throws InvalidInterfaceException
283
-     */
284
-    public function set_must_use_terms($taxonomy, $term_details)
285
-    {
286
-        $register_custom_taxonomy_terms = EE_Register_CPTs::getRegisterCustomTaxonomyTerms();
287
-        $register_custom_taxonomy_terms->setMustUseTerms($taxonomy, $term_details);
288
-    }
289
-
290
-
291
-    /**
292
-     * @deprecated $VID:$
293
-     * @param string $taxonomy  The taxonomy we're using for the default term
294
-     * @param string $term_slug The slug of the term that will be the default.
295
-     * @param array  $cpt_slugs An array of custom post types we want the default assigned to
296
-     * @throws InvalidArgumentException
297
-     * @throws InvalidDataTypeException
298
-     * @throws InvalidInterfaceException
299
-     */
300
-    public function set_default_term($taxonomy, $term_slug, $cpt_slugs = array())
301
-    {
302
-        $register_custom_taxonomy_terms = EE_Register_CPTs::getRegisterCustomTaxonomyTerms();
303
-        $register_custom_taxonomy_terms->registerCustomTaxonomyTerm(
304
-            $taxonomy,
305
-            $term_slug,
306
-            $cpt_slugs
307
-        );
308
-    }
309
-
310
-
311
-    /**
312
-     * @deprecated $VID:$
313
-     * @param  int     $post_id ID of CPT being saved
314
-     * @param  WP_Post $post    Post object
315
-     * @return void
316
-     * @throws InvalidArgumentException
317
-     * @throws InvalidDataTypeException
318
-     * @throws InvalidInterfaceException
319
-     */
320
-    public function save_default_term($post_id, $post)
321
-    {
322
-        $register_custom_taxonomy_terms = EE_Register_CPTs::getRegisterCustomTaxonomyTerms();
323
-        $register_custom_taxonomy_terms->saveDefaultTerm($post_id, $post);
324
-    }
28
+	/**
29
+	 * instantiated at init priority 5
30
+	 *
31
+	 * @deprecated $VID:$
32
+	 */
33
+	public function __construct()
34
+	{
35
+		do_action('AHEE__EE_Register_CPTs__construct_end', $this);
36
+	}
37
+
38
+
39
+	/**
40
+	 * This will flush rewrite rules on demand.  This actually gets called around wp init priority level 100.
41
+	 *
42
+	 * @deprecated $VID:$
43
+	 * @return void
44
+	 * @throws InvalidInterfaceException
45
+	 * @throws InvalidDataTypeException
46
+	 * @throws InvalidArgumentException
47
+	 */
48
+	public static function maybe_flush_rewrite_rules()
49
+	{
50
+		/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
51
+		$rewrite_rules = LoaderFactory::getLoader()->getShared(
52
+			'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
53
+		);
54
+		$rewrite_rules->flushRewriteRules();
55
+	}
56
+
57
+
58
+	/**
59
+	 * @return CustomTaxonomyDefinitions
60
+	 * @throws InvalidArgumentException
61
+	 * @throws InvalidDataTypeException
62
+	 * @throws InvalidInterfaceException
63
+	 */
64
+	public static function getTaxonomyDefinitions()
65
+	{
66
+		return LoaderFactory::getLoader()->getShared(
67
+			'EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions'
68
+		);
69
+	}
70
+
71
+
72
+	/**
73
+	 * @deprecated $VID:$
74
+	 * @param string $description The description content.
75
+	 * @param string $taxonomy    The taxonomy name for the taxonomy being filtered.
76
+	 * @return string
77
+	 * @throws InvalidArgumentException
78
+	 * @throws InvalidDataTypeException
79
+	 * @throws InvalidInterfaceException
80
+	 */
81
+	public function ee_filter_ee_term_description_not_wp($description, $taxonomy)
82
+	{
83
+		$taxonomies = EE_Register_CPTs::getTaxonomyDefinitions();
84
+		return $taxonomies->filterCustomTermDescription($description, $taxonomy);
85
+	}
86
+
87
+
88
+	/**
89
+	 * @deprecated $VID:$
90
+	 * @return array
91
+	 * @throws InvalidArgumentException
92
+	 * @throws InvalidDataTypeException
93
+	 * @throws InvalidInterfaceException
94
+	 */
95
+	public static function get_taxonomies()
96
+	{
97
+		$taxonomies = EE_Register_CPTs::getTaxonomyDefinitions();
98
+		return $taxonomies->getCustomTaxonomyDefinitions();
99
+	}
100
+
101
+
102
+	/**
103
+	 * @return CustomPostTypeDefinitions
104
+	 * @throws InvalidArgumentException
105
+	 * @throws InvalidDataTypeException
106
+	 * @throws InvalidInterfaceException
107
+	 */
108
+	public static function getCustomPostTypeDefinitions()
109
+	{
110
+		return LoaderFactory::getLoader()->getShared(
111
+			'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
112
+		);
113
+	}
114
+
115
+
116
+	/**
117
+	 * @deprecated $VID:$
118
+	 * @return array
119
+	 * @throws InvalidArgumentException
120
+	 * @throws InvalidDataTypeException
121
+	 * @throws InvalidInterfaceException
122
+	 */
123
+	public static function get_CPTs()
124
+	{
125
+		$custom_post_types = EE_Register_CPTs::getCustomPostTypeDefinitions();
126
+		return $custom_post_types->getDefinitions();
127
+	}
128
+
129
+
130
+	/**
131
+	 * @deprecated $VID:$
132
+	 * @return array
133
+	 * @throws InvalidArgumentException
134
+	 * @throws InvalidDataTypeException
135
+	 * @throws InvalidInterfaceException
136
+	 */
137
+	public static function get_private_CPTs()
138
+	{
139
+		$custom_post_types = EE_Register_CPTs::getCustomPostTypeDefinitions();
140
+		return $custom_post_types->getPrivateCustomPostTypes();
141
+	}
142
+
143
+
144
+	/**
145
+	 * @deprecated $VID:$
146
+	 * @param string $post_type_slug              If a slug is included, then attempt to retrieve the model name for
147
+	 *                                            the given cpt slug.  Otherwise if empty, then we'll return all cpt
148
+	 *                                            model names for cpts registered in EE.
149
+	 * @return array           Empty array if no matching model names for the given slug or an array of model
150
+	 *                                            names indexed by post type slug.
151
+	 * @throws InvalidArgumentException
152
+	 * @throws InvalidDataTypeException
153
+	 * @throws InvalidInterfaceException
154
+	 */
155
+	public static function get_cpt_model_names($post_type_slug = '')
156
+	{
157
+		$custom_post_types = EE_Register_CPTs::getCustomPostTypeDefinitions();
158
+		return $custom_post_types->getCustomPostTypeModelNames($post_type_slug);
159
+	}
160
+
161
+
162
+	/**
163
+	 * @deprecated $VID:$
164
+	 * @param string $post_type_slug If valid slug is provided, then will instantiate the model only for
165
+	 *                               the cpt matching the given slug.  Otherwise all cpt models will be
166
+	 *                               instantiated (if possible).
167
+	 * @return EEM_CPT_Base[]        successful instantiation will return an array of successfully instantiated
168
+	 *                               EEM models indexed by post slug.
169
+	 * @throws InvalidArgumentException
170
+	 * @throws InvalidDataTypeException
171
+	 * @throws InvalidInterfaceException
172
+	 */
173
+	public static function instantiate_cpt_models($post_type_slug = '')
174
+	{
175
+		$custom_post_types = EE_Register_CPTs::getCustomPostTypeDefinitions();
176
+		return $custom_post_types->getCustomPostTypeModels($post_type_slug);
177
+	}
178
+
179
+
180
+	/**
181
+	 * @deprecated $VID:$
182
+	 * @param string $taxonomy_name , eg 'books'
183
+	 * @param string $singular_name internationalized singular name
184
+	 * @param string $plural_name   internationalized plural name
185
+	 * @param array  $override_args like $args on http://codex.wordpress.org/Function_Reference/register_taxonomy
186
+	 * @throws InvalidArgumentException
187
+	 * @throws InvalidDataTypeException
188
+	 * @throws InvalidInterfaceException
189
+	 * @throws DomainException
190
+	 */
191
+	public function register_taxonomy($taxonomy_name, $singular_name, $plural_name, $override_args = array())
192
+	{
193
+		/** @var \EventEspresso\core\domain\services\custom_post_types\registerCustomTaxonomies $taxonomies */
194
+		$taxonomies = LoaderFactory::getLoader()->getShared(
195
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'
196
+		);
197
+		$taxonomies->registerCustomTaxonomy(
198
+			$taxonomy_name,
199
+			$singular_name,
200
+			$plural_name,
201
+			$override_args
202
+		);
203
+	}
204
+
205
+
206
+	/**
207
+	 * @deprecated $VID:$
208
+	 * @param string $post_type     the actual post type name
209
+	 *                              (VERY IMPORTANT: this much match what the slug is for admin pages related to this
210
+	 *                              cpt Also any models must use this slug as well)
211
+	 * @param string $singular_name a pre-internationalized string for the singular name of the objects
212
+	 * @param string $plural_name   a pre-internalized string for the plural name of the objects
213
+	 * @param array  $override_args exactly like $args as described in
214
+	 *                              http://codex.wordpress.org/Function_Reference/register_post_type The default values
215
+	 *                              set in this function will be overridden by whatever you set in $override_args
216
+	 * @param string $singular_slug
217
+	 * @param string $plural_slug
218
+	 * @return void , but registers the custom post type
219
+	 * @throws InvalidArgumentException
220
+	 * @throws InvalidDataTypeException
221
+	 * @throws InvalidInterfaceException
222
+	 * @throws DomainException
223
+	 */
224
+	public function register_CPT(
225
+		$post_type,
226
+		$singular_name,
227
+		$plural_name,
228
+		$override_args = array(),
229
+		$singular_slug = '',
230
+		$plural_slug = ''
231
+	) {
232
+		/** @var \EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes $register_custom_post_types */
233
+		$register_custom_post_types = LoaderFactory::getLoader()->getShared(
234
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'
235
+		);
236
+		$register_custom_post_types->registerCustomPostType(
237
+			$post_type,
238
+			$singular_name,
239
+			$plural_name,
240
+			$singular_slug,
241
+			$plural_slug,
242
+			$override_args
243
+		);
244
+	}
245
+
246
+
247
+	/**
248
+	 * @return RegisterCustomTaxonomyTerms
249
+	 * @throws InvalidArgumentException
250
+	 * @throws InvalidDataTypeException
251
+	 * @throws InvalidInterfaceException
252
+	 */
253
+	public static function getRegisterCustomTaxonomyTerms()
254
+	{
255
+		return LoaderFactory::getLoader()->getShared(
256
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms'
257
+		);
258
+	}
259
+
260
+
261
+	/**
262
+	 * @deprecated $VID:$
263
+	 * @throws InvalidArgumentException
264
+	 * @throws InvalidDataTypeException
265
+	 * @throws InvalidInterfaceException
266
+	 */
267
+	public function set_must_use_event_types()
268
+	{
269
+		$register_custom_taxonomy_terms = EE_Register_CPTs::getRegisterCustomTaxonomyTerms();
270
+		$register_custom_taxonomy_terms->setMustUseEventTypes();
271
+	}
272
+
273
+
274
+	/**
275
+	 * @deprecated $VID:$
276
+	 * @param string $taxonomy     The name of the taxonomy
277
+	 * @param array  $term_details An array of term details indexed by slug and containing Name of term, and
278
+	 *                             description as the elements in the array
279
+	 * @return void
280
+	 * @throws InvalidArgumentException
281
+	 * @throws InvalidDataTypeException
282
+	 * @throws InvalidInterfaceException
283
+	 */
284
+	public function set_must_use_terms($taxonomy, $term_details)
285
+	{
286
+		$register_custom_taxonomy_terms = EE_Register_CPTs::getRegisterCustomTaxonomyTerms();
287
+		$register_custom_taxonomy_terms->setMustUseTerms($taxonomy, $term_details);
288
+	}
289
+
290
+
291
+	/**
292
+	 * @deprecated $VID:$
293
+	 * @param string $taxonomy  The taxonomy we're using for the default term
294
+	 * @param string $term_slug The slug of the term that will be the default.
295
+	 * @param array  $cpt_slugs An array of custom post types we want the default assigned to
296
+	 * @throws InvalidArgumentException
297
+	 * @throws InvalidDataTypeException
298
+	 * @throws InvalidInterfaceException
299
+	 */
300
+	public function set_default_term($taxonomy, $term_slug, $cpt_slugs = array())
301
+	{
302
+		$register_custom_taxonomy_terms = EE_Register_CPTs::getRegisterCustomTaxonomyTerms();
303
+		$register_custom_taxonomy_terms->registerCustomTaxonomyTerm(
304
+			$taxonomy,
305
+			$term_slug,
306
+			$cpt_slugs
307
+		);
308
+	}
309
+
310
+
311
+	/**
312
+	 * @deprecated $VID:$
313
+	 * @param  int     $post_id ID of CPT being saved
314
+	 * @param  WP_Post $post    Post object
315
+	 * @return void
316
+	 * @throws InvalidArgumentException
317
+	 * @throws InvalidDataTypeException
318
+	 * @throws InvalidInterfaceException
319
+	 */
320
+	public function save_default_term($post_id, $post)
321
+	{
322
+		$register_custom_taxonomy_terms = EE_Register_CPTs::getRegisterCustomTaxonomyTerms();
323
+		$register_custom_taxonomy_terms->saveDefaultTerm($post_id, $post);
324
+	}
325 325
 }
326 326
 
327 327
 
@@ -335,24 +335,24 @@  discard block
 block discarded – undo
335 335
 class EE_Default_Term
336 336
 {
337 337
 
338
-    //props holding the items
339
-    public $taxonomy  = '';
338
+	//props holding the items
339
+	public $taxonomy  = '';
340 340
 
341
-    public $cpt_slugs = array();
341
+	public $cpt_slugs = array();
342 342
 
343
-    public $term_slug = '';
343
+	public $term_slug = '';
344 344
 
345 345
 
346
-    /**
347
-     * @deprecated $VID:$
348
-     * @param string $taxonomy The taxonomy the default term belongs to
349
-     * @param string $term_slug The slug of the term that will be the default.
350
-     * @param array  $cpt_slugs The custom post type the default term gets saved with
351
-     */
352
-    public function __construct($taxonomy, $term_slug, $cpt_slugs = array())
353
-    {
354
-        $this->taxonomy  = $taxonomy;
355
-        $this->cpt_slugs = (array) $cpt_slugs;
356
-        $this->term_slug = $term_slug;
357
-    }
346
+	/**
347
+	 * @deprecated $VID:$
348
+	 * @param string $taxonomy The taxonomy the default term belongs to
349
+	 * @param string $term_slug The slug of the term that will be the default.
350
+	 * @param array  $cpt_slugs The custom post type the default term gets saved with
351
+	 */
352
+	public function __construct($taxonomy, $term_slug, $cpt_slugs = array())
353
+	{
354
+		$this->taxonomy  = $taxonomy;
355
+		$this->cpt_slugs = (array) $cpt_slugs;
356
+		$this->term_slug = $term_slug;
357
+	}
358 358
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -7,7 +7,7 @@
 block discarded – undo
7 7
 use EventEspresso\core\exceptions\InvalidInterfaceException;
8 8
 use EventEspresso\core\services\loaders\LoaderFactory;
9 9
 
10
-if (! defined('EVENT_ESPRESSO_VERSION')) {
10
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
11 11
     exit('No direct script access allowed');
12 12
 }
13 13
 
Please login to merge, or discard this patch.
core/domain/services/custom_post_types/RewriteRules.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -17,30 +17,30 @@
 block discarded – undo
17 17
 class RewriteRules
18 18
 {
19 19
 
20
-    const OPTION_KEY_FLUSH_REWRITE_RULES = 'ee_flush_rewrite_rules';
21
-
22
-
23
-    /**
24
-     * This will flush rewrite rules on demand.  This actually gets called around wp init priority level 100.
25
-     *
26
-     * @return void
27
-     */
28
-    public function flush()
29
-    {
30
-        update_option(RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES, true);
31
-    }
32
-
33
-
34
-    /**
35
-     * This will flush rewrite rules on demand.  This actually gets called around wp init priority level 100.
36
-     *
37
-     * @return void
38
-     */
39
-    public function flushRewriteRules()
40
-    {
41
-        if (get_option(RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES, true)) {
42
-            flush_rewrite_rules();
43
-            update_option(RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES, false);
44
-        }
45
-    }
20
+	const OPTION_KEY_FLUSH_REWRITE_RULES = 'ee_flush_rewrite_rules';
21
+
22
+
23
+	/**
24
+	 * This will flush rewrite rules on demand.  This actually gets called around wp init priority level 100.
25
+	 *
26
+	 * @return void
27
+	 */
28
+	public function flush()
29
+	{
30
+		update_option(RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES, true);
31
+	}
32
+
33
+
34
+	/**
35
+	 * This will flush rewrite rules on demand.  This actually gets called around wp init priority level 100.
36
+	 *
37
+	 * @return void
38
+	 */
39
+	public function flushRewriteRules()
40
+	{
41
+		if (get_option(RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES, true)) {
42
+			flush_rewrite_rules();
43
+			update_option(RewriteRules::OPTION_KEY_FLUSH_REWRITE_RULES, false);
44
+		}
45
+	}
46 46
 }
Please login to merge, or discard this patch.
core/domain/services/custom_post_types/RegisterCustomTaxonomyTerms.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
      */
66 66
     public function registerCustomTaxonomyTerm($taxonomy, $term_slug, array $cpt_slugs = array())
67 67
     {
68
-        $this->custom_taxonomy_terms[][ $term_slug ] = new CustomTaxonomyTerm(
68
+        $this->custom_taxonomy_terms[][$term_slug] = new CustomTaxonomyTerm(
69 69
             $taxonomy,
70 70
             $term_slug,
71 71
             $cpt_slugs
Please login to merge, or discard this patch.
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -20,182 +20,182 @@
 block discarded – undo
20 20
 class RegisterCustomTaxonomyTerms
21 21
 {
22 22
 
23
-    /**
24
-     * @var array[] $custom_taxonomy_terms
25
-     */
26
-    public $custom_taxonomy_terms = array();
27
-
28
-
29
-    /**
30
-     * RegisterCustomTaxonomyTerms constructor.
31
-     */
32
-    public function __construct()
33
-    {
34
-        // hook into save_post so that we can make sure that the default terms get saved on publish of registered cpts
35
-        // IF they don't have a term for that taxonomy set.
36
-        add_action('save_post', array($this, 'saveDefaultTerm'), 100, 2);
37
-        do_action(
38
-            'AHEE__EventEspresso_core_domain_services_custom_post_types_RegisterCustomTaxonomyTerms__construct_end',
39
-            $this
40
-        );
41
-    }
42
-
43
-
44
-    public function registerCustomTaxonomyTerms()
45
-    {
46
-        // setup default terms in any of our taxonomies (but only if we're in admin).
47
-        // Why not added via register_activation_hook?
48
-        // Because it's possible that in future iterations of EE we may add new defaults for specialized taxonomies
49
-        // (think event_types) and register_activation_hook only reliably runs when a user manually activates the plugin.
50
-        // Keep in mind that this will READ these terms if they are deleted by the user.  Hence MUST use terms.
51
-        // if ( is_admin() ) {
52
-        // 	$this->set_must_use_event_types();
53
-        // }
54
-        //set default terms
55
-        $this->registerCustomTaxonomyTerm(
56
-            'espresso_event_type',
57
-            'single-event',
58
-            array('espresso_events')
59
-        );
60
-    }
61
-
62
-
63
-    /**
64
-     * Allows us to set what the default will be for terms when a cpt is PUBLISHED.
65
-     *
66
-     * @param string $taxonomy  The taxonomy we're using for the default term
67
-     * @param string $term_slug The slug of the term that will be the default.
68
-     * @param array  $cpt_slugs An array of custom post types we want the default assigned to
69
-     */
70
-    public function registerCustomTaxonomyTerm($taxonomy, $term_slug, array $cpt_slugs = array())
71
-    {
72
-        $this->custom_taxonomy_terms[][ $term_slug ] = new CustomTaxonomyTerm(
73
-            $taxonomy,
74
-            $term_slug,
75
-            $cpt_slugs
76
-        );
77
-    }
78
-
79
-
80
-    /**
81
-     * hooked into the wp 'save_post' action hook for setting our default terms found in the $_default_terms property
82
-     *
83
-     * @param  int    $post_id ID of CPT being saved
84
-     * @param  WP_Post $post    Post object
85
-     * @return void
86
-     */
87
-    public function saveDefaultTerm($post_id, WP_Post $post)
88
-    {
89
-        if (empty($this->custom_taxonomy_terms)) {
90
-            return;
91
-        }
92
-        //no default terms set so lets just exit.
93
-        foreach ($this->custom_taxonomy_terms as $custom_taxonomy_terms) {
94
-            foreach ($custom_taxonomy_terms as $custom_taxonomy_term) {
95
-                if (
96
-                    $post->post_status === 'publish'
97
-                    && $custom_taxonomy_term instanceof CustomTaxonomyTerm
98
-                    && in_array($post->post_type, $custom_taxonomy_term->customPostTypeSlugs(), true)
99
-                ) {
100
-                    //note some error proofing going on here to save unnecessary db queries
101
-                    $taxonomies = get_object_taxonomies($post->post_type);
102
-                    foreach ($taxonomies as $taxonomy) {
103
-                        $terms = wp_get_post_terms($post_id, $taxonomy);
104
-                        if (empty($terms) && $taxonomy === $custom_taxonomy_term->taxonomySlug()) {
105
-                            wp_set_object_terms(
106
-                                $post_id,
107
-                                array($custom_taxonomy_term->termSlug()),
108
-                                $taxonomy
109
-                            );
110
-                        }
111
-                    }
112
-                }
113
-            }
114
-        }
115
-    }
116
-
117
-
118
-    /**
119
-     * @return void
120
-     */
121
-    public function setMustUseEventTypes()
122
-    {
123
-        $term_details = array(
124
-            //Attendee's register for the first date-time only
125
-            'single-event'    => array(
126
-                'term' => esc_html__('Single Event', 'event_espresso'),
127
-                'desc' => esc_html__(
128
-                    'A single event that spans one or more consecutive days.',
129
-                    'event_espresso'
130
-                ),
131
-            ),
132
-            //example: a party or two-day long workshop
133
-            //Attendee's can register for any of the date-times
134
-            'multi-event'     => array(
135
-                'term' => esc_html__('Multi Event', 'event_espresso'),
136
-                'desc' => esc_html__(
137
-                    'Multiple, separate, but related events that occur on consecutive days.',
138
-                    'event_espresso'
139
-                ),
140
-            ),
141
-            //example: a three day music festival or week long conference
142
-            //Attendee's register for the first date-time only
143
-            'event-series'    => array(
144
-                'term' => esc_html__('Event Series', 'event_espresso'),
145
-                'desc' => esc_html__(
146
-                    ' Multiple events that occur over multiple non-consecutive days.',
147
-                    'event_espresso'
148
-                ),
149
-            ),
150
-            //example: an 8 week introduction to basket weaving course
151
-            //Attendee's can register for any of the date-times.
152
-            'recurring-event' => array(
153
-                'term' => esc_html__('Recurring Event', 'event_espresso'),
154
-                'desc' => esc_html__(
155
-                    'Multiple events that occur over multiple non-consecutive days.',
156
-                    'event_espresso'
157
-                ),
158
-            ),
159
-            //example: a yoga class
160
-            'ongoing'         => array(
161
-                'term' => esc_html__('Ongoing Event', 'event_espresso'),
162
-                'desc' => esc_html__(
163
-                    'An "event" that people can purchase tickets to gain access for anytime for this event regardless of date times on the event',
164
-                    'event_espresso'
165
-                ),
166
-            )
167
-            //example: access to a museum
168
-            //'walk-in' => array( esc_html__('Walk In', 'event_espresso'), esc_html__('Single datetime and single entry recurring events. Attendees register for one or multiple datetimes individually.', 'event_espresso') ),
169
-            //'reservation' => array( esc_html__('Reservation', 'event_espresso'), esc_html__('Reservations are created by specifying available datetimes and quantities. Attendees choose from the available datetimes and specify the quantity available (if the maximum is greater than 1)') ), //@TODO to avoid confusion we'll implement this in a later iteration > EE4.1
170
-            // 'multiple-session' => array( esc_html__('Multiple Session', 'event_espresso'), esc_html__('Multiple event, multiple datetime, hierarchically organized, custom entry events. Attendees may be required to register for a parent event before being allowed to register for child events. Attendees can register for any combination of child events as long as the datetimes do not conflict. Parent and child events may have additional fees or registration questions.') ), //@TODO to avoid confusion we'll implement this in a later iteration > EE4.1
171
-            //'appointment' => array( esc_html__('Appointments', 'event_espresso'), esc_html__('Time slotted events where datetimes are generally in hours or minutes. For example, attendees can register for a single 15 minute or 1 hour time slot and this type of availability frequently reoccurs.', 'event_espresso') )
172
-        );
173
-        $this->setMustUseTerms('espresso_event_type', $term_details);
174
-    }
175
-
176
-
177
-    /**
178
-     * wrapper method for handling the setting up of initial terms in the db (if they don't already exist).
179
-     * Note this should ONLY be used for terms that always must be present.  Be aware that if an initial term is
180
-     * deleted then it WILL be recreated.
181
-     *
182
-     * @param string $taxonomy     The name of the taxonomy
183
-     * @param array  $term_details An array of term details indexed by slug and containing Name of term, and
184
-     *                             description as the elements in the array
185
-     * @return void
186
-     */
187
-    public function setMustUseTerms($taxonomy, $term_details)
188
-    {
189
-        $term_details = (array) $term_details;
190
-        foreach ($term_details as $slug => $details) {
191
-            if (isset($details['term'], $details['desc']) && ! term_exists($slug, $taxonomy)) {
192
-                $insert_arr = array(
193
-                    'slug'        => $slug,
194
-                    'description' => $details['desc'],
195
-                );
196
-                wp_insert_term($details['term'], $taxonomy, $insert_arr);
197
-            }
198
-        }
199
-    }
23
+	/**
24
+	 * @var array[] $custom_taxonomy_terms
25
+	 */
26
+	public $custom_taxonomy_terms = array();
27
+
28
+
29
+	/**
30
+	 * RegisterCustomTaxonomyTerms constructor.
31
+	 */
32
+	public function __construct()
33
+	{
34
+		// hook into save_post so that we can make sure that the default terms get saved on publish of registered cpts
35
+		// IF they don't have a term for that taxonomy set.
36
+		add_action('save_post', array($this, 'saveDefaultTerm'), 100, 2);
37
+		do_action(
38
+			'AHEE__EventEspresso_core_domain_services_custom_post_types_RegisterCustomTaxonomyTerms__construct_end',
39
+			$this
40
+		);
41
+	}
42
+
43
+
44
+	public function registerCustomTaxonomyTerms()
45
+	{
46
+		// setup default terms in any of our taxonomies (but only if we're in admin).
47
+		// Why not added via register_activation_hook?
48
+		// Because it's possible that in future iterations of EE we may add new defaults for specialized taxonomies
49
+		// (think event_types) and register_activation_hook only reliably runs when a user manually activates the plugin.
50
+		// Keep in mind that this will READ these terms if they are deleted by the user.  Hence MUST use terms.
51
+		// if ( is_admin() ) {
52
+		// 	$this->set_must_use_event_types();
53
+		// }
54
+		//set default terms
55
+		$this->registerCustomTaxonomyTerm(
56
+			'espresso_event_type',
57
+			'single-event',
58
+			array('espresso_events')
59
+		);
60
+	}
61
+
62
+
63
+	/**
64
+	 * Allows us to set what the default will be for terms when a cpt is PUBLISHED.
65
+	 *
66
+	 * @param string $taxonomy  The taxonomy we're using for the default term
67
+	 * @param string $term_slug The slug of the term that will be the default.
68
+	 * @param array  $cpt_slugs An array of custom post types we want the default assigned to
69
+	 */
70
+	public function registerCustomTaxonomyTerm($taxonomy, $term_slug, array $cpt_slugs = array())
71
+	{
72
+		$this->custom_taxonomy_terms[][ $term_slug ] = new CustomTaxonomyTerm(
73
+			$taxonomy,
74
+			$term_slug,
75
+			$cpt_slugs
76
+		);
77
+	}
78
+
79
+
80
+	/**
81
+	 * hooked into the wp 'save_post' action hook for setting our default terms found in the $_default_terms property
82
+	 *
83
+	 * @param  int    $post_id ID of CPT being saved
84
+	 * @param  WP_Post $post    Post object
85
+	 * @return void
86
+	 */
87
+	public function saveDefaultTerm($post_id, WP_Post $post)
88
+	{
89
+		if (empty($this->custom_taxonomy_terms)) {
90
+			return;
91
+		}
92
+		//no default terms set so lets just exit.
93
+		foreach ($this->custom_taxonomy_terms as $custom_taxonomy_terms) {
94
+			foreach ($custom_taxonomy_terms as $custom_taxonomy_term) {
95
+				if (
96
+					$post->post_status === 'publish'
97
+					&& $custom_taxonomy_term instanceof CustomTaxonomyTerm
98
+					&& in_array($post->post_type, $custom_taxonomy_term->customPostTypeSlugs(), true)
99
+				) {
100
+					//note some error proofing going on here to save unnecessary db queries
101
+					$taxonomies = get_object_taxonomies($post->post_type);
102
+					foreach ($taxonomies as $taxonomy) {
103
+						$terms = wp_get_post_terms($post_id, $taxonomy);
104
+						if (empty($terms) && $taxonomy === $custom_taxonomy_term->taxonomySlug()) {
105
+							wp_set_object_terms(
106
+								$post_id,
107
+								array($custom_taxonomy_term->termSlug()),
108
+								$taxonomy
109
+							);
110
+						}
111
+					}
112
+				}
113
+			}
114
+		}
115
+	}
116
+
117
+
118
+	/**
119
+	 * @return void
120
+	 */
121
+	public function setMustUseEventTypes()
122
+	{
123
+		$term_details = array(
124
+			//Attendee's register for the first date-time only
125
+			'single-event'    => array(
126
+				'term' => esc_html__('Single Event', 'event_espresso'),
127
+				'desc' => esc_html__(
128
+					'A single event that spans one or more consecutive days.',
129
+					'event_espresso'
130
+				),
131
+			),
132
+			//example: a party or two-day long workshop
133
+			//Attendee's can register for any of the date-times
134
+			'multi-event'     => array(
135
+				'term' => esc_html__('Multi Event', 'event_espresso'),
136
+				'desc' => esc_html__(
137
+					'Multiple, separate, but related events that occur on consecutive days.',
138
+					'event_espresso'
139
+				),
140
+			),
141
+			//example: a three day music festival or week long conference
142
+			//Attendee's register for the first date-time only
143
+			'event-series'    => array(
144
+				'term' => esc_html__('Event Series', 'event_espresso'),
145
+				'desc' => esc_html__(
146
+					' Multiple events that occur over multiple non-consecutive days.',
147
+					'event_espresso'
148
+				),
149
+			),
150
+			//example: an 8 week introduction to basket weaving course
151
+			//Attendee's can register for any of the date-times.
152
+			'recurring-event' => array(
153
+				'term' => esc_html__('Recurring Event', 'event_espresso'),
154
+				'desc' => esc_html__(
155
+					'Multiple events that occur over multiple non-consecutive days.',
156
+					'event_espresso'
157
+				),
158
+			),
159
+			//example: a yoga class
160
+			'ongoing'         => array(
161
+				'term' => esc_html__('Ongoing Event', 'event_espresso'),
162
+				'desc' => esc_html__(
163
+					'An "event" that people can purchase tickets to gain access for anytime for this event regardless of date times on the event',
164
+					'event_espresso'
165
+				),
166
+			)
167
+			//example: access to a museum
168
+			//'walk-in' => array( esc_html__('Walk In', 'event_espresso'), esc_html__('Single datetime and single entry recurring events. Attendees register for one or multiple datetimes individually.', 'event_espresso') ),
169
+			//'reservation' => array( esc_html__('Reservation', 'event_espresso'), esc_html__('Reservations are created by specifying available datetimes and quantities. Attendees choose from the available datetimes and specify the quantity available (if the maximum is greater than 1)') ), //@TODO to avoid confusion we'll implement this in a later iteration > EE4.1
170
+			// 'multiple-session' => array( esc_html__('Multiple Session', 'event_espresso'), esc_html__('Multiple event, multiple datetime, hierarchically organized, custom entry events. Attendees may be required to register for a parent event before being allowed to register for child events. Attendees can register for any combination of child events as long as the datetimes do not conflict. Parent and child events may have additional fees or registration questions.') ), //@TODO to avoid confusion we'll implement this in a later iteration > EE4.1
171
+			//'appointment' => array( esc_html__('Appointments', 'event_espresso'), esc_html__('Time slotted events where datetimes are generally in hours or minutes. For example, attendees can register for a single 15 minute or 1 hour time slot and this type of availability frequently reoccurs.', 'event_espresso') )
172
+		);
173
+		$this->setMustUseTerms('espresso_event_type', $term_details);
174
+	}
175
+
176
+
177
+	/**
178
+	 * wrapper method for handling the setting up of initial terms in the db (if they don't already exist).
179
+	 * Note this should ONLY be used for terms that always must be present.  Be aware that if an initial term is
180
+	 * deleted then it WILL be recreated.
181
+	 *
182
+	 * @param string $taxonomy     The name of the taxonomy
183
+	 * @param array  $term_details An array of term details indexed by slug and containing Name of term, and
184
+	 *                             description as the elements in the array
185
+	 * @return void
186
+	 */
187
+	public function setMustUseTerms($taxonomy, $term_details)
188
+	{
189
+		$term_details = (array) $term_details;
190
+		foreach ($term_details as $slug => $details) {
191
+			if (isset($details['term'], $details['desc']) && ! term_exists($slug, $taxonomy)) {
192
+				$insert_arr = array(
193
+					'slug'        => $slug,
194
+					'description' => $details['desc'],
195
+				);
196
+				wp_insert_term($details['term'], $taxonomy, $insert_arr);
197
+			}
198
+		}
199
+	}
200 200
 
201 201
 }
Please login to merge, or discard this patch.
core/domain/entities/custom_post_types/CustomTaxonomyTerm.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -17,60 +17,60 @@
 block discarded – undo
17 17
 class CustomTaxonomyTerm
18 18
 {
19 19
 
20
-    /**
21
-     * @var string $taxonomy_slug
22
-     */
23
-    public $taxonomy_slug;
24
-
25
-    /**
26
-     * @var string $term_slug
27
-     */
28
-    public $term_slug;
29
-
30
-    /**
31
-     * @var array $custom_post_type_slugs
32
-     */
33
-    public $custom_post_type_slugs;
34
-
35
-
36
-    /**
37
-     * CustomTaxonomyTerm constructor.
38
-     *
39
-     * @param string $taxonomy_slug
40
-     * @param string $term_slug
41
-     * @param array  $custom_post_type_slugs
42
-     */
43
-    public function __construct($taxonomy_slug, $term_slug, array $custom_post_type_slugs = array())
44
-    {
45
-        $this->taxonomy_slug          = $taxonomy_slug;
46
-        $this->term_slug              = $term_slug;
47
-        $this->custom_post_type_slugs = $custom_post_type_slugs;
48
-    }
49
-
50
-
51
-    /**
52
-     * @return string
53
-     */
54
-    public function taxonomySlug()
55
-    {
56
-        return $this->taxonomy_slug;
57
-    }
58
-
59
-
60
-    /**
61
-     * @return string
62
-     */
63
-    public function termSlug()
64
-    {
65
-        return $this->term_slug;
66
-    }
67
-
68
-
69
-    /**
70
-     * @return array
71
-     */
72
-    public function customPostTypeSlugs()
73
-    {
74
-        return $this->custom_post_type_slugs;
75
-    }
20
+	/**
21
+	 * @var string $taxonomy_slug
22
+	 */
23
+	public $taxonomy_slug;
24
+
25
+	/**
26
+	 * @var string $term_slug
27
+	 */
28
+	public $term_slug;
29
+
30
+	/**
31
+	 * @var array $custom_post_type_slugs
32
+	 */
33
+	public $custom_post_type_slugs;
34
+
35
+
36
+	/**
37
+	 * CustomTaxonomyTerm constructor.
38
+	 *
39
+	 * @param string $taxonomy_slug
40
+	 * @param string $term_slug
41
+	 * @param array  $custom_post_type_slugs
42
+	 */
43
+	public function __construct($taxonomy_slug, $term_slug, array $custom_post_type_slugs = array())
44
+	{
45
+		$this->taxonomy_slug          = $taxonomy_slug;
46
+		$this->term_slug              = $term_slug;
47
+		$this->custom_post_type_slugs = $custom_post_type_slugs;
48
+	}
49
+
50
+
51
+	/**
52
+	 * @return string
53
+	 */
54
+	public function taxonomySlug()
55
+	{
56
+		return $this->taxonomy_slug;
57
+	}
58
+
59
+
60
+	/**
61
+	 * @return string
62
+	 */
63
+	public function termSlug()
64
+	{
65
+		return $this->term_slug;
66
+	}
67
+
68
+
69
+	/**
70
+	 * @return array
71
+	 */
72
+	public function customPostTypeSlugs()
73
+	{
74
+		return $this->custom_post_type_slugs;
75
+	}
76 76
 }
Please login to merge, or discard this patch.
core/domain/entities/custom_post_types/CustomTaxonomyDefinitions.php 1 patch
Indentation   +126 added lines, -126 removed lines patch added patch discarded remove patch
@@ -17,130 +17,130 @@
 block discarded – undo
17 17
 class CustomTaxonomyDefinitions
18 18
 {
19 19
 
20
-    /**
21
-     * @var array $taxonomies
22
-     */
23
-    private $taxonomies;
24
-
25
-
26
-    /**
27
-     * EspressoCustomPostTypeDefinitions constructor.
28
-     */
29
-    public function __construct()
30
-    {
31
-        $this->setTaxonomies();
32
-        add_filter('pre_term_description', array($this, 'filterCustomTermDescription'), 1, 2);
33
-    }
34
-
35
-
36
-    private function setTaxonomies()
37
-    {
38
-        $this->taxonomies = array(
39
-            'espresso_event_categories' => array(
40
-                'singular_name' => esc_html__('Event Category', 'event_espresso'),
41
-                'plural_name'   => esc_html__('Event Categories', 'event_espresso'),
42
-                'args'          => array(
43
-                    'public'            => true,
44
-                    'show_in_nav_menus' => true,
45
-                    'show_in_rest'      => true,
46
-                    'capabilities'      => array(
47
-                        'manage_terms' => 'ee_manage_event_categories',
48
-                        'edit_terms'   => 'ee_edit_event_category',
49
-                        'delete_terms' => 'ee_delete_event_category',
50
-                        'assign_terms' => 'ee_assign_event_category',
51
-                    ),
52
-                    'rewrite'           => array('slug' => esc_html__('event-category', 'event_espresso')),
53
-                ),
54
-            ),
55
-            'espresso_venue_categories' => array(
56
-                'singular_name' => esc_html__('Venue Category', 'event_espresso'),
57
-                'plural_name'   => esc_html__('Venue Categories', 'event_espresso'),
58
-                'args'          => array(
59
-                    'public'            => true,
60
-                    'show_in_nav_menus' => false, //by default this doesn't show for decaf
61
-                    'show_in_rest'      => true,
62
-                    'capabilities'      => array(
63
-                        'manage_terms' => 'ee_manage_venue_categories',
64
-                        'edit_terms'   => 'ee_edit_venue_category',
65
-                        'delete_terms' => 'ee_delete_venue_category',
66
-                        'assign_terms' => 'ee_assign_venue_category',
67
-                    ),
68
-                    'rewrite'           => array('slug' => esc_html__('venue-category', 'event_espresso')),
69
-                ),
70
-            ),
71
-            'espresso_event_type'       => array(
72
-                'singular_name' => esc_html__('Event Type', 'event_espresso'),
73
-                'plural_name'   => esc_html__('Event Types', 'event_espresso'),
74
-                'args'          => array(
75
-                    'public'       => true,
76
-                    'show_ui'      => false,
77
-                    'show_in_rest' => true,
78
-                    'capabilities' => array(
79
-                        'manage_terms' => 'ee_read_event_type',
80
-                        'edit_terms'   => 'ee_edit_event_type',
81
-                        'delete_terms' => 'ee_delete_event_type',
82
-                        'assign_terms' => 'ee_assign_event_type',
83
-                    ),
84
-                    'rewrite'      => array('slug' => esc_html__('event-type', 'event_espresso')),
85
-                    'hierarchical' => true,
86
-                ),
87
-            ),
88
-        );
89
-    }
90
-
91
-
92
-    /**
93
-     * @return array
94
-     */
95
-    public function getCustomTaxonomyDefinitions()
96
-    {
97
-        return (array) apply_filters(
98
-            'FHEE__EventEspresso_core_domain_entities_custom_post_types_TaxonomyDefinitions__getTaxonomies',
99
-            // legacy filter applied for now,
100
-            // later on we'll run a has_filter($tag) check and throw a doing_it_wrong() notice
101
-            apply_filters(
102
-                'FHEE__EE_Register_CPTs__get_taxonomies__taxonomies',
103
-                $this->taxonomies
104
-            )
105
-        );
106
-    }
107
-
108
-
109
-    /**
110
-     * @return array
111
-     */
112
-    public function getCustomTaxonomySlugs()
113
-    {
114
-        return array_keys($this->getCustomTaxonomyDefinitions());
115
-    }
116
-
117
-
118
-    /**
119
-     * By default, WordPress strips all html from term taxonomy description content.
120
-     * The purpose of this method is to remove that restriction
121
-     * and ensure that we still run ee term taxonomy descriptions
122
-     * through some full html sanitization equivalent to the post content field.
123
-     * So first we remove default filter for term description
124
-     * but we have to do this earlier before wp sets their own filter
125
-     * because they just set a global filter on all term descriptions
126
-     * before the custom term description filter.
127
-     * Really sux.
128
-     *
129
-     * @param string $description The description content.
130
-     * @param string $taxonomy    The taxonomy name for the taxonomy being filtered.
131
-     * @return string
132
-     */
133
-    public function filterCustomTermDescription($description, $taxonomy)
134
-    {
135
-        //get a list of EE taxonomies
136
-        $custom_taxonomies = $this->getCustomTaxonomySlugs();
137
-        //only do our own thing if the taxonomy listed is an ee taxonomy.
138
-        if (in_array($taxonomy, $custom_taxonomies, true)) {
139
-            //remove default wp filter
140
-            remove_filter('pre_term_description', 'wp_filter_kses');
141
-            //sanitize THIS content.
142
-            $description = wp_kses($description, wp_kses_allowed_html('post'));
143
-        }
144
-        return $description;
145
-    }
20
+	/**
21
+	 * @var array $taxonomies
22
+	 */
23
+	private $taxonomies;
24
+
25
+
26
+	/**
27
+	 * EspressoCustomPostTypeDefinitions constructor.
28
+	 */
29
+	public function __construct()
30
+	{
31
+		$this->setTaxonomies();
32
+		add_filter('pre_term_description', array($this, 'filterCustomTermDescription'), 1, 2);
33
+	}
34
+
35
+
36
+	private function setTaxonomies()
37
+	{
38
+		$this->taxonomies = array(
39
+			'espresso_event_categories' => array(
40
+				'singular_name' => esc_html__('Event Category', 'event_espresso'),
41
+				'plural_name'   => esc_html__('Event Categories', 'event_espresso'),
42
+				'args'          => array(
43
+					'public'            => true,
44
+					'show_in_nav_menus' => true,
45
+					'show_in_rest'      => true,
46
+					'capabilities'      => array(
47
+						'manage_terms' => 'ee_manage_event_categories',
48
+						'edit_terms'   => 'ee_edit_event_category',
49
+						'delete_terms' => 'ee_delete_event_category',
50
+						'assign_terms' => 'ee_assign_event_category',
51
+					),
52
+					'rewrite'           => array('slug' => esc_html__('event-category', 'event_espresso')),
53
+				),
54
+			),
55
+			'espresso_venue_categories' => array(
56
+				'singular_name' => esc_html__('Venue Category', 'event_espresso'),
57
+				'plural_name'   => esc_html__('Venue Categories', 'event_espresso'),
58
+				'args'          => array(
59
+					'public'            => true,
60
+					'show_in_nav_menus' => false, //by default this doesn't show for decaf
61
+					'show_in_rest'      => true,
62
+					'capabilities'      => array(
63
+						'manage_terms' => 'ee_manage_venue_categories',
64
+						'edit_terms'   => 'ee_edit_venue_category',
65
+						'delete_terms' => 'ee_delete_venue_category',
66
+						'assign_terms' => 'ee_assign_venue_category',
67
+					),
68
+					'rewrite'           => array('slug' => esc_html__('venue-category', 'event_espresso')),
69
+				),
70
+			),
71
+			'espresso_event_type'       => array(
72
+				'singular_name' => esc_html__('Event Type', 'event_espresso'),
73
+				'plural_name'   => esc_html__('Event Types', 'event_espresso'),
74
+				'args'          => array(
75
+					'public'       => true,
76
+					'show_ui'      => false,
77
+					'show_in_rest' => true,
78
+					'capabilities' => array(
79
+						'manage_terms' => 'ee_read_event_type',
80
+						'edit_terms'   => 'ee_edit_event_type',
81
+						'delete_terms' => 'ee_delete_event_type',
82
+						'assign_terms' => 'ee_assign_event_type',
83
+					),
84
+					'rewrite'      => array('slug' => esc_html__('event-type', 'event_espresso')),
85
+					'hierarchical' => true,
86
+				),
87
+			),
88
+		);
89
+	}
90
+
91
+
92
+	/**
93
+	 * @return array
94
+	 */
95
+	public function getCustomTaxonomyDefinitions()
96
+	{
97
+		return (array) apply_filters(
98
+			'FHEE__EventEspresso_core_domain_entities_custom_post_types_TaxonomyDefinitions__getTaxonomies',
99
+			// legacy filter applied for now,
100
+			// later on we'll run a has_filter($tag) check and throw a doing_it_wrong() notice
101
+			apply_filters(
102
+				'FHEE__EE_Register_CPTs__get_taxonomies__taxonomies',
103
+				$this->taxonomies
104
+			)
105
+		);
106
+	}
107
+
108
+
109
+	/**
110
+	 * @return array
111
+	 */
112
+	public function getCustomTaxonomySlugs()
113
+	{
114
+		return array_keys($this->getCustomTaxonomyDefinitions());
115
+	}
116
+
117
+
118
+	/**
119
+	 * By default, WordPress strips all html from term taxonomy description content.
120
+	 * The purpose of this method is to remove that restriction
121
+	 * and ensure that we still run ee term taxonomy descriptions
122
+	 * through some full html sanitization equivalent to the post content field.
123
+	 * So first we remove default filter for term description
124
+	 * but we have to do this earlier before wp sets their own filter
125
+	 * because they just set a global filter on all term descriptions
126
+	 * before the custom term description filter.
127
+	 * Really sux.
128
+	 *
129
+	 * @param string $description The description content.
130
+	 * @param string $taxonomy    The taxonomy name for the taxonomy being filtered.
131
+	 * @return string
132
+	 */
133
+	public function filterCustomTermDescription($description, $taxonomy)
134
+	{
135
+		//get a list of EE taxonomies
136
+		$custom_taxonomies = $this->getCustomTaxonomySlugs();
137
+		//only do our own thing if the taxonomy listed is an ee taxonomy.
138
+		if (in_array($taxonomy, $custom_taxonomies, true)) {
139
+			//remove default wp filter
140
+			remove_filter('pre_term_description', 'wp_filter_kses');
141
+			//sanitize THIS content.
142
+			$description = wp_kses($description, wp_kses_allowed_html('post'));
143
+		}
144
+		return $description;
145
+	}
146 146
 }
Please login to merge, or discard this patch.
caffeinated/admin/extend/events/Extend_Events_Admin_Page.core.php 2 patches
Indentation   +1268 added lines, -1268 removed lines patch added patch discarded remove patch
@@ -19,1272 +19,1272 @@
 block discarded – undo
19 19
 {
20 20
 
21 21
 
22
-    /**
23
-     * Extend_Events_Admin_Page constructor.
24
-     *
25
-     * @param bool $routing
26
-     */
27
-    public function __construct($routing = true)
28
-    {
29
-        parent::__construct($routing);
30
-        if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
31
-            define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
32
-            define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
33
-            define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
34
-        }
35
-    }
36
-
37
-
38
-    /**
39
-     * Sets routes.
40
-     */
41
-    protected function _extend_page_config()
42
-    {
43
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
44
-        //is there a evt_id in the request?
45
-        $evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
46
-            ? $this->_req_data['EVT_ID']
47
-            : 0;
48
-        $evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
49
-        //tkt_id?
50
-        $tkt_id             = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
51
-            ? $this->_req_data['TKT_ID']
52
-            : 0;
53
-        $new_page_routes    = array(
54
-            'duplicate_event'          => array(
55
-                'func'       => '_duplicate_event',
56
-                'capability' => 'ee_edit_event',
57
-                'obj_id'     => $evt_id,
58
-                'noheader'   => true,
59
-            ),
60
-            'ticket_list_table'        => array(
61
-                'func'       => '_tickets_overview_list_table',
62
-                'capability' => 'ee_read_default_tickets',
63
-            ),
64
-            'trash_ticket'             => array(
65
-                'func'       => '_trash_or_restore_ticket',
66
-                'capability' => 'ee_delete_default_ticket',
67
-                'obj_id'     => $tkt_id,
68
-                'noheader'   => true,
69
-                'args'       => array('trash' => true),
70
-            ),
71
-            'trash_tickets'            => array(
72
-                'func'       => '_trash_or_restore_ticket',
73
-                'capability' => 'ee_delete_default_tickets',
74
-                'noheader'   => true,
75
-                'args'       => array('trash' => true),
76
-            ),
77
-            'restore_ticket'           => array(
78
-                'func'       => '_trash_or_restore_ticket',
79
-                'capability' => 'ee_delete_default_ticket',
80
-                'obj_id'     => $tkt_id,
81
-                'noheader'   => true,
82
-            ),
83
-            'restore_tickets'          => array(
84
-                'func'       => '_trash_or_restore_ticket',
85
-                'capability' => 'ee_delete_default_tickets',
86
-                'noheader'   => true,
87
-            ),
88
-            'delete_ticket'            => array(
89
-                'func'       => '_delete_ticket',
90
-                'capability' => 'ee_delete_default_ticket',
91
-                'obj_id'     => $tkt_id,
92
-                'noheader'   => true,
93
-            ),
94
-            'delete_tickets'           => array(
95
-                'func'       => '_delete_ticket',
96
-                'capability' => 'ee_delete_default_tickets',
97
-                'noheader'   => true,
98
-            ),
99
-            'import_page'              => array(
100
-                'func'       => '_import_page',
101
-                'capability' => 'import',
102
-            ),
103
-            'import'                   => array(
104
-                'func'       => '_import_events',
105
-                'capability' => 'import',
106
-                'noheader'   => true,
107
-            ),
108
-            'import_events'            => array(
109
-                'func'       => '_import_events',
110
-                'capability' => 'import',
111
-                'noheader'   => true,
112
-            ),
113
-            'export_events'            => array(
114
-                'func'       => '_events_export',
115
-                'capability' => 'export',
116
-                'noheader'   => true,
117
-            ),
118
-            'export_categories'        => array(
119
-                'func'       => '_categories_export',
120
-                'capability' => 'export',
121
-                'noheader'   => true,
122
-            ),
123
-            'sample_export_file'       => array(
124
-                'func'       => '_sample_export_file',
125
-                'capability' => 'export',
126
-                'noheader'   => true,
127
-            ),
128
-            'update_template_settings' => array(
129
-                'func'       => '_update_template_settings',
130
-                'capability' => 'manage_options',
131
-                'noheader'   => true,
132
-            ),
133
-        );
134
-        $this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
135
-        //partial route/config override
136
-        $this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
137
-        $this->_page_config['create_new']['metaboxes'][]  = '_premium_event_editor_meta_boxes';
138
-        $this->_page_config['create_new']['qtips'][]      = 'EE_Event_Editor_Tips';
139
-        $this->_page_config['edit']['qtips'][]            = 'EE_Event_Editor_Tips';
140
-        $this->_page_config['edit']['metaboxes'][]        = '_premium_event_editor_meta_boxes';
141
-        $this->_page_config['default']['list_table']      = 'Extend_Events_Admin_List_Table';
142
-        //add tickets tab but only if there are more than one default ticket!
143
-        $tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
144
-            array(array('TKT_is_default' => 1)),
145
-            'TKT_ID',
146
-            true
147
-        );
148
-        if ($tkt_count > 1) {
149
-            $new_page_config = array(
150
-                'ticket_list_table' => array(
151
-                    'nav'           => array(
152
-                        'label' => esc_html__('Default Tickets', 'event_espresso'),
153
-                        'order' => 60,
154
-                    ),
155
-                    'list_table'    => 'Tickets_List_Table',
156
-                    'require_nonce' => false,
157
-                ),
158
-            );
159
-        }
160
-        //template settings
161
-        $new_page_config['template_settings'] = array(
162
-            'nav'           => array(
163
-                'label' => esc_html__('Templates', 'event_espresso'),
164
-                'order' => 30,
165
-            ),
166
-            'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
167
-            'help_tabs'     => array(
168
-                'general_settings_templates_help_tab' => array(
169
-                    'title'    => esc_html__('Templates', 'event_espresso'),
170
-                    'filename' => 'general_settings_templates',
171
-                ),
172
-            ),
173
-            'help_tour'     => array('Templates_Help_Tour'),
174
-            'require_nonce' => false,
175
-        );
176
-        $this->_page_config                   = array_merge($this->_page_config, $new_page_config);
177
-        //add filters and actions
178
-        //modifying _views
179
-        add_filter(
180
-            'FHEE_event_datetime_metabox_add_additional_date_time_template',
181
-            array($this, 'add_additional_datetime_button'),
182
-            10,
183
-            2
184
-        );
185
-        add_filter(
186
-            'FHEE_event_datetime_metabox_clone_button_template',
187
-            array($this, 'add_datetime_clone_button'),
188
-            10,
189
-            2
190
-        );
191
-        add_filter(
192
-            'FHEE_event_datetime_metabox_timezones_template',
193
-            array($this, 'datetime_timezones_template'),
194
-            10,
195
-            2
196
-        );
197
-        //filters for event list table
198
-        add_filter('FHEE__Extend_Events_Admin_List_Table__filters', array($this, 'list_table_filters'), 10, 2);
199
-        add_filter(
200
-            'FHEE__Events_Admin_List_Table__column_actions__action_links',
201
-            array($this, 'extra_list_table_actions'),
202
-            10,
203
-            2
204
-        );
205
-        //legend item
206
-        add_filter('FHEE__Events_Admin_Page___event_legend_items__items', array($this, 'additional_legend_items'));
207
-        add_action('admin_init', array($this, 'admin_init'));
208
-        //heartbeat stuff
209
-        add_filter('heartbeat_received', array($this, 'heartbeat_response'), 10, 2);
210
-    }
211
-
212
-
213
-    /**
214
-     * admin_init
215
-     */
216
-    public function admin_init()
217
-    {
218
-        EE_Registry::$i18n_js_strings = array_merge(
219
-            EE_Registry::$i18n_js_strings,
220
-            array(
221
-                'image_confirm'          => esc_html__(
222
-                    'Do you really want to delete this image? Please remember to update your event to complete the removal.',
223
-                    'event_espresso'
224
-                ),
225
-                'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
226
-                'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
227
-                'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
228
-                'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
229
-                'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
230
-            )
231
-        );
232
-    }
233
-
234
-
235
-    /**
236
-     * This will be used to listen for any heartbeat data packages coming via the WordPress heartbeat API and handle
237
-     * accordingly.
238
-     *
239
-     * @param array $response The existing heartbeat response array.
240
-     * @param array $data     The incoming data package.
241
-     * @return array  possibly appended response.
242
-     */
243
-    public function heartbeat_response($response, $data)
244
-    {
245
-        /**
246
-         * check whether count of tickets is approaching the potential
247
-         * limits for the server.
248
-         */
249
-        if (! empty($data['input_count'])) {
250
-            $response['max_input_vars_check'] = EE_Registry::instance()->CFG->environment->max_input_vars_limit_check(
251
-                $data['input_count']
252
-            );
253
-        }
254
-        return $response;
255
-    }
256
-
257
-
258
-    /**
259
-     * Add per page screen options to the default ticket list table view.
260
-     */
261
-    protected function _add_screen_options_ticket_list_table()
262
-    {
263
-        $this->_per_page_screen_option();
264
-    }
265
-
266
-
267
-    /**
268
-     * @param string $return
269
-     * @param int    $id
270
-     * @param string $new_title
271
-     * @param string $new_slug
272
-     * @return string
273
-     */
274
-    public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
275
-    {
276
-        $return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
277
-        //make sure this is only when editing
278
-        if (! empty($id)) {
279
-            $href   = EE_Admin_Page::add_query_args_and_nonce(
280
-                array('action' => 'duplicate_event', 'EVT_ID' => $id),
281
-                $this->_admin_base_url
282
-            );
283
-            $title  = esc_attr__('Duplicate Event', 'event_espresso');
284
-            $return .= '<a href="'
285
-                       . $href
286
-                       . '" title="'
287
-                       . $title
288
-                       . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
289
-                       . $title
290
-                       . '</a>';
291
-        }
292
-        return $return;
293
-    }
294
-
295
-
296
-    /**
297
-     * Set the list table views for the default ticket list table view.
298
-     */
299
-    public function _set_list_table_views_ticket_list_table()
300
-    {
301
-        $this->_views = array(
302
-            'all'     => array(
303
-                'slug'        => 'all',
304
-                'label'       => esc_html__('All', 'event_espresso'),
305
-                'count'       => 0,
306
-                'bulk_action' => array(
307
-                    'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
308
-                ),
309
-            ),
310
-            'trashed' => array(
311
-                'slug'        => 'trashed',
312
-                'label'       => esc_html__('Trash', 'event_espresso'),
313
-                'count'       => 0,
314
-                'bulk_action' => array(
315
-                    'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
316
-                    'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
317
-                ),
318
-            ),
319
-        );
320
-    }
321
-
322
-
323
-    /**
324
-     * Enqueue scripts and styles for the event editor.
325
-     */
326
-    public function load_scripts_styles_edit()
327
-    {
328
-        wp_register_script(
329
-            'ee-event-editor-heartbeat',
330
-            EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
331
-            array('ee_admin_js', 'heartbeat'),
332
-            EVENT_ESPRESSO_VERSION,
333
-            true
334
-        );
335
-        wp_enqueue_script('ee-accounting');
336
-        //styles
337
-        wp_enqueue_style('espresso-ui-theme');
338
-        wp_enqueue_script('event_editor_js');
339
-        wp_enqueue_script('ee-event-editor-heartbeat');
340
-    }
341
-
342
-
343
-    /**
344
-     * Returns template for the additional datetime.
345
-     * @param $template
346
-     * @param $template_args
347
-     * @return mixed
348
-     * @throws DomainException
349
-     */
350
-    public function add_additional_datetime_button($template, $template_args)
351
-    {
352
-        return EEH_Template::display_template(
353
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
354
-            $template_args,
355
-            true
356
-        );
357
-    }
358
-
359
-
360
-    /**
361
-     * Returns the template for cloning a datetime.
362
-     * @param $template
363
-     * @param $template_args
364
-     * @return mixed
365
-     * @throws DomainException
366
-     */
367
-    public function add_datetime_clone_button($template, $template_args)
368
-    {
369
-        return EEH_Template::display_template(
370
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
371
-            $template_args,
372
-            true
373
-        );
374
-    }
375
-
376
-
377
-    /**
378
-     * Returns the template for datetime timezones.
379
-     * @param $template
380
-     * @param $template_args
381
-     * @return mixed
382
-     * @throws DomainException
383
-     */
384
-    public function datetime_timezones_template($template, $template_args)
385
-    {
386
-        return EEH_Template::display_template(
387
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
388
-            $template_args,
389
-            true
390
-        );
391
-    }
392
-
393
-
394
-    /**
395
-     * Sets the views for the default list table view.
396
-     */
397
-    protected function _set_list_table_views_default()
398
-    {
399
-        parent::_set_list_table_views_default();
400
-        $new_views    = array(
401
-            'today' => array(
402
-                'slug'        => 'today',
403
-                'label'       => esc_html__('Today', 'event_espresso'),
404
-                'count'       => $this->total_events_today(),
405
-                'bulk_action' => array(
406
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
407
-                ),
408
-            ),
409
-            'month' => array(
410
-                'slug'        => 'month',
411
-                'label'       => esc_html__('This Month', 'event_espresso'),
412
-                'count'       => $this->total_events_this_month(),
413
-                'bulk_action' => array(
414
-                    'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
415
-                ),
416
-            ),
417
-        );
418
-        $this->_views = array_merge($this->_views, $new_views);
419
-    }
420
-
421
-
422
-    /**
423
-     * Returns the extra action links for the default list table view.
424
-     * @param array     $action_links
425
-     * @param \EE_Event $event
426
-     * @return array
427
-     * @throws EE_Error
428
-     */
429
-    public function extra_list_table_actions(array $action_links, \EE_Event $event)
430
-    {
431
-        if (EE_Registry::instance()->CAP->current_user_can(
432
-            'ee_read_registrations',
433
-            'espresso_registrations_reports',
434
-            $event->ID()
435
-        )
436
-        ) {
437
-            $reports_query_args = array(
438
-                'action' => 'reports',
439
-                'EVT_ID' => $event->ID(),
440
-            );
441
-            $reports_link       = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
442
-            $action_links[]     = '<a href="'
443
-                                  . $reports_link
444
-                                  . '" title="'
445
-                                  . esc_attr__('View Report', 'event_espresso')
446
-                                  . '"><div class="dashicons dashicons-chart-bar"></div></a>'
447
-                                  . "\n\t";
448
-        }
449
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
450
-            EE_Registry::instance()->load_helper('MSG_Template');
451
-            $action_links[] = EEH_MSG_Template::get_message_action_link(
452
-                'see_notifications_for',
453
-                null,
454
-                array('EVT_ID' => $event->ID())
455
-            );
456
-        }
457
-        return $action_links;
458
-    }
459
-
460
-
461
-    /**
462
-     * @param $items
463
-     * @return mixed
464
-     */
465
-    public function additional_legend_items($items)
466
-    {
467
-        if (EE_Registry::instance()->CAP->current_user_can(
468
-            'ee_read_registrations',
469
-            'espresso_registrations_reports'
470
-        )
471
-        ) {
472
-            $items['reports'] = array(
473
-                'class' => 'dashicons dashicons-chart-bar',
474
-                'desc'  => esc_html__('Event Reports', 'event_espresso'),
475
-            );
476
-        }
477
-        if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
478
-            $related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
479
-            if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
480
-                $items['view_related_messages'] = array(
481
-                    'class' => $related_for_icon['css_class'],
482
-                    'desc'  => $related_for_icon['label'],
483
-                );
484
-            }
485
-        }
486
-        return $items;
487
-    }
488
-
489
-
490
-    /**
491
-     * This is the callback method for the duplicate event route
492
-     * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
493
-     * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
494
-     * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
495
-     * After duplication the redirect is to the new event edit page.
496
-     *
497
-     * @return void
498
-     * @access protected
499
-     * @throws EE_Error If EE_Event is not available with given ID
500
-     */
501
-    protected function _duplicate_event()
502
-    {
503
-        // first make sure the ID for the event is in the request.
504
-        //  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
505
-        if (! isset($this->_req_data['EVT_ID'])) {
506
-            EE_Error::add_error(
507
-                esc_html__(
508
-                    'In order to duplicate an event an Event ID is required.  None was given.',
509
-                    'event_espresso'
510
-                ),
511
-                __FILE__,
512
-                __FUNCTION__,
513
-                __LINE__
514
-            );
515
-            $this->_redirect_after_action(false, '', '', array(), true);
516
-            return;
517
-        }
518
-        //k we've got EVT_ID so let's use that to get the event we'll duplicate
519
-        $orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
520
-        if (! $orig_event instanceof EE_Event) {
521
-            throw new EE_Error(
522
-                sprintf(
523
-                    esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
524
-                    $this->_req_data['EVT_ID']
525
-                )
526
-            );
527
-        }
528
-        //k now let's clone the $orig_event before getting relations
529
-        $new_event = clone $orig_event;
530
-        //original datetimes
531
-        $orig_datetimes = $orig_event->get_many_related('Datetime');
532
-        //other original relations
533
-        $orig_ven = $orig_event->get_many_related('Venue');
534
-        //reset the ID and modify other details to make it clear this is a dupe
535
-        $new_event->set('EVT_ID', 0);
536
-        $new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
537
-        $new_event->set('EVT_name', $new_name);
538
-        $new_event->set(
539
-            'EVT_slug',
540
-            wp_unique_post_slug(
541
-                sanitize_title($orig_event->name()),
542
-                0,
543
-                'publish',
544
-                'espresso_events',
545
-                0
546
-            )
547
-        );
548
-        $new_event->set('status', 'draft');
549
-        //duplicate discussion settings
550
-        $new_event->set('comment_status', $orig_event->get('comment_status'));
551
-        $new_event->set('ping_status', $orig_event->get('ping_status'));
552
-        //save the new event
553
-        $new_event->save();
554
-        //venues
555
-        foreach ($orig_ven as $ven) {
556
-            $new_event->_add_relation_to($ven, 'Venue');
557
-        }
558
-        $new_event->save();
559
-        //now we need to get the question group relations and handle that
560
-        //first primary question groups
561
-        $orig_primary_qgs = $orig_event->get_many_related(
562
-            'Question_Group',
563
-            array(array('Event_Question_Group.EQG_primary' => 1))
564
-        );
565
-        if (! empty($orig_primary_qgs)) {
566
-            foreach ($orig_primary_qgs as $id => $obj) {
567
-                if ($obj instanceof EE_Question_Group) {
568
-                    $new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 1));
569
-                }
570
-            }
571
-        }
572
-        //next additional attendee question groups
573
-        $orig_additional_qgs = $orig_event->get_many_related(
574
-            'Question_Group',
575
-            array(array('Event_Question_Group.EQG_primary' => 0))
576
-        );
577
-        if (! empty($orig_additional_qgs)) {
578
-            foreach ($orig_additional_qgs as $id => $obj) {
579
-                if ($obj instanceof EE_Question_Group) {
580
-                    $new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 0));
581
-                }
582
-            }
583
-        }
584
-
585
-        $new_event->save();
586
-
587
-        //k now that we have the new event saved we can loop through the datetimes and start adding relations.
588
-        $cloned_tickets = array();
589
-        foreach ($orig_datetimes as $orig_dtt) {
590
-            if (! $orig_dtt instanceof EE_Datetime) {
591
-                continue;
592
-            }
593
-            $new_dtt   = clone $orig_dtt;
594
-            $orig_tkts = $orig_dtt->tickets();
595
-            //save new dtt then add to event
596
-            $new_dtt->set('DTT_ID', 0);
597
-            $new_dtt->set('DTT_sold', 0);
598
-            $new_dtt->set_reserved(0);
599
-            $new_dtt->save();
600
-            $new_event->_add_relation_to($new_dtt, 'Datetime');
601
-            $new_event->save();
602
-            //now let's get the ticket relations setup.
603
-            foreach ((array)$orig_tkts as $orig_tkt) {
604
-                //it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
605
-                if (! $orig_tkt instanceof EE_Ticket) {
606
-                    continue;
607
-                }
608
-                //is this ticket archived?  If it is then let's skip
609
-                if ($orig_tkt->get('TKT_deleted')) {
610
-                    continue;
611
-                }
612
-                // does this original ticket already exist in the clone_tickets cache?
613
-                //  If so we'll just use the new ticket from it.
614
-                if (isset($cloned_tickets[$orig_tkt->ID()])) {
615
-                    $new_tkt = $cloned_tickets[$orig_tkt->ID()];
616
-                } else {
617
-                    $new_tkt = clone $orig_tkt;
618
-                    //get relations on the $orig_tkt that we need to setup.
619
-                    $orig_prices = $orig_tkt->prices();
620
-                    $new_tkt->set('TKT_ID', 0);
621
-                    $new_tkt->set('TKT_sold', 0);
622
-                    $new_tkt->set('TKT_reserved', 0);
623
-                    $new_tkt->save(); //make sure new ticket has ID.
624
-                    //price relations on new ticket need to be setup.
625
-                    foreach ($orig_prices as $orig_price) {
626
-                        $new_price = clone $orig_price;
627
-                        $new_price->set('PRC_ID', 0);
628
-                        $new_price->save();
629
-                        $new_tkt->_add_relation_to($new_price, 'Price');
630
-                        $new_tkt->save();
631
-                    }
632
-
633
-                    do_action(
634
-                        'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
635
-                        $orig_tkt,
636
-                        $new_tkt,
637
-                        $orig_prices,
638
-                        $orig_event,
639
-                        $orig_dtt,
640
-                        $new_dtt
641
-                    );
642
-                }
643
-                // k now we can add the new ticket as a relation to the new datetime
644
-                // and make sure its added to our cached $cloned_tickets array
645
-                // for use with later datetimes that have the same ticket.
646
-                $new_dtt->_add_relation_to($new_tkt, 'Ticket');
647
-                $new_dtt->save();
648
-                $cloned_tickets[$orig_tkt->ID()] = $new_tkt;
649
-            }
650
-        }
651
-        //clone taxonomy information
652
-        $taxonomies_to_clone_with = apply_filters(
653
-            'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
654
-            array('espresso_event_categories', 'espresso_event_type', 'post_tag')
655
-        );
656
-        //get terms for original event (notice)
657
-        $orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
658
-        //loop through terms and add them to new event.
659
-        foreach ($orig_terms as $term) {
660
-            wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
661
-        }
662
-
663
-        //duplicate other core WP_Post items for this event.
664
-        //post thumbnail (feature image).
665
-        $feature_image_id = get_post_thumbnail_id($orig_event->ID());
666
-        if ($feature_image_id) {
667
-            update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
668
-        }
669
-
670
-        //duplicate page_template setting
671
-        $page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
672
-        if ($page_template) {
673
-            update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
674
-        }
675
-
676
-        do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
677
-        //now let's redirect to the edit page for this duplicated event if we have a new event id.
678
-        if ($new_event->ID()) {
679
-            $redirect_args = array(
680
-                'post'   => $new_event->ID(),
681
-                'action' => 'edit',
682
-            );
683
-            EE_Error::add_success(
684
-                esc_html__(
685
-                    'Event successfully duplicated.  Please review the details below and make any necessary edits',
686
-                    'event_espresso'
687
-                )
688
-            );
689
-        } else {
690
-            $redirect_args = array(
691
-                'action' => 'default',
692
-            );
693
-            EE_Error::add_error(
694
-                esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
695
-                __FILE__,
696
-                __FUNCTION__,
697
-                __LINE__
698
-            );
699
-        }
700
-        $this->_redirect_after_action(false, '', '', $redirect_args, true);
701
-    }
702
-
703
-
704
-    /**
705
-     * Generates output for the import page.
706
-     * @throws DomainException
707
-     */
708
-    protected function _import_page()
709
-    {
710
-        $title                                      = esc_html__('Import', 'event_espresso');
711
-        $intro                                      = esc_html__(
712
-            'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
713
-            'event_espresso'
714
-        );
715
-        $form_url                                   = EVENTS_ADMIN_URL;
716
-        $action                                     = 'import_events';
717
-        $type                                       = 'csv';
718
-        $this->_template_args['form']               = EE_Import::instance()->upload_form(
719
-            $title, $intro, $form_url, $action, $type
720
-        );
721
-        $this->_template_args['sample_file_link']   = EE_Admin_Page::add_query_args_and_nonce(
722
-            array('action' => 'sample_export_file'),
723
-            $this->_admin_base_url
724
-        );
725
-        $content                                    = EEH_Template::display_template(
726
-            EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
727
-            $this->_template_args,
728
-            true
729
-        );
730
-        $this->_template_args['admin_page_content'] = $content;
731
-        $this->display_admin_page_with_sidebar();
732
-    }
733
-
734
-
735
-    /**
736
-     * _import_events
737
-     * This handles displaying the screen and running imports for importing events.
738
-     *
739
-     * @return void
740
-     */
741
-    protected function _import_events()
742
-    {
743
-        require_once(EE_CLASSES . 'EE_Import.class.php');
744
-        $success = EE_Import::instance()->import();
745
-        $this->_redirect_after_action($success, 'Import File', 'ran', array('action' => 'import_page'), true);
746
-    }
747
-
748
-
749
-    /**
750
-     * _events_export
751
-     * Will export all (or just the given event) to a Excel compatible file.
752
-     *
753
-     * @access protected
754
-     * @return void
755
-     */
756
-    protected function _events_export()
757
-    {
758
-        if (isset($this->_req_data['EVT_ID'])) {
759
-            $event_ids = $this->_req_data['EVT_ID'];
760
-        } elseif (isset($this->_req_data['EVT_IDs'])) {
761
-            $event_ids = $this->_req_data['EVT_IDs'];
762
-        } else {
763
-            $event_ids = null;
764
-        }
765
-        //todo: I don't like doing this but it'll do until we modify EE_Export Class.
766
-        $new_request_args = array(
767
-            'export' => 'report',
768
-            'action' => 'all_event_data',
769
-            'EVT_ID' => $event_ids,
770
-        );
771
-        $this->_req_data  = array_merge($this->_req_data, $new_request_args);
772
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
773
-            require_once(EE_CLASSES . 'EE_Export.class.php');
774
-            $EE_Export = EE_Export::instance($this->_req_data);
775
-            $EE_Export->export();
776
-        }
777
-    }
778
-
779
-
780
-    /**
781
-     * handle category exports()
782
-     *
783
-     * @return void
784
-     */
785
-    protected function _categories_export()
786
-    {
787
-        //todo: I don't like doing this but it'll do until we modify EE_Export Class.
788
-        $new_request_args = array(
789
-            'export'       => 'report',
790
-            'action'       => 'categories',
791
-            'category_ids' => $this->_req_data['EVT_CAT_ID'],
792
-        );
793
-        $this->_req_data  = array_merge($this->_req_data, $new_request_args);
794
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
795
-            require_once(EE_CLASSES . 'EE_Export.class.php');
796
-            $EE_Export = EE_Export::instance($this->_req_data);
797
-            $EE_Export->export();
798
-        }
799
-    }
800
-
801
-
802
-    /**
803
-     * Creates a sample CSV file for importing
804
-     */
805
-    protected function _sample_export_file()
806
-    {
807
-        //		require_once(EE_CLASSES . 'EE_Export.class.php');
808
-        EE_Export::instance()->export_sample();
809
-    }
810
-
811
-
812
-    /*************        Template Settings        *************/
813
-    /**
814
-     * Generates template settings page output
815
-     * @throws DomainException
816
-     * @throws EE_Error
817
-     */
818
-    protected function _template_settings()
819
-    {
820
-        $this->_template_args['values'] = $this->_yes_no_values;
821
-        /**
822
-         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
823
-         * from General_Settings_Admin_Page to here.
824
-         */
825
-        $this->_template_args = apply_filters(
826
-            'FHEE__General_Settings_Admin_Page__template_settings__template_args',
827
-            $this->_template_args
828
-        );
829
-        $this->_set_add_edit_form_tags('update_template_settings');
830
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
831
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
832
-            EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
833
-            $this->_template_args,
834
-            true
835
-        );
836
-        $this->display_admin_page_with_sidebar();
837
-    }
838
-
839
-
840
-    /**
841
-     * Handler for updating template settings.
842
-     *
843
-     * @throws InvalidInterfaceException
844
-     * @throws InvalidDataTypeException
845
-     * @throws InvalidArgumentException
846
-     */
847
-    protected function _update_template_settings()
848
-    {
849
-        /**
850
-         * Note leaving this filter in for backward compatibility this was moved in 4.6.x
851
-         * from General_Settings_Admin_Page to here.
852
-         */
853
-        EE_Registry::instance()->CFG->template_settings = apply_filters(
854
-            'FHEE__General_Settings_Admin_Page__update_template_settings__data',
855
-            EE_Registry::instance()->CFG->template_settings,
856
-            $this->_req_data
857
-        );
858
-        //update custom post type slugs and detect if we need to flush rewrite rules
859
-        $old_slug                                          = EE_Registry::instance()->CFG->core->event_cpt_slug;
860
-        EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
861
-            ? EE_Registry::instance()->CFG->core->event_cpt_slug
862
-            : sanitize_title_with_dashes($this->_req_data['event_cpt_slug']);
863
-        $what                                              = 'Template Settings';
864
-        $success                                           = $this->_update_espresso_configuration(
865
-            $what,
866
-            EE_Registry::instance()->CFG->template_settings,
867
-            __FILE__,
868
-            __FUNCTION__,
869
-            __LINE__
870
-        );
871
-        if (EE_Registry::instance()->CFG->core->event_cpt_slug != $old_slug) {
872
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
873
-            $rewrite_rules =  LoaderFactory::getLoader()->getShared(
874
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
875
-            );
876
-            $rewrite_rules->flush();
877
-        }
878
-        $this->_redirect_after_action($success, $what, 'updated', array('action' => 'template_settings'));
879
-    }
880
-
881
-
882
-    /**
883
-     * _premium_event_editor_meta_boxes
884
-     * add all metaboxes related to the event_editor
885
-     *
886
-     * @access protected
887
-     * @return void
888
-     * @throws EE_Error
889
-     */
890
-    protected function _premium_event_editor_meta_boxes()
891
-    {
892
-        $this->verify_cpt_object();
893
-        add_meta_box(
894
-            'espresso_event_editor_event_options',
895
-            esc_html__('Event Registration Options', 'event_espresso'),
896
-            array($this, 'registration_options_meta_box'),
897
-            $this->page_slug,
898
-            'side',
899
-            'core'
900
-        );
901
-    }
902
-
903
-
904
-    /**
905
-     * override caf metabox
906
-     *
907
-     * @return void
908
-     * @throws DomainException
909
-     */
910
-    public function registration_options_meta_box()
911
-    {
912
-        $yes_no_values                                    = array(
913
-            array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
914
-            array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
915
-        );
916
-        $default_reg_status_values                        = EEM_Registration::reg_status_array(
917
-            array(
918
-                EEM_Registration::status_id_cancelled,
919
-                EEM_Registration::status_id_declined,
920
-                EEM_Registration::status_id_incomplete,
921
-                EEM_Registration::status_id_wait_list,
922
-            ),
923
-            true
924
-        );
925
-        $template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
926
-        $template_args['_event']                          = $this->_cpt_model_obj;
927
-        $template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
928
-        $template_args['default_registration_status']     = EEH_Form_Fields::select_input(
929
-            'default_reg_status',
930
-            $default_reg_status_values,
931
-            $this->_cpt_model_obj->default_registration_status()
932
-        );
933
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
934
-            'display_desc',
935
-            $yes_no_values,
936
-            $this->_cpt_model_obj->display_description()
937
-        );
938
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
939
-            'display_ticket_selector',
940
-            $yes_no_values,
941
-            $this->_cpt_model_obj->display_ticket_selector(),
942
-            '',
943
-            '',
944
-            false
945
-        );
946
-        $template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
947
-            'EVT_default_registration_status',
948
-            $default_reg_status_values,
949
-            $this->_cpt_model_obj->default_registration_status()
950
-        );
951
-        $template_args['additional_registration_options'] = apply_filters(
952
-            'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
953
-            '',
954
-            $template_args,
955
-            $yes_no_values,
956
-            $default_reg_status_values
957
-        );
958
-        EEH_Template::display_template(
959
-            EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
960
-            $template_args
961
-        );
962
-    }
963
-
964
-
965
-
966
-    /**
967
-     * wp_list_table_mods for caf
968
-     * ============================
969
-     */
970
-    /**
971
-     * hook into list table filters and provide filters for caffeinated list table
972
-     *
973
-     * @param  array $old_filters    any existing filters present
974
-     * @param  array $list_table_obj the list table object
975
-     * @return array                  new filters
976
-     */
977
-    public function list_table_filters($old_filters, $list_table_obj)
978
-    {
979
-        $filters = array();
980
-        //first month/year filters
981
-        $filters[] = $this->espresso_event_months_dropdown();
982
-        $status    = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
983
-        //active status dropdown
984
-        if ($status !== 'draft') {
985
-            $filters[] = $this->active_status_dropdown(
986
-                isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
987
-            );
988
-        }
989
-        //category filter
990
-        $filters[] = $this->category_dropdown();
991
-        return array_merge($old_filters, $filters);
992
-    }
993
-
994
-
995
-    /**
996
-     * espresso_event_months_dropdown
997
-     *
998
-     * @access public
999
-     * @return string                dropdown listing month/year selections for events.
1000
-     */
1001
-    public function espresso_event_months_dropdown()
1002
-    {
1003
-        // what we need to do is get all PRIMARY datetimes for all events to filter on.
1004
-        // Note we need to include any other filters that are set!
1005
-        $status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1006
-        //categories?
1007
-        $category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1008
-            ? $this->_req_data['EVT_CAT']
1009
-            : null;
1010
-        //active status?
1011
-        $active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
1012
-        $cur_date      = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1013
-        return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1014
-    }
1015
-
1016
-
1017
-    /**
1018
-     * returns a list of "active" statuses on the event
1019
-     *
1020
-     * @param  string $current_value whatever the current active status is
1021
-     * @return string
1022
-     */
1023
-    public function active_status_dropdown($current_value = '')
1024
-    {
1025
-        $select_name = 'active_status';
1026
-        $values      = array(
1027
-            'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1028
-            'active'   => esc_html__('Active', 'event_espresso'),
1029
-            'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1030
-            'expired'  => esc_html__('Expired', 'event_espresso'),
1031
-            'inactive' => esc_html__('Inactive', 'event_espresso'),
1032
-        );
1033
-        $id          = 'id="espresso-active-status-dropdown-filter"';
1034
-        $class       = 'wide';
1035
-        return EEH_Form_Fields::select_input($select_name, $values, $current_value, $id, $class);
1036
-    }
1037
-
1038
-
1039
-    /**
1040
-     * output a dropdown of the categories for the category filter on the event admin list table
1041
-     *
1042
-     * @access  public
1043
-     * @return string html
1044
-     */
1045
-    public function category_dropdown()
1046
-    {
1047
-        $cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1048
-        return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1049
-    }
1050
-
1051
-
1052
-    /**
1053
-     * get total number of events today
1054
-     *
1055
-     * @access public
1056
-     * @return int
1057
-     * @throws EE_Error
1058
-     */
1059
-    public function total_events_today()
1060
-    {
1061
-        $start = EEM_Datetime::instance()->convert_datetime_for_query(
1062
-            'DTT_EVT_start',
1063
-            date('Y-m-d') . ' 00:00:00',
1064
-            'Y-m-d H:i:s',
1065
-            'UTC'
1066
-        );
1067
-        $end   = EEM_Datetime::instance()->convert_datetime_for_query(
1068
-            'DTT_EVT_start',
1069
-            date('Y-m-d') . ' 23:59:59',
1070
-            'Y-m-d H:i:s',
1071
-            'UTC'
1072
-        );
1073
-        $where = array(
1074
-            'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1075
-        );
1076
-        $count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1077
-        return $count;
1078
-    }
1079
-
1080
-
1081
-    /**
1082
-     * get total number of events this month
1083
-     *
1084
-     * @access public
1085
-     * @return int
1086
-     * @throws EE_Error
1087
-     */
1088
-    public function total_events_this_month()
1089
-    {
1090
-        //Dates
1091
-        $this_year_r     = date('Y');
1092
-        $this_month_r    = date('m');
1093
-        $days_this_month = date('t');
1094
-        $start           = EEM_Datetime::instance()->convert_datetime_for_query(
1095
-            'DTT_EVT_start',
1096
-            $this_year_r . '-' . $this_month_r . '-01 00:00:00',
1097
-            'Y-m-d H:i:s',
1098
-            'UTC'
1099
-        );
1100
-        $end             = EEM_Datetime::instance()->convert_datetime_for_query(
1101
-            'DTT_EVT_start',
1102
-            $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1103
-            'Y-m-d H:i:s',
1104
-            'UTC'
1105
-        );
1106
-        $where           = array(
1107
-            'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1108
-        );
1109
-        $count           = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1110
-        return $count;
1111
-    }
1112
-
1113
-
1114
-    /** DEFAULT TICKETS STUFF **/
1115
-
1116
-    /**
1117
-     * Output default tickets list table view.
1118
-     */
1119
-    public function _tickets_overview_list_table()
1120
-    {
1121
-        $this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1122
-        $this->display_admin_list_table_page_with_no_sidebar();
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * @param int  $per_page
1128
-     * @param bool $count
1129
-     * @param bool $trashed
1130
-     * @return \EE_Soft_Delete_Base_Class[]|int
1131
-     */
1132
-    public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1133
-    {
1134
-        $orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1135
-        $order   = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1136
-        switch ($orderby) {
1137
-            case 'TKT_name':
1138
-                $orderby = array('TKT_name' => $order);
1139
-                break;
1140
-            case 'TKT_price':
1141
-                $orderby = array('TKT_price' => $order);
1142
-                break;
1143
-            case 'TKT_uses':
1144
-                $orderby = array('TKT_uses' => $order);
1145
-                break;
1146
-            case 'TKT_min':
1147
-                $orderby = array('TKT_min' => $order);
1148
-                break;
1149
-            case 'TKT_max':
1150
-                $orderby = array('TKT_max' => $order);
1151
-                break;
1152
-            case 'TKT_qty':
1153
-                $orderby = array('TKT_qty' => $order);
1154
-                break;
1155
-        }
1156
-        $current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1157
-            ? $this->_req_data['paged']
1158
-            : 1;
1159
-        $per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1160
-            ? $this->_req_data['perpage']
1161
-            : $per_page;
1162
-        $_where       = array(
1163
-            'TKT_is_default' => 1,
1164
-            'TKT_deleted'    => $trashed,
1165
-        );
1166
-        $offset       = ($current_page - 1) * $per_page;
1167
-        $limit        = array($offset, $per_page);
1168
-        if (isset($this->_req_data['s'])) {
1169
-            $sstr         = '%' . $this->_req_data['s'] . '%';
1170
-            $_where['OR'] = array(
1171
-                'TKT_name'        => array('LIKE', $sstr),
1172
-                'TKT_description' => array('LIKE', $sstr),
1173
-            );
1174
-        }
1175
-        $query_params = array(
1176
-            $_where,
1177
-            'order_by' => $orderby,
1178
-            'limit'    => $limit,
1179
-            'group_by' => 'TKT_ID',
1180
-        );
1181
-        if ($count) {
1182
-            return EEM_Ticket::instance()->count_deleted_and_undeleted(array($_where));
1183
-        } else {
1184
-            return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1185
-        }
1186
-    }
1187
-
1188
-
1189
-    /**
1190
-     * @param bool $trash
1191
-     * @throws EE_Error
1192
-     */
1193
-    protected function _trash_or_restore_ticket($trash = false)
1194
-    {
1195
-        $success = 1;
1196
-        $TKT     = EEM_Ticket::instance();
1197
-        //checkboxes?
1198
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1199
-            //if array has more than one element then success message should be plural
1200
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1201
-            //cycle thru the boxes
1202
-            while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1203
-                if ($trash) {
1204
-                    if (! $TKT->delete_by_ID($TKT_ID)) {
1205
-                        $success = 0;
1206
-                    }
1207
-                } else {
1208
-                    if (! $TKT->restore_by_ID($TKT_ID)) {
1209
-                        $success = 0;
1210
-                    }
1211
-                }
1212
-            }
1213
-        } else {
1214
-            //grab single id and trash
1215
-            $TKT_ID = absint($this->_req_data['TKT_ID']);
1216
-            if ($trash) {
1217
-                if (! $TKT->delete_by_ID($TKT_ID)) {
1218
-                    $success = 0;
1219
-                }
1220
-            } else {
1221
-                if (! $TKT->restore_by_ID($TKT_ID)) {
1222
-                    $success = 0;
1223
-                }
1224
-            }
1225
-        }
1226
-        $action_desc = $trash ? 'moved to the trash' : 'restored';
1227
-        $query_args  = array(
1228
-            'action' => 'ticket_list_table',
1229
-            'status' => $trash ? '' : 'trashed',
1230
-        );
1231
-        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * Handles trashing default ticket.
1237
-     */
1238
-    protected function _delete_ticket()
1239
-    {
1240
-        $success = 1;
1241
-        //checkboxes?
1242
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1243
-            //if array has more than one element then success message should be plural
1244
-            $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1245
-            //cycle thru the boxes
1246
-            while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1247
-                //delete
1248
-                if (! $this->_delete_the_ticket($TKT_ID)) {
1249
-                    $success = 0;
1250
-                }
1251
-            }
1252
-        } else {
1253
-            //grab single id and trash
1254
-            $TKT_ID = absint($this->_req_data['TKT_ID']);
1255
-            if (! $this->_delete_the_ticket($TKT_ID)) {
1256
-                $success = 0;
1257
-            }
1258
-        }
1259
-        $action_desc = 'deleted';
1260
-        $query_args  = array(
1261
-            'action' => 'ticket_list_table',
1262
-            'status' => 'trashed',
1263
-        );
1264
-        //fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1265
-        if (EEM_Ticket::instance()->count_deleted_and_undeleted(
1266
-            array(array('TKT_is_default' => 1)),
1267
-            'TKT_ID',
1268
-            true
1269
-        )
1270
-        ) {
1271
-            $query_args = array();
1272
-        }
1273
-        $this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1274
-    }
1275
-
1276
-
1277
-    /**
1278
-     * @param int $TKT_ID
1279
-     * @return bool|int
1280
-     * @throws EE_Error
1281
-     */
1282
-    protected function _delete_the_ticket($TKT_ID)
1283
-    {
1284
-        $tkt = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1285
-        $tkt->_remove_relations('Datetime');
1286
-        //delete all related prices first
1287
-        $tkt->delete_related_permanently('Price');
1288
-        return $tkt->delete_permanently();
1289
-    }
22
+	/**
23
+	 * Extend_Events_Admin_Page constructor.
24
+	 *
25
+	 * @param bool $routing
26
+	 */
27
+	public function __construct($routing = true)
28
+	{
29
+		parent::__construct($routing);
30
+		if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
31
+			define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
32
+			define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
33
+			define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
34
+		}
35
+	}
36
+
37
+
38
+	/**
39
+	 * Sets routes.
40
+	 */
41
+	protected function _extend_page_config()
42
+	{
43
+		$this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
44
+		//is there a evt_id in the request?
45
+		$evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
46
+			? $this->_req_data['EVT_ID']
47
+			: 0;
48
+		$evt_id = ! empty($this->_req_data['post']) ? $this->_req_data['post'] : $evt_id;
49
+		//tkt_id?
50
+		$tkt_id             = ! empty($this->_req_data['TKT_ID']) && ! is_array($this->_req_data['TKT_ID'])
51
+			? $this->_req_data['TKT_ID']
52
+			: 0;
53
+		$new_page_routes    = array(
54
+			'duplicate_event'          => array(
55
+				'func'       => '_duplicate_event',
56
+				'capability' => 'ee_edit_event',
57
+				'obj_id'     => $evt_id,
58
+				'noheader'   => true,
59
+			),
60
+			'ticket_list_table'        => array(
61
+				'func'       => '_tickets_overview_list_table',
62
+				'capability' => 'ee_read_default_tickets',
63
+			),
64
+			'trash_ticket'             => array(
65
+				'func'       => '_trash_or_restore_ticket',
66
+				'capability' => 'ee_delete_default_ticket',
67
+				'obj_id'     => $tkt_id,
68
+				'noheader'   => true,
69
+				'args'       => array('trash' => true),
70
+			),
71
+			'trash_tickets'            => array(
72
+				'func'       => '_trash_or_restore_ticket',
73
+				'capability' => 'ee_delete_default_tickets',
74
+				'noheader'   => true,
75
+				'args'       => array('trash' => true),
76
+			),
77
+			'restore_ticket'           => array(
78
+				'func'       => '_trash_or_restore_ticket',
79
+				'capability' => 'ee_delete_default_ticket',
80
+				'obj_id'     => $tkt_id,
81
+				'noheader'   => true,
82
+			),
83
+			'restore_tickets'          => array(
84
+				'func'       => '_trash_or_restore_ticket',
85
+				'capability' => 'ee_delete_default_tickets',
86
+				'noheader'   => true,
87
+			),
88
+			'delete_ticket'            => array(
89
+				'func'       => '_delete_ticket',
90
+				'capability' => 'ee_delete_default_ticket',
91
+				'obj_id'     => $tkt_id,
92
+				'noheader'   => true,
93
+			),
94
+			'delete_tickets'           => array(
95
+				'func'       => '_delete_ticket',
96
+				'capability' => 'ee_delete_default_tickets',
97
+				'noheader'   => true,
98
+			),
99
+			'import_page'              => array(
100
+				'func'       => '_import_page',
101
+				'capability' => 'import',
102
+			),
103
+			'import'                   => array(
104
+				'func'       => '_import_events',
105
+				'capability' => 'import',
106
+				'noheader'   => true,
107
+			),
108
+			'import_events'            => array(
109
+				'func'       => '_import_events',
110
+				'capability' => 'import',
111
+				'noheader'   => true,
112
+			),
113
+			'export_events'            => array(
114
+				'func'       => '_events_export',
115
+				'capability' => 'export',
116
+				'noheader'   => true,
117
+			),
118
+			'export_categories'        => array(
119
+				'func'       => '_categories_export',
120
+				'capability' => 'export',
121
+				'noheader'   => true,
122
+			),
123
+			'sample_export_file'       => array(
124
+				'func'       => '_sample_export_file',
125
+				'capability' => 'export',
126
+				'noheader'   => true,
127
+			),
128
+			'update_template_settings' => array(
129
+				'func'       => '_update_template_settings',
130
+				'capability' => 'manage_options',
131
+				'noheader'   => true,
132
+			),
133
+		);
134
+		$this->_page_routes = array_merge($this->_page_routes, $new_page_routes);
135
+		//partial route/config override
136
+		$this->_page_config['import_events']['metaboxes'] = $this->_default_espresso_metaboxes;
137
+		$this->_page_config['create_new']['metaboxes'][]  = '_premium_event_editor_meta_boxes';
138
+		$this->_page_config['create_new']['qtips'][]      = 'EE_Event_Editor_Tips';
139
+		$this->_page_config['edit']['qtips'][]            = 'EE_Event_Editor_Tips';
140
+		$this->_page_config['edit']['metaboxes'][]        = '_premium_event_editor_meta_boxes';
141
+		$this->_page_config['default']['list_table']      = 'Extend_Events_Admin_List_Table';
142
+		//add tickets tab but only if there are more than one default ticket!
143
+		$tkt_count = EEM_Ticket::instance()->count_deleted_and_undeleted(
144
+			array(array('TKT_is_default' => 1)),
145
+			'TKT_ID',
146
+			true
147
+		);
148
+		if ($tkt_count > 1) {
149
+			$new_page_config = array(
150
+				'ticket_list_table' => array(
151
+					'nav'           => array(
152
+						'label' => esc_html__('Default Tickets', 'event_espresso'),
153
+						'order' => 60,
154
+					),
155
+					'list_table'    => 'Tickets_List_Table',
156
+					'require_nonce' => false,
157
+				),
158
+			);
159
+		}
160
+		//template settings
161
+		$new_page_config['template_settings'] = array(
162
+			'nav'           => array(
163
+				'label' => esc_html__('Templates', 'event_espresso'),
164
+				'order' => 30,
165
+			),
166
+			'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
167
+			'help_tabs'     => array(
168
+				'general_settings_templates_help_tab' => array(
169
+					'title'    => esc_html__('Templates', 'event_espresso'),
170
+					'filename' => 'general_settings_templates',
171
+				),
172
+			),
173
+			'help_tour'     => array('Templates_Help_Tour'),
174
+			'require_nonce' => false,
175
+		);
176
+		$this->_page_config                   = array_merge($this->_page_config, $new_page_config);
177
+		//add filters and actions
178
+		//modifying _views
179
+		add_filter(
180
+			'FHEE_event_datetime_metabox_add_additional_date_time_template',
181
+			array($this, 'add_additional_datetime_button'),
182
+			10,
183
+			2
184
+		);
185
+		add_filter(
186
+			'FHEE_event_datetime_metabox_clone_button_template',
187
+			array($this, 'add_datetime_clone_button'),
188
+			10,
189
+			2
190
+		);
191
+		add_filter(
192
+			'FHEE_event_datetime_metabox_timezones_template',
193
+			array($this, 'datetime_timezones_template'),
194
+			10,
195
+			2
196
+		);
197
+		//filters for event list table
198
+		add_filter('FHEE__Extend_Events_Admin_List_Table__filters', array($this, 'list_table_filters'), 10, 2);
199
+		add_filter(
200
+			'FHEE__Events_Admin_List_Table__column_actions__action_links',
201
+			array($this, 'extra_list_table_actions'),
202
+			10,
203
+			2
204
+		);
205
+		//legend item
206
+		add_filter('FHEE__Events_Admin_Page___event_legend_items__items', array($this, 'additional_legend_items'));
207
+		add_action('admin_init', array($this, 'admin_init'));
208
+		//heartbeat stuff
209
+		add_filter('heartbeat_received', array($this, 'heartbeat_response'), 10, 2);
210
+	}
211
+
212
+
213
+	/**
214
+	 * admin_init
215
+	 */
216
+	public function admin_init()
217
+	{
218
+		EE_Registry::$i18n_js_strings = array_merge(
219
+			EE_Registry::$i18n_js_strings,
220
+			array(
221
+				'image_confirm'          => esc_html__(
222
+					'Do you really want to delete this image? Please remember to update your event to complete the removal.',
223
+					'event_espresso'
224
+				),
225
+				'event_starts_on'        => esc_html__('Event Starts on', 'event_espresso'),
226
+				'event_ends_on'          => esc_html__('Event Ends on', 'event_espresso'),
227
+				'event_datetime_actions' => esc_html__('Actions', 'event_espresso'),
228
+				'event_clone_dt_msg'     => esc_html__('Clone this Event Date and Time', 'event_espresso'),
229
+				'remove_event_dt_msg'    => esc_html__('Remove this Event Time', 'event_espresso'),
230
+			)
231
+		);
232
+	}
233
+
234
+
235
+	/**
236
+	 * This will be used to listen for any heartbeat data packages coming via the WordPress heartbeat API and handle
237
+	 * accordingly.
238
+	 *
239
+	 * @param array $response The existing heartbeat response array.
240
+	 * @param array $data     The incoming data package.
241
+	 * @return array  possibly appended response.
242
+	 */
243
+	public function heartbeat_response($response, $data)
244
+	{
245
+		/**
246
+		 * check whether count of tickets is approaching the potential
247
+		 * limits for the server.
248
+		 */
249
+		if (! empty($data['input_count'])) {
250
+			$response['max_input_vars_check'] = EE_Registry::instance()->CFG->environment->max_input_vars_limit_check(
251
+				$data['input_count']
252
+			);
253
+		}
254
+		return $response;
255
+	}
256
+
257
+
258
+	/**
259
+	 * Add per page screen options to the default ticket list table view.
260
+	 */
261
+	protected function _add_screen_options_ticket_list_table()
262
+	{
263
+		$this->_per_page_screen_option();
264
+	}
265
+
266
+
267
+	/**
268
+	 * @param string $return
269
+	 * @param int    $id
270
+	 * @param string $new_title
271
+	 * @param string $new_slug
272
+	 * @return string
273
+	 */
274
+	public function extra_permalink_field_buttons($return, $id, $new_title, $new_slug)
275
+	{
276
+		$return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
277
+		//make sure this is only when editing
278
+		if (! empty($id)) {
279
+			$href   = EE_Admin_Page::add_query_args_and_nonce(
280
+				array('action' => 'duplicate_event', 'EVT_ID' => $id),
281
+				$this->_admin_base_url
282
+			);
283
+			$title  = esc_attr__('Duplicate Event', 'event_espresso');
284
+			$return .= '<a href="'
285
+					   . $href
286
+					   . '" title="'
287
+					   . $title
288
+					   . '" id="ee-duplicate-event-button" class="button button-small"  value="duplicate_event">'
289
+					   . $title
290
+					   . '</a>';
291
+		}
292
+		return $return;
293
+	}
294
+
295
+
296
+	/**
297
+	 * Set the list table views for the default ticket list table view.
298
+	 */
299
+	public function _set_list_table_views_ticket_list_table()
300
+	{
301
+		$this->_views = array(
302
+			'all'     => array(
303
+				'slug'        => 'all',
304
+				'label'       => esc_html__('All', 'event_espresso'),
305
+				'count'       => 0,
306
+				'bulk_action' => array(
307
+					'trash_tickets' => esc_html__('Move to Trash', 'event_espresso'),
308
+				),
309
+			),
310
+			'trashed' => array(
311
+				'slug'        => 'trashed',
312
+				'label'       => esc_html__('Trash', 'event_espresso'),
313
+				'count'       => 0,
314
+				'bulk_action' => array(
315
+					'restore_tickets' => esc_html__('Restore from Trash', 'event_espresso'),
316
+					'delete_tickets'  => esc_html__('Delete Permanently', 'event_espresso'),
317
+				),
318
+			),
319
+		);
320
+	}
321
+
322
+
323
+	/**
324
+	 * Enqueue scripts and styles for the event editor.
325
+	 */
326
+	public function load_scripts_styles_edit()
327
+	{
328
+		wp_register_script(
329
+			'ee-event-editor-heartbeat',
330
+			EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
331
+			array('ee_admin_js', 'heartbeat'),
332
+			EVENT_ESPRESSO_VERSION,
333
+			true
334
+		);
335
+		wp_enqueue_script('ee-accounting');
336
+		//styles
337
+		wp_enqueue_style('espresso-ui-theme');
338
+		wp_enqueue_script('event_editor_js');
339
+		wp_enqueue_script('ee-event-editor-heartbeat');
340
+	}
341
+
342
+
343
+	/**
344
+	 * Returns template for the additional datetime.
345
+	 * @param $template
346
+	 * @param $template_args
347
+	 * @return mixed
348
+	 * @throws DomainException
349
+	 */
350
+	public function add_additional_datetime_button($template, $template_args)
351
+	{
352
+		return EEH_Template::display_template(
353
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
354
+			$template_args,
355
+			true
356
+		);
357
+	}
358
+
359
+
360
+	/**
361
+	 * Returns the template for cloning a datetime.
362
+	 * @param $template
363
+	 * @param $template_args
364
+	 * @return mixed
365
+	 * @throws DomainException
366
+	 */
367
+	public function add_datetime_clone_button($template, $template_args)
368
+	{
369
+		return EEH_Template::display_template(
370
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
371
+			$template_args,
372
+			true
373
+		);
374
+	}
375
+
376
+
377
+	/**
378
+	 * Returns the template for datetime timezones.
379
+	 * @param $template
380
+	 * @param $template_args
381
+	 * @return mixed
382
+	 * @throws DomainException
383
+	 */
384
+	public function datetime_timezones_template($template, $template_args)
385
+	{
386
+		return EEH_Template::display_template(
387
+			EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
388
+			$template_args,
389
+			true
390
+		);
391
+	}
392
+
393
+
394
+	/**
395
+	 * Sets the views for the default list table view.
396
+	 */
397
+	protected function _set_list_table_views_default()
398
+	{
399
+		parent::_set_list_table_views_default();
400
+		$new_views    = array(
401
+			'today' => array(
402
+				'slug'        => 'today',
403
+				'label'       => esc_html__('Today', 'event_espresso'),
404
+				'count'       => $this->total_events_today(),
405
+				'bulk_action' => array(
406
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
407
+				),
408
+			),
409
+			'month' => array(
410
+				'slug'        => 'month',
411
+				'label'       => esc_html__('This Month', 'event_espresso'),
412
+				'count'       => $this->total_events_this_month(),
413
+				'bulk_action' => array(
414
+					'trash_events' => esc_html__('Move to Trash', 'event_espresso'),
415
+				),
416
+			),
417
+		);
418
+		$this->_views = array_merge($this->_views, $new_views);
419
+	}
420
+
421
+
422
+	/**
423
+	 * Returns the extra action links for the default list table view.
424
+	 * @param array     $action_links
425
+	 * @param \EE_Event $event
426
+	 * @return array
427
+	 * @throws EE_Error
428
+	 */
429
+	public function extra_list_table_actions(array $action_links, \EE_Event $event)
430
+	{
431
+		if (EE_Registry::instance()->CAP->current_user_can(
432
+			'ee_read_registrations',
433
+			'espresso_registrations_reports',
434
+			$event->ID()
435
+		)
436
+		) {
437
+			$reports_query_args = array(
438
+				'action' => 'reports',
439
+				'EVT_ID' => $event->ID(),
440
+			);
441
+			$reports_link       = EE_Admin_Page::add_query_args_and_nonce($reports_query_args, REG_ADMIN_URL);
442
+			$action_links[]     = '<a href="'
443
+								  . $reports_link
444
+								  . '" title="'
445
+								  . esc_attr__('View Report', 'event_espresso')
446
+								  . '"><div class="dashicons dashicons-chart-bar"></div></a>'
447
+								  . "\n\t";
448
+		}
449
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
450
+			EE_Registry::instance()->load_helper('MSG_Template');
451
+			$action_links[] = EEH_MSG_Template::get_message_action_link(
452
+				'see_notifications_for',
453
+				null,
454
+				array('EVT_ID' => $event->ID())
455
+			);
456
+		}
457
+		return $action_links;
458
+	}
459
+
460
+
461
+	/**
462
+	 * @param $items
463
+	 * @return mixed
464
+	 */
465
+	public function additional_legend_items($items)
466
+	{
467
+		if (EE_Registry::instance()->CAP->current_user_can(
468
+			'ee_read_registrations',
469
+			'espresso_registrations_reports'
470
+		)
471
+		) {
472
+			$items['reports'] = array(
473
+				'class' => 'dashicons dashicons-chart-bar',
474
+				'desc'  => esc_html__('Event Reports', 'event_espresso'),
475
+			);
476
+		}
477
+		if (EE_Registry::instance()->CAP->current_user_can('ee_read_global_messages', 'view_filtered_messages')) {
478
+			$related_for_icon = EEH_MSG_Template::get_message_action_icon('see_notifications_for');
479
+			if (isset($related_for_icon['css_class']) && isset($related_for_icon['label'])) {
480
+				$items['view_related_messages'] = array(
481
+					'class' => $related_for_icon['css_class'],
482
+					'desc'  => $related_for_icon['label'],
483
+				);
484
+			}
485
+		}
486
+		return $items;
487
+	}
488
+
489
+
490
+	/**
491
+	 * This is the callback method for the duplicate event route
492
+	 * Method looks for 'EVT_ID' in the request and retrieves that event and its details and duplicates them
493
+	 * into a new event.  We add a hook so that any plugins that add extra event details can hook into this
494
+	 * action.  Note that the dupe will have **DUPLICATE** as its title and slug.
495
+	 * After duplication the redirect is to the new event edit page.
496
+	 *
497
+	 * @return void
498
+	 * @access protected
499
+	 * @throws EE_Error If EE_Event is not available with given ID
500
+	 */
501
+	protected function _duplicate_event()
502
+	{
503
+		// first make sure the ID for the event is in the request.
504
+		//  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
505
+		if (! isset($this->_req_data['EVT_ID'])) {
506
+			EE_Error::add_error(
507
+				esc_html__(
508
+					'In order to duplicate an event an Event ID is required.  None was given.',
509
+					'event_espresso'
510
+				),
511
+				__FILE__,
512
+				__FUNCTION__,
513
+				__LINE__
514
+			);
515
+			$this->_redirect_after_action(false, '', '', array(), true);
516
+			return;
517
+		}
518
+		//k we've got EVT_ID so let's use that to get the event we'll duplicate
519
+		$orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
520
+		if (! $orig_event instanceof EE_Event) {
521
+			throw new EE_Error(
522
+				sprintf(
523
+					esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
524
+					$this->_req_data['EVT_ID']
525
+				)
526
+			);
527
+		}
528
+		//k now let's clone the $orig_event before getting relations
529
+		$new_event = clone $orig_event;
530
+		//original datetimes
531
+		$orig_datetimes = $orig_event->get_many_related('Datetime');
532
+		//other original relations
533
+		$orig_ven = $orig_event->get_many_related('Venue');
534
+		//reset the ID and modify other details to make it clear this is a dupe
535
+		$new_event->set('EVT_ID', 0);
536
+		$new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
537
+		$new_event->set('EVT_name', $new_name);
538
+		$new_event->set(
539
+			'EVT_slug',
540
+			wp_unique_post_slug(
541
+				sanitize_title($orig_event->name()),
542
+				0,
543
+				'publish',
544
+				'espresso_events',
545
+				0
546
+			)
547
+		);
548
+		$new_event->set('status', 'draft');
549
+		//duplicate discussion settings
550
+		$new_event->set('comment_status', $orig_event->get('comment_status'));
551
+		$new_event->set('ping_status', $orig_event->get('ping_status'));
552
+		//save the new event
553
+		$new_event->save();
554
+		//venues
555
+		foreach ($orig_ven as $ven) {
556
+			$new_event->_add_relation_to($ven, 'Venue');
557
+		}
558
+		$new_event->save();
559
+		//now we need to get the question group relations and handle that
560
+		//first primary question groups
561
+		$orig_primary_qgs = $orig_event->get_many_related(
562
+			'Question_Group',
563
+			array(array('Event_Question_Group.EQG_primary' => 1))
564
+		);
565
+		if (! empty($orig_primary_qgs)) {
566
+			foreach ($orig_primary_qgs as $id => $obj) {
567
+				if ($obj instanceof EE_Question_Group) {
568
+					$new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 1));
569
+				}
570
+			}
571
+		}
572
+		//next additional attendee question groups
573
+		$orig_additional_qgs = $orig_event->get_many_related(
574
+			'Question_Group',
575
+			array(array('Event_Question_Group.EQG_primary' => 0))
576
+		);
577
+		if (! empty($orig_additional_qgs)) {
578
+			foreach ($orig_additional_qgs as $id => $obj) {
579
+				if ($obj instanceof EE_Question_Group) {
580
+					$new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 0));
581
+				}
582
+			}
583
+		}
584
+
585
+		$new_event->save();
586
+
587
+		//k now that we have the new event saved we can loop through the datetimes and start adding relations.
588
+		$cloned_tickets = array();
589
+		foreach ($orig_datetimes as $orig_dtt) {
590
+			if (! $orig_dtt instanceof EE_Datetime) {
591
+				continue;
592
+			}
593
+			$new_dtt   = clone $orig_dtt;
594
+			$orig_tkts = $orig_dtt->tickets();
595
+			//save new dtt then add to event
596
+			$new_dtt->set('DTT_ID', 0);
597
+			$new_dtt->set('DTT_sold', 0);
598
+			$new_dtt->set_reserved(0);
599
+			$new_dtt->save();
600
+			$new_event->_add_relation_to($new_dtt, 'Datetime');
601
+			$new_event->save();
602
+			//now let's get the ticket relations setup.
603
+			foreach ((array)$orig_tkts as $orig_tkt) {
604
+				//it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
605
+				if (! $orig_tkt instanceof EE_Ticket) {
606
+					continue;
607
+				}
608
+				//is this ticket archived?  If it is then let's skip
609
+				if ($orig_tkt->get('TKT_deleted')) {
610
+					continue;
611
+				}
612
+				// does this original ticket already exist in the clone_tickets cache?
613
+				//  If so we'll just use the new ticket from it.
614
+				if (isset($cloned_tickets[$orig_tkt->ID()])) {
615
+					$new_tkt = $cloned_tickets[$orig_tkt->ID()];
616
+				} else {
617
+					$new_tkt = clone $orig_tkt;
618
+					//get relations on the $orig_tkt that we need to setup.
619
+					$orig_prices = $orig_tkt->prices();
620
+					$new_tkt->set('TKT_ID', 0);
621
+					$new_tkt->set('TKT_sold', 0);
622
+					$new_tkt->set('TKT_reserved', 0);
623
+					$new_tkt->save(); //make sure new ticket has ID.
624
+					//price relations on new ticket need to be setup.
625
+					foreach ($orig_prices as $orig_price) {
626
+						$new_price = clone $orig_price;
627
+						$new_price->set('PRC_ID', 0);
628
+						$new_price->save();
629
+						$new_tkt->_add_relation_to($new_price, 'Price');
630
+						$new_tkt->save();
631
+					}
632
+
633
+					do_action(
634
+						'AHEE__Extend_Events_Admin_Page___duplicate_event__duplicate_ticket__after',
635
+						$orig_tkt,
636
+						$new_tkt,
637
+						$orig_prices,
638
+						$orig_event,
639
+						$orig_dtt,
640
+						$new_dtt
641
+					);
642
+				}
643
+				// k now we can add the new ticket as a relation to the new datetime
644
+				// and make sure its added to our cached $cloned_tickets array
645
+				// for use with later datetimes that have the same ticket.
646
+				$new_dtt->_add_relation_to($new_tkt, 'Ticket');
647
+				$new_dtt->save();
648
+				$cloned_tickets[$orig_tkt->ID()] = $new_tkt;
649
+			}
650
+		}
651
+		//clone taxonomy information
652
+		$taxonomies_to_clone_with = apply_filters(
653
+			'FHEE__Extend_Events_Admin_Page___duplicate_event__taxonomies_to_clone',
654
+			array('espresso_event_categories', 'espresso_event_type', 'post_tag')
655
+		);
656
+		//get terms for original event (notice)
657
+		$orig_terms = wp_get_object_terms($orig_event->ID(), $taxonomies_to_clone_with);
658
+		//loop through terms and add them to new event.
659
+		foreach ($orig_terms as $term) {
660
+			wp_set_object_terms($new_event->ID(), $term->term_id, $term->taxonomy, true);
661
+		}
662
+
663
+		//duplicate other core WP_Post items for this event.
664
+		//post thumbnail (feature image).
665
+		$feature_image_id = get_post_thumbnail_id($orig_event->ID());
666
+		if ($feature_image_id) {
667
+			update_post_meta($new_event->ID(), '_thumbnail_id', $feature_image_id);
668
+		}
669
+
670
+		//duplicate page_template setting
671
+		$page_template = get_post_meta($orig_event->ID(), '_wp_page_template', true);
672
+		if ($page_template) {
673
+			update_post_meta($new_event->ID(), '_wp_page_template', $page_template);
674
+		}
675
+
676
+		do_action('AHEE__Extend_Events_Admin_Page___duplicate_event__after', $new_event, $orig_event);
677
+		//now let's redirect to the edit page for this duplicated event if we have a new event id.
678
+		if ($new_event->ID()) {
679
+			$redirect_args = array(
680
+				'post'   => $new_event->ID(),
681
+				'action' => 'edit',
682
+			);
683
+			EE_Error::add_success(
684
+				esc_html__(
685
+					'Event successfully duplicated.  Please review the details below and make any necessary edits',
686
+					'event_espresso'
687
+				)
688
+			);
689
+		} else {
690
+			$redirect_args = array(
691
+				'action' => 'default',
692
+			);
693
+			EE_Error::add_error(
694
+				esc_html__('Not able to duplicate event.  Something went wrong.', 'event_espresso'),
695
+				__FILE__,
696
+				__FUNCTION__,
697
+				__LINE__
698
+			);
699
+		}
700
+		$this->_redirect_after_action(false, '', '', $redirect_args, true);
701
+	}
702
+
703
+
704
+	/**
705
+	 * Generates output for the import page.
706
+	 * @throws DomainException
707
+	 */
708
+	protected function _import_page()
709
+	{
710
+		$title                                      = esc_html__('Import', 'event_espresso');
711
+		$intro                                      = esc_html__(
712
+			'If you have a previously exported Event Espresso 4 information in a Comma Separated Value (CSV) file format, you can upload the file here: ',
713
+			'event_espresso'
714
+		);
715
+		$form_url                                   = EVENTS_ADMIN_URL;
716
+		$action                                     = 'import_events';
717
+		$type                                       = 'csv';
718
+		$this->_template_args['form']               = EE_Import::instance()->upload_form(
719
+			$title, $intro, $form_url, $action, $type
720
+		);
721
+		$this->_template_args['sample_file_link']   = EE_Admin_Page::add_query_args_and_nonce(
722
+			array('action' => 'sample_export_file'),
723
+			$this->_admin_base_url
724
+		);
725
+		$content                                    = EEH_Template::display_template(
726
+			EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
727
+			$this->_template_args,
728
+			true
729
+		);
730
+		$this->_template_args['admin_page_content'] = $content;
731
+		$this->display_admin_page_with_sidebar();
732
+	}
733
+
734
+
735
+	/**
736
+	 * _import_events
737
+	 * This handles displaying the screen and running imports for importing events.
738
+	 *
739
+	 * @return void
740
+	 */
741
+	protected function _import_events()
742
+	{
743
+		require_once(EE_CLASSES . 'EE_Import.class.php');
744
+		$success = EE_Import::instance()->import();
745
+		$this->_redirect_after_action($success, 'Import File', 'ran', array('action' => 'import_page'), true);
746
+	}
747
+
748
+
749
+	/**
750
+	 * _events_export
751
+	 * Will export all (or just the given event) to a Excel compatible file.
752
+	 *
753
+	 * @access protected
754
+	 * @return void
755
+	 */
756
+	protected function _events_export()
757
+	{
758
+		if (isset($this->_req_data['EVT_ID'])) {
759
+			$event_ids = $this->_req_data['EVT_ID'];
760
+		} elseif (isset($this->_req_data['EVT_IDs'])) {
761
+			$event_ids = $this->_req_data['EVT_IDs'];
762
+		} else {
763
+			$event_ids = null;
764
+		}
765
+		//todo: I don't like doing this but it'll do until we modify EE_Export Class.
766
+		$new_request_args = array(
767
+			'export' => 'report',
768
+			'action' => 'all_event_data',
769
+			'EVT_ID' => $event_ids,
770
+		);
771
+		$this->_req_data  = array_merge($this->_req_data, $new_request_args);
772
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
773
+			require_once(EE_CLASSES . 'EE_Export.class.php');
774
+			$EE_Export = EE_Export::instance($this->_req_data);
775
+			$EE_Export->export();
776
+		}
777
+	}
778
+
779
+
780
+	/**
781
+	 * handle category exports()
782
+	 *
783
+	 * @return void
784
+	 */
785
+	protected function _categories_export()
786
+	{
787
+		//todo: I don't like doing this but it'll do until we modify EE_Export Class.
788
+		$new_request_args = array(
789
+			'export'       => 'report',
790
+			'action'       => 'categories',
791
+			'category_ids' => $this->_req_data['EVT_CAT_ID'],
792
+		);
793
+		$this->_req_data  = array_merge($this->_req_data, $new_request_args);
794
+		if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
795
+			require_once(EE_CLASSES . 'EE_Export.class.php');
796
+			$EE_Export = EE_Export::instance($this->_req_data);
797
+			$EE_Export->export();
798
+		}
799
+	}
800
+
801
+
802
+	/**
803
+	 * Creates a sample CSV file for importing
804
+	 */
805
+	protected function _sample_export_file()
806
+	{
807
+		//		require_once(EE_CLASSES . 'EE_Export.class.php');
808
+		EE_Export::instance()->export_sample();
809
+	}
810
+
811
+
812
+	/*************        Template Settings        *************/
813
+	/**
814
+	 * Generates template settings page output
815
+	 * @throws DomainException
816
+	 * @throws EE_Error
817
+	 */
818
+	protected function _template_settings()
819
+	{
820
+		$this->_template_args['values'] = $this->_yes_no_values;
821
+		/**
822
+		 * Note leaving this filter in for backward compatibility this was moved in 4.6.x
823
+		 * from General_Settings_Admin_Page to here.
824
+		 */
825
+		$this->_template_args = apply_filters(
826
+			'FHEE__General_Settings_Admin_Page__template_settings__template_args',
827
+			$this->_template_args
828
+		);
829
+		$this->_set_add_edit_form_tags('update_template_settings');
830
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
831
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
832
+			EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
833
+			$this->_template_args,
834
+			true
835
+		);
836
+		$this->display_admin_page_with_sidebar();
837
+	}
838
+
839
+
840
+	/**
841
+	 * Handler for updating template settings.
842
+	 *
843
+	 * @throws InvalidInterfaceException
844
+	 * @throws InvalidDataTypeException
845
+	 * @throws InvalidArgumentException
846
+	 */
847
+	protected function _update_template_settings()
848
+	{
849
+		/**
850
+		 * Note leaving this filter in for backward compatibility this was moved in 4.6.x
851
+		 * from General_Settings_Admin_Page to here.
852
+		 */
853
+		EE_Registry::instance()->CFG->template_settings = apply_filters(
854
+			'FHEE__General_Settings_Admin_Page__update_template_settings__data',
855
+			EE_Registry::instance()->CFG->template_settings,
856
+			$this->_req_data
857
+		);
858
+		//update custom post type slugs and detect if we need to flush rewrite rules
859
+		$old_slug                                          = EE_Registry::instance()->CFG->core->event_cpt_slug;
860
+		EE_Registry::instance()->CFG->core->event_cpt_slug = empty($this->_req_data['event_cpt_slug'])
861
+			? EE_Registry::instance()->CFG->core->event_cpt_slug
862
+			: sanitize_title_with_dashes($this->_req_data['event_cpt_slug']);
863
+		$what                                              = 'Template Settings';
864
+		$success                                           = $this->_update_espresso_configuration(
865
+			$what,
866
+			EE_Registry::instance()->CFG->template_settings,
867
+			__FILE__,
868
+			__FUNCTION__,
869
+			__LINE__
870
+		);
871
+		if (EE_Registry::instance()->CFG->core->event_cpt_slug != $old_slug) {
872
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
873
+			$rewrite_rules =  LoaderFactory::getLoader()->getShared(
874
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
875
+			);
876
+			$rewrite_rules->flush();
877
+		}
878
+		$this->_redirect_after_action($success, $what, 'updated', array('action' => 'template_settings'));
879
+	}
880
+
881
+
882
+	/**
883
+	 * _premium_event_editor_meta_boxes
884
+	 * add all metaboxes related to the event_editor
885
+	 *
886
+	 * @access protected
887
+	 * @return void
888
+	 * @throws EE_Error
889
+	 */
890
+	protected function _premium_event_editor_meta_boxes()
891
+	{
892
+		$this->verify_cpt_object();
893
+		add_meta_box(
894
+			'espresso_event_editor_event_options',
895
+			esc_html__('Event Registration Options', 'event_espresso'),
896
+			array($this, 'registration_options_meta_box'),
897
+			$this->page_slug,
898
+			'side',
899
+			'core'
900
+		);
901
+	}
902
+
903
+
904
+	/**
905
+	 * override caf metabox
906
+	 *
907
+	 * @return void
908
+	 * @throws DomainException
909
+	 */
910
+	public function registration_options_meta_box()
911
+	{
912
+		$yes_no_values                                    = array(
913
+			array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
914
+			array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
915
+		);
916
+		$default_reg_status_values                        = EEM_Registration::reg_status_array(
917
+			array(
918
+				EEM_Registration::status_id_cancelled,
919
+				EEM_Registration::status_id_declined,
920
+				EEM_Registration::status_id_incomplete,
921
+				EEM_Registration::status_id_wait_list,
922
+			),
923
+			true
924
+		);
925
+		$template_args['active_status']                   = $this->_cpt_model_obj->pretty_active_status(false);
926
+		$template_args['_event']                          = $this->_cpt_model_obj;
927
+		$template_args['additional_limit']                = $this->_cpt_model_obj->additional_limit();
928
+		$template_args['default_registration_status']     = EEH_Form_Fields::select_input(
929
+			'default_reg_status',
930
+			$default_reg_status_values,
931
+			$this->_cpt_model_obj->default_registration_status()
932
+		);
933
+		$template_args['display_description']             = EEH_Form_Fields::select_input(
934
+			'display_desc',
935
+			$yes_no_values,
936
+			$this->_cpt_model_obj->display_description()
937
+		);
938
+		$template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
939
+			'display_ticket_selector',
940
+			$yes_no_values,
941
+			$this->_cpt_model_obj->display_ticket_selector(),
942
+			'',
943
+			'',
944
+			false
945
+		);
946
+		$template_args['EVT_default_registration_status'] = EEH_Form_Fields::select_input(
947
+			'EVT_default_registration_status',
948
+			$default_reg_status_values,
949
+			$this->_cpt_model_obj->default_registration_status()
950
+		);
951
+		$template_args['additional_registration_options'] = apply_filters(
952
+			'FHEE__Events_Admin_Page__registration_options_meta_box__additional_registration_options',
953
+			'',
954
+			$template_args,
955
+			$yes_no_values,
956
+			$default_reg_status_values
957
+		);
958
+		EEH_Template::display_template(
959
+			EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
960
+			$template_args
961
+		);
962
+	}
963
+
964
+
965
+
966
+	/**
967
+	 * wp_list_table_mods for caf
968
+	 * ============================
969
+	 */
970
+	/**
971
+	 * hook into list table filters and provide filters for caffeinated list table
972
+	 *
973
+	 * @param  array $old_filters    any existing filters present
974
+	 * @param  array $list_table_obj the list table object
975
+	 * @return array                  new filters
976
+	 */
977
+	public function list_table_filters($old_filters, $list_table_obj)
978
+	{
979
+		$filters = array();
980
+		//first month/year filters
981
+		$filters[] = $this->espresso_event_months_dropdown();
982
+		$status    = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
983
+		//active status dropdown
984
+		if ($status !== 'draft') {
985
+			$filters[] = $this->active_status_dropdown(
986
+				isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : ''
987
+			);
988
+		}
989
+		//category filter
990
+		$filters[] = $this->category_dropdown();
991
+		return array_merge($old_filters, $filters);
992
+	}
993
+
994
+
995
+	/**
996
+	 * espresso_event_months_dropdown
997
+	 *
998
+	 * @access public
999
+	 * @return string                dropdown listing month/year selections for events.
1000
+	 */
1001
+	public function espresso_event_months_dropdown()
1002
+	{
1003
+		// what we need to do is get all PRIMARY datetimes for all events to filter on.
1004
+		// Note we need to include any other filters that are set!
1005
+		$status = isset($this->_req_data['status']) ? $this->_req_data['status'] : null;
1006
+		//categories?
1007
+		$category = isset($this->_req_data['EVT_CAT']) && $this->_req_data['EVT_CAT'] > 0
1008
+			? $this->_req_data['EVT_CAT']
1009
+			: null;
1010
+		//active status?
1011
+		$active_status = isset($this->_req_data['active_status']) ? $this->_req_data['active_status'] : null;
1012
+		$cur_date      = isset($this->_req_data['month_range']) ? $this->_req_data['month_range'] : '';
1013
+		return EEH_Form_Fields::generate_event_months_dropdown($cur_date, $status, $category, $active_status);
1014
+	}
1015
+
1016
+
1017
+	/**
1018
+	 * returns a list of "active" statuses on the event
1019
+	 *
1020
+	 * @param  string $current_value whatever the current active status is
1021
+	 * @return string
1022
+	 */
1023
+	public function active_status_dropdown($current_value = '')
1024
+	{
1025
+		$select_name = 'active_status';
1026
+		$values      = array(
1027
+			'none'     => esc_html__('Show Active/Inactive', 'event_espresso'),
1028
+			'active'   => esc_html__('Active', 'event_espresso'),
1029
+			'upcoming' => esc_html__('Upcoming', 'event_espresso'),
1030
+			'expired'  => esc_html__('Expired', 'event_espresso'),
1031
+			'inactive' => esc_html__('Inactive', 'event_espresso'),
1032
+		);
1033
+		$id          = 'id="espresso-active-status-dropdown-filter"';
1034
+		$class       = 'wide';
1035
+		return EEH_Form_Fields::select_input($select_name, $values, $current_value, $id, $class);
1036
+	}
1037
+
1038
+
1039
+	/**
1040
+	 * output a dropdown of the categories for the category filter on the event admin list table
1041
+	 *
1042
+	 * @access  public
1043
+	 * @return string html
1044
+	 */
1045
+	public function category_dropdown()
1046
+	{
1047
+		$cur_cat = isset($this->_req_data['EVT_CAT']) ? $this->_req_data['EVT_CAT'] : -1;
1048
+		return EEH_Form_Fields::generate_event_category_dropdown($cur_cat);
1049
+	}
1050
+
1051
+
1052
+	/**
1053
+	 * get total number of events today
1054
+	 *
1055
+	 * @access public
1056
+	 * @return int
1057
+	 * @throws EE_Error
1058
+	 */
1059
+	public function total_events_today()
1060
+	{
1061
+		$start = EEM_Datetime::instance()->convert_datetime_for_query(
1062
+			'DTT_EVT_start',
1063
+			date('Y-m-d') . ' 00:00:00',
1064
+			'Y-m-d H:i:s',
1065
+			'UTC'
1066
+		);
1067
+		$end   = EEM_Datetime::instance()->convert_datetime_for_query(
1068
+			'DTT_EVT_start',
1069
+			date('Y-m-d') . ' 23:59:59',
1070
+			'Y-m-d H:i:s',
1071
+			'UTC'
1072
+		);
1073
+		$where = array(
1074
+			'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1075
+		);
1076
+		$count = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1077
+		return $count;
1078
+	}
1079
+
1080
+
1081
+	/**
1082
+	 * get total number of events this month
1083
+	 *
1084
+	 * @access public
1085
+	 * @return int
1086
+	 * @throws EE_Error
1087
+	 */
1088
+	public function total_events_this_month()
1089
+	{
1090
+		//Dates
1091
+		$this_year_r     = date('Y');
1092
+		$this_month_r    = date('m');
1093
+		$days_this_month = date('t');
1094
+		$start           = EEM_Datetime::instance()->convert_datetime_for_query(
1095
+			'DTT_EVT_start',
1096
+			$this_year_r . '-' . $this_month_r . '-01 00:00:00',
1097
+			'Y-m-d H:i:s',
1098
+			'UTC'
1099
+		);
1100
+		$end             = EEM_Datetime::instance()->convert_datetime_for_query(
1101
+			'DTT_EVT_start',
1102
+			$this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1103
+			'Y-m-d H:i:s',
1104
+			'UTC'
1105
+		);
1106
+		$where           = array(
1107
+			'Datetime.DTT_EVT_start' => array('BETWEEN', array($start, $end)),
1108
+		);
1109
+		$count           = EEM_Event::instance()->count(array($where, 'caps' => 'read_admin'), 'EVT_ID', true);
1110
+		return $count;
1111
+	}
1112
+
1113
+
1114
+	/** DEFAULT TICKETS STUFF **/
1115
+
1116
+	/**
1117
+	 * Output default tickets list table view.
1118
+	 */
1119
+	public function _tickets_overview_list_table()
1120
+	{
1121
+		$this->_search_btn_label = esc_html__('Tickets', 'event_espresso');
1122
+		$this->display_admin_list_table_page_with_no_sidebar();
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * @param int  $per_page
1128
+	 * @param bool $count
1129
+	 * @param bool $trashed
1130
+	 * @return \EE_Soft_Delete_Base_Class[]|int
1131
+	 */
1132
+	public function get_default_tickets($per_page = 10, $count = false, $trashed = false)
1133
+	{
1134
+		$orderby = empty($this->_req_data['orderby']) ? 'TKT_name' : $this->_req_data['orderby'];
1135
+		$order   = empty($this->_req_data['order']) ? 'ASC' : $this->_req_data['order'];
1136
+		switch ($orderby) {
1137
+			case 'TKT_name':
1138
+				$orderby = array('TKT_name' => $order);
1139
+				break;
1140
+			case 'TKT_price':
1141
+				$orderby = array('TKT_price' => $order);
1142
+				break;
1143
+			case 'TKT_uses':
1144
+				$orderby = array('TKT_uses' => $order);
1145
+				break;
1146
+			case 'TKT_min':
1147
+				$orderby = array('TKT_min' => $order);
1148
+				break;
1149
+			case 'TKT_max':
1150
+				$orderby = array('TKT_max' => $order);
1151
+				break;
1152
+			case 'TKT_qty':
1153
+				$orderby = array('TKT_qty' => $order);
1154
+				break;
1155
+		}
1156
+		$current_page = isset($this->_req_data['paged']) && ! empty($this->_req_data['paged'])
1157
+			? $this->_req_data['paged']
1158
+			: 1;
1159
+		$per_page     = isset($this->_req_data['perpage']) && ! empty($this->_req_data['perpage'])
1160
+			? $this->_req_data['perpage']
1161
+			: $per_page;
1162
+		$_where       = array(
1163
+			'TKT_is_default' => 1,
1164
+			'TKT_deleted'    => $trashed,
1165
+		);
1166
+		$offset       = ($current_page - 1) * $per_page;
1167
+		$limit        = array($offset, $per_page);
1168
+		if (isset($this->_req_data['s'])) {
1169
+			$sstr         = '%' . $this->_req_data['s'] . '%';
1170
+			$_where['OR'] = array(
1171
+				'TKT_name'        => array('LIKE', $sstr),
1172
+				'TKT_description' => array('LIKE', $sstr),
1173
+			);
1174
+		}
1175
+		$query_params = array(
1176
+			$_where,
1177
+			'order_by' => $orderby,
1178
+			'limit'    => $limit,
1179
+			'group_by' => 'TKT_ID',
1180
+		);
1181
+		if ($count) {
1182
+			return EEM_Ticket::instance()->count_deleted_and_undeleted(array($_where));
1183
+		} else {
1184
+			return EEM_Ticket::instance()->get_all_deleted_and_undeleted($query_params);
1185
+		}
1186
+	}
1187
+
1188
+
1189
+	/**
1190
+	 * @param bool $trash
1191
+	 * @throws EE_Error
1192
+	 */
1193
+	protected function _trash_or_restore_ticket($trash = false)
1194
+	{
1195
+		$success = 1;
1196
+		$TKT     = EEM_Ticket::instance();
1197
+		//checkboxes?
1198
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1199
+			//if array has more than one element then success message should be plural
1200
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1201
+			//cycle thru the boxes
1202
+			while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1203
+				if ($trash) {
1204
+					if (! $TKT->delete_by_ID($TKT_ID)) {
1205
+						$success = 0;
1206
+					}
1207
+				} else {
1208
+					if (! $TKT->restore_by_ID($TKT_ID)) {
1209
+						$success = 0;
1210
+					}
1211
+				}
1212
+			}
1213
+		} else {
1214
+			//grab single id and trash
1215
+			$TKT_ID = absint($this->_req_data['TKT_ID']);
1216
+			if ($trash) {
1217
+				if (! $TKT->delete_by_ID($TKT_ID)) {
1218
+					$success = 0;
1219
+				}
1220
+			} else {
1221
+				if (! $TKT->restore_by_ID($TKT_ID)) {
1222
+					$success = 0;
1223
+				}
1224
+			}
1225
+		}
1226
+		$action_desc = $trash ? 'moved to the trash' : 'restored';
1227
+		$query_args  = array(
1228
+			'action' => 'ticket_list_table',
1229
+			'status' => $trash ? '' : 'trashed',
1230
+		);
1231
+		$this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * Handles trashing default ticket.
1237
+	 */
1238
+	protected function _delete_ticket()
1239
+	{
1240
+		$success = 1;
1241
+		//checkboxes?
1242
+		if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1243
+			//if array has more than one element then success message should be plural
1244
+			$success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1245
+			//cycle thru the boxes
1246
+			while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1247
+				//delete
1248
+				if (! $this->_delete_the_ticket($TKT_ID)) {
1249
+					$success = 0;
1250
+				}
1251
+			}
1252
+		} else {
1253
+			//grab single id and trash
1254
+			$TKT_ID = absint($this->_req_data['TKT_ID']);
1255
+			if (! $this->_delete_the_ticket($TKT_ID)) {
1256
+				$success = 0;
1257
+			}
1258
+		}
1259
+		$action_desc = 'deleted';
1260
+		$query_args  = array(
1261
+			'action' => 'ticket_list_table',
1262
+			'status' => 'trashed',
1263
+		);
1264
+		//fail safe.  If the default ticket count === 1 then we need to redirect to event overview.
1265
+		if (EEM_Ticket::instance()->count_deleted_and_undeleted(
1266
+			array(array('TKT_is_default' => 1)),
1267
+			'TKT_ID',
1268
+			true
1269
+		)
1270
+		) {
1271
+			$query_args = array();
1272
+		}
1273
+		$this->_redirect_after_action($success, 'Tickets', $action_desc, $query_args);
1274
+	}
1275
+
1276
+
1277
+	/**
1278
+	 * @param int $TKT_ID
1279
+	 * @return bool|int
1280
+	 * @throws EE_Error
1281
+	 */
1282
+	protected function _delete_the_ticket($TKT_ID)
1283
+	{
1284
+		$tkt = EEM_Ticket::instance()->get_one_by_ID($TKT_ID);
1285
+		$tkt->_remove_relations('Datetime');
1286
+		//delete all related prices first
1287
+		$tkt->delete_related_permanently('Price');
1288
+		return $tkt->delete_permanently();
1289
+	}
1290 1290
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -27,10 +27,10 @@  discard block
 block discarded – undo
27 27
     public function __construct($routing = true)
28 28
     {
29 29
         parent::__construct($routing);
30
-        if (! defined('EVENTS_CAF_TEMPLATE_PATH')) {
31
-            define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND . 'events/templates/');
32
-            define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND . 'events/assets/');
33
-            define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL . 'events/assets/');
30
+        if ( ! defined('EVENTS_CAF_TEMPLATE_PATH')) {
31
+            define('EVENTS_CAF_TEMPLATE_PATH', EE_CORE_CAF_ADMIN_EXTEND.'events/templates/');
32
+            define('EVENTS_CAF_ASSETS', EE_CORE_CAF_ADMIN_EXTEND.'events/assets/');
33
+            define('EVENTS_CAF_ASSETS_URL', EE_CORE_CAF_ADMIN_EXTEND_URL.'events/assets/');
34 34
         }
35 35
     }
36 36
 
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
      */
41 41
     protected function _extend_page_config()
42 42
     {
43
-        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND . 'events';
43
+        $this->_admin_base_path = EE_CORE_CAF_ADMIN_EXTEND.'events';
44 44
         //is there a evt_id in the request?
45 45
         $evt_id = ! empty($this->_req_data['EVT_ID']) && ! is_array($this->_req_data['EVT_ID'])
46 46
             ? $this->_req_data['EVT_ID']
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
             'help_tour'     => array('Templates_Help_Tour'),
174 174
             'require_nonce' => false,
175 175
         );
176
-        $this->_page_config                   = array_merge($this->_page_config, $new_page_config);
176
+        $this->_page_config = array_merge($this->_page_config, $new_page_config);
177 177
         //add filters and actions
178 178
         //modifying _views
179 179
         add_filter(
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
          * check whether count of tickets is approaching the potential
247 247
          * limits for the server.
248 248
          */
249
-        if (! empty($data['input_count'])) {
249
+        if ( ! empty($data['input_count'])) {
250 250
             $response['max_input_vars_check'] = EE_Registry::instance()->CFG->environment->max_input_vars_limit_check(
251 251
                 $data['input_count']
252 252
             );
@@ -275,12 +275,12 @@  discard block
 block discarded – undo
275 275
     {
276 276
         $return = parent::extra_permalink_field_buttons($return, $id, $new_title, $new_slug);
277 277
         //make sure this is only when editing
278
-        if (! empty($id)) {
279
-            $href   = EE_Admin_Page::add_query_args_and_nonce(
278
+        if ( ! empty($id)) {
279
+            $href = EE_Admin_Page::add_query_args_and_nonce(
280 280
                 array('action' => 'duplicate_event', 'EVT_ID' => $id),
281 281
                 $this->_admin_base_url
282 282
             );
283
-            $title  = esc_attr__('Duplicate Event', 'event_espresso');
283
+            $title = esc_attr__('Duplicate Event', 'event_espresso');
284 284
             $return .= '<a href="'
285 285
                        . $href
286 286
                        . '" title="'
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
     {
328 328
         wp_register_script(
329 329
             'ee-event-editor-heartbeat',
330
-            EVENTS_CAF_ASSETS_URL . 'event-editor-heartbeat.js',
330
+            EVENTS_CAF_ASSETS_URL.'event-editor-heartbeat.js',
331 331
             array('ee_admin_js', 'heartbeat'),
332 332
             EVENT_ESPRESSO_VERSION,
333 333
             true
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
     public function add_additional_datetime_button($template, $template_args)
351 351
     {
352 352
         return EEH_Template::display_template(
353
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_add_additional_time.template.php',
353
+            EVENTS_CAF_TEMPLATE_PATH.'event_datetime_add_additional_time.template.php',
354 354
             $template_args,
355 355
             true
356 356
         );
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
     public function add_datetime_clone_button($template, $template_args)
368 368
     {
369 369
         return EEH_Template::display_template(
370
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_metabox_clone_button.template.php',
370
+            EVENTS_CAF_TEMPLATE_PATH.'event_datetime_metabox_clone_button.template.php',
371 371
             $template_args,
372 372
             true
373 373
         );
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
     public function datetime_timezones_template($template, $template_args)
385 385
     {
386 386
         return EEH_Template::display_template(
387
-            EVENTS_CAF_TEMPLATE_PATH . 'event_datetime_timezones.template.php',
387
+            EVENTS_CAF_TEMPLATE_PATH.'event_datetime_timezones.template.php',
388 388
             $template_args,
389 389
             true
390 390
         );
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
     protected function _set_list_table_views_default()
398 398
     {
399 399
         parent::_set_list_table_views_default();
400
-        $new_views    = array(
400
+        $new_views = array(
401 401
             'today' => array(
402 402
                 'slug'        => 'today',
403 403
                 'label'       => esc_html__('Today', 'event_espresso'),
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
     {
503 503
         // first make sure the ID for the event is in the request.
504 504
         //  If it isn't then we need to bail and redirect back to overview list table (cause how did we get here?)
505
-        if (! isset($this->_req_data['EVT_ID'])) {
505
+        if ( ! isset($this->_req_data['EVT_ID'])) {
506 506
             EE_Error::add_error(
507 507
                 esc_html__(
508 508
                     'In order to duplicate an event an Event ID is required.  None was given.',
@@ -517,7 +517,7 @@  discard block
 block discarded – undo
517 517
         }
518 518
         //k we've got EVT_ID so let's use that to get the event we'll duplicate
519 519
         $orig_event = EEM_Event::instance()->get_one_by_ID($this->_req_data['EVT_ID']);
520
-        if (! $orig_event instanceof EE_Event) {
520
+        if ( ! $orig_event instanceof EE_Event) {
521 521
             throw new EE_Error(
522 522
                 sprintf(
523 523
                     esc_html__('An EE_Event object could not be retrieved for the given ID (%s)', 'event_espresso'),
@@ -533,7 +533,7 @@  discard block
 block discarded – undo
533 533
         $orig_ven = $orig_event->get_many_related('Venue');
534 534
         //reset the ID and modify other details to make it clear this is a dupe
535 535
         $new_event->set('EVT_ID', 0);
536
-        $new_name = $new_event->name() . ' ' . esc_html__('**DUPLICATE**', 'event_espresso');
536
+        $new_name = $new_event->name().' '.esc_html__('**DUPLICATE**', 'event_espresso');
537 537
         $new_event->set('EVT_name', $new_name);
538 538
         $new_event->set(
539 539
             'EVT_slug',
@@ -562,7 +562,7 @@  discard block
 block discarded – undo
562 562
             'Question_Group',
563 563
             array(array('Event_Question_Group.EQG_primary' => 1))
564 564
         );
565
-        if (! empty($orig_primary_qgs)) {
565
+        if ( ! empty($orig_primary_qgs)) {
566 566
             foreach ($orig_primary_qgs as $id => $obj) {
567 567
                 if ($obj instanceof EE_Question_Group) {
568 568
                     $new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 1));
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
             'Question_Group',
575 575
             array(array('Event_Question_Group.EQG_primary' => 0))
576 576
         );
577
-        if (! empty($orig_additional_qgs)) {
577
+        if ( ! empty($orig_additional_qgs)) {
578 578
             foreach ($orig_additional_qgs as $id => $obj) {
579 579
                 if ($obj instanceof EE_Question_Group) {
580 580
                     $new_event->_add_relation_to($obj, 'Question_Group', array('EQG_primary' => 0));
@@ -587,7 +587,7 @@  discard block
 block discarded – undo
587 587
         //k now that we have the new event saved we can loop through the datetimes and start adding relations.
588 588
         $cloned_tickets = array();
589 589
         foreach ($orig_datetimes as $orig_dtt) {
590
-            if (! $orig_dtt instanceof EE_Datetime) {
590
+            if ( ! $orig_dtt instanceof EE_Datetime) {
591 591
                 continue;
592 592
             }
593 593
             $new_dtt   = clone $orig_dtt;
@@ -600,9 +600,9 @@  discard block
 block discarded – undo
600 600
             $new_event->_add_relation_to($new_dtt, 'Datetime');
601 601
             $new_event->save();
602 602
             //now let's get the ticket relations setup.
603
-            foreach ((array)$orig_tkts as $orig_tkt) {
603
+            foreach ((array) $orig_tkts as $orig_tkt) {
604 604
                 //it's possible a datetime will have no tickets so let's verify we HAVE a ticket first.
605
-                if (! $orig_tkt instanceof EE_Ticket) {
605
+                if ( ! $orig_tkt instanceof EE_Ticket) {
606 606
                     continue;
607 607
                 }
608 608
                 //is this ticket archived?  If it is then let's skip
@@ -722,8 +722,8 @@  discard block
 block discarded – undo
722 722
             array('action' => 'sample_export_file'),
723 723
             $this->_admin_base_url
724 724
         );
725
-        $content                                    = EEH_Template::display_template(
726
-            EVENTS_CAF_TEMPLATE_PATH . 'import_page.template.php',
725
+        $content = EEH_Template::display_template(
726
+            EVENTS_CAF_TEMPLATE_PATH.'import_page.template.php',
727 727
             $this->_template_args,
728 728
             true
729 729
         );
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
      */
741 741
     protected function _import_events()
742 742
     {
743
-        require_once(EE_CLASSES . 'EE_Import.class.php');
743
+        require_once(EE_CLASSES.'EE_Import.class.php');
744 744
         $success = EE_Import::instance()->import();
745 745
         $this->_redirect_after_action($success, 'Import File', 'ran', array('action' => 'import_page'), true);
746 746
     }
@@ -768,9 +768,9 @@  discard block
 block discarded – undo
768 768
             'action' => 'all_event_data',
769 769
             'EVT_ID' => $event_ids,
770 770
         );
771
-        $this->_req_data  = array_merge($this->_req_data, $new_request_args);
772
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
773
-            require_once(EE_CLASSES . 'EE_Export.class.php');
771
+        $this->_req_data = array_merge($this->_req_data, $new_request_args);
772
+        if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
773
+            require_once(EE_CLASSES.'EE_Export.class.php');
774 774
             $EE_Export = EE_Export::instance($this->_req_data);
775 775
             $EE_Export->export();
776 776
         }
@@ -790,9 +790,9 @@  discard block
 block discarded – undo
790 790
             'action'       => 'categories',
791 791
             'category_ids' => $this->_req_data['EVT_CAT_ID'],
792 792
         );
793
-        $this->_req_data  = array_merge($this->_req_data, $new_request_args);
794
-        if (is_readable(EE_CLASSES . 'EE_Export.class.php')) {
795
-            require_once(EE_CLASSES . 'EE_Export.class.php');
793
+        $this->_req_data = array_merge($this->_req_data, $new_request_args);
794
+        if (is_readable(EE_CLASSES.'EE_Export.class.php')) {
795
+            require_once(EE_CLASSES.'EE_Export.class.php');
796 796
             $EE_Export = EE_Export::instance($this->_req_data);
797 797
             $EE_Export->export();
798 798
         }
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         $this->_set_add_edit_form_tags('update_template_settings');
830 830
         $this->_set_publish_post_box_vars(null, false, false, null, false);
831 831
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
832
-            EVENTS_CAF_TEMPLATE_PATH . 'template_settings.template.php',
832
+            EVENTS_CAF_TEMPLATE_PATH.'template_settings.template.php',
833 833
             $this->_template_args,
834 834
             true
835 835
         );
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
         );
871 871
         if (EE_Registry::instance()->CFG->core->event_cpt_slug != $old_slug) {
872 872
             /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
873
-            $rewrite_rules =  LoaderFactory::getLoader()->getShared(
873
+            $rewrite_rules = LoaderFactory::getLoader()->getShared(
874 874
                 'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
875 875
             );
876 876
             $rewrite_rules->flush();
@@ -909,11 +909,11 @@  discard block
 block discarded – undo
909 909
      */
910 910
     public function registration_options_meta_box()
911 911
     {
912
-        $yes_no_values                                    = array(
912
+        $yes_no_values = array(
913 913
             array('id' => true, 'text' => esc_html__('Yes', 'event_espresso')),
914 914
             array('id' => false, 'text' => esc_html__('No', 'event_espresso')),
915 915
         );
916
-        $default_reg_status_values                        = EEM_Registration::reg_status_array(
916
+        $default_reg_status_values = EEM_Registration::reg_status_array(
917 917
             array(
918 918
                 EEM_Registration::status_id_cancelled,
919 919
                 EEM_Registration::status_id_declined,
@@ -930,12 +930,12 @@  discard block
 block discarded – undo
930 930
             $default_reg_status_values,
931 931
             $this->_cpt_model_obj->default_registration_status()
932 932
         );
933
-        $template_args['display_description']             = EEH_Form_Fields::select_input(
933
+        $template_args['display_description'] = EEH_Form_Fields::select_input(
934 934
             'display_desc',
935 935
             $yes_no_values,
936 936
             $this->_cpt_model_obj->display_description()
937 937
         );
938
-        $template_args['display_ticket_selector']         = EEH_Form_Fields::select_input(
938
+        $template_args['display_ticket_selector'] = EEH_Form_Fields::select_input(
939 939
             'display_ticket_selector',
940 940
             $yes_no_values,
941 941
             $this->_cpt_model_obj->display_ticket_selector(),
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
             $default_reg_status_values
957 957
         );
958 958
         EEH_Template::display_template(
959
-            EVENTS_CAF_TEMPLATE_PATH . 'event_registration_options.template.php',
959
+            EVENTS_CAF_TEMPLATE_PATH.'event_registration_options.template.php',
960 960
             $template_args
961 961
         );
962 962
     }
@@ -1060,13 +1060,13 @@  discard block
 block discarded – undo
1060 1060
     {
1061 1061
         $start = EEM_Datetime::instance()->convert_datetime_for_query(
1062 1062
             'DTT_EVT_start',
1063
-            date('Y-m-d') . ' 00:00:00',
1063
+            date('Y-m-d').' 00:00:00',
1064 1064
             'Y-m-d H:i:s',
1065 1065
             'UTC'
1066 1066
         );
1067
-        $end   = EEM_Datetime::instance()->convert_datetime_for_query(
1067
+        $end = EEM_Datetime::instance()->convert_datetime_for_query(
1068 1068
             'DTT_EVT_start',
1069
-            date('Y-m-d') . ' 23:59:59',
1069
+            date('Y-m-d').' 23:59:59',
1070 1070
             'Y-m-d H:i:s',
1071 1071
             'UTC'
1072 1072
         );
@@ -1093,13 +1093,13 @@  discard block
 block discarded – undo
1093 1093
         $days_this_month = date('t');
1094 1094
         $start           = EEM_Datetime::instance()->convert_datetime_for_query(
1095 1095
             'DTT_EVT_start',
1096
-            $this_year_r . '-' . $this_month_r . '-01 00:00:00',
1096
+            $this_year_r.'-'.$this_month_r.'-01 00:00:00',
1097 1097
             'Y-m-d H:i:s',
1098 1098
             'UTC'
1099 1099
         );
1100
-        $end             = EEM_Datetime::instance()->convert_datetime_for_query(
1100
+        $end = EEM_Datetime::instance()->convert_datetime_for_query(
1101 1101
             'DTT_EVT_start',
1102
-            $this_year_r . '-' . $this_month_r . '-' . $days_this_month . ' 23:59:59',
1102
+            $this_year_r.'-'.$this_month_r.'-'.$days_this_month.' 23:59:59',
1103 1103
             'Y-m-d H:i:s',
1104 1104
             'UTC'
1105 1105
         );
@@ -1166,7 +1166,7 @@  discard block
 block discarded – undo
1166 1166
         $offset       = ($current_page - 1) * $per_page;
1167 1167
         $limit        = array($offset, $per_page);
1168 1168
         if (isset($this->_req_data['s'])) {
1169
-            $sstr         = '%' . $this->_req_data['s'] . '%';
1169
+            $sstr         = '%'.$this->_req_data['s'].'%';
1170 1170
             $_where['OR'] = array(
1171 1171
                 'TKT_name'        => array('LIKE', $sstr),
1172 1172
                 'TKT_description' => array('LIKE', $sstr),
@@ -1195,17 +1195,17 @@  discard block
 block discarded – undo
1195 1195
         $success = 1;
1196 1196
         $TKT     = EEM_Ticket::instance();
1197 1197
         //checkboxes?
1198
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1198
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1199 1199
             //if array has more than one element then success message should be plural
1200 1200
             $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1201 1201
             //cycle thru the boxes
1202 1202
             while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1203 1203
                 if ($trash) {
1204
-                    if (! $TKT->delete_by_ID($TKT_ID)) {
1204
+                    if ( ! $TKT->delete_by_ID($TKT_ID)) {
1205 1205
                         $success = 0;
1206 1206
                     }
1207 1207
                 } else {
1208
-                    if (! $TKT->restore_by_ID($TKT_ID)) {
1208
+                    if ( ! $TKT->restore_by_ID($TKT_ID)) {
1209 1209
                         $success = 0;
1210 1210
                     }
1211 1211
                 }
@@ -1214,11 +1214,11 @@  discard block
 block discarded – undo
1214 1214
             //grab single id and trash
1215 1215
             $TKT_ID = absint($this->_req_data['TKT_ID']);
1216 1216
             if ($trash) {
1217
-                if (! $TKT->delete_by_ID($TKT_ID)) {
1217
+                if ( ! $TKT->delete_by_ID($TKT_ID)) {
1218 1218
                     $success = 0;
1219 1219
                 }
1220 1220
             } else {
1221
-                if (! $TKT->restore_by_ID($TKT_ID)) {
1221
+                if ( ! $TKT->restore_by_ID($TKT_ID)) {
1222 1222
                     $success = 0;
1223 1223
                 }
1224 1224
             }
@@ -1239,20 +1239,20 @@  discard block
 block discarded – undo
1239 1239
     {
1240 1240
         $success = 1;
1241 1241
         //checkboxes?
1242
-        if (! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1242
+        if ( ! empty($this->_req_data['checkbox']) && is_array($this->_req_data['checkbox'])) {
1243 1243
             //if array has more than one element then success message should be plural
1244 1244
             $success = count($this->_req_data['checkbox']) > 1 ? 2 : 1;
1245 1245
             //cycle thru the boxes
1246 1246
             while (list($TKT_ID, $value) = each($this->_req_data['checkbox'])) {
1247 1247
                 //delete
1248
-                if (! $this->_delete_the_ticket($TKT_ID)) {
1248
+                if ( ! $this->_delete_the_ticket($TKT_ID)) {
1249 1249
                     $success = 0;
1250 1250
                 }
1251 1251
             }
1252 1252
         } else {
1253 1253
             //grab single id and trash
1254 1254
             $TKT_ID = absint($this->_req_data['TKT_ID']);
1255
-            if (! $this->_delete_the_ticket($TKT_ID)) {
1255
+            if ( ! $this->_delete_the_ticket($TKT_ID)) {
1256 1256
                 $success = 0;
1257 1257
             }
1258 1258
         }
Please login to merge, or discard this patch.
core/EE_System.core.php 1 patch
Indentation   +1289 added lines, -1289 removed lines patch added patch discarded remove patch
@@ -32,1295 +32,1295 @@
 block discarded – undo
32 32
 {
33 33
 
34 34
 
35
-    /**
36
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
37
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
38
-     */
39
-    const req_type_normal = 0;
40
-
41
-    /**
42
-     * Indicates this is a brand new installation of EE so we should install
43
-     * tables and default data etc
44
-     */
45
-    const req_type_new_activation = 1;
46
-
47
-    /**
48
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
49
-     * and we just exited maintenance mode). We MUST check the database is setup properly
50
-     * and that default data is setup too
51
-     */
52
-    const req_type_reactivation = 2;
53
-
54
-    /**
55
-     * indicates that EE has been upgraded since its previous request.
56
-     * We may have data migration scripts to call and will want to trigger maintenance mode
57
-     */
58
-    const req_type_upgrade = 3;
59
-
60
-    /**
61
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
62
-     */
63
-    const req_type_downgrade = 4;
64
-
65
-    /**
66
-     * @deprecated since version 4.6.0.dev.006
67
-     * Now whenever a new_activation is detected the request type is still just
68
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
69
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
70
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
71
-     * (Specifically, when the migration manager indicates migrations are finished
72
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
73
-     */
74
-    const req_type_activation_but_not_installed = 5;
75
-
76
-    /**
77
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
78
-     */
79
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
80
-
81
-
82
-    /**
83
-     * @var EE_System $_instance
84
-     */
85
-    private static $_instance;
86
-
87
-    /**
88
-     * @var EE_Registry $registry
89
-     */
90
-    private $registry;
91
-
92
-    /**
93
-     * @var LoaderInterface $loader
94
-     */
95
-    private $loader;
96
-
97
-    /**
98
-     * @var EE_Capabilities $capabilities
99
-     */
100
-    private $capabilities;
101
-
102
-    /**
103
-     * @var RequestInterface $request
104
-     */
105
-    private $request;
106
-
107
-    /**
108
-     * @var EE_Maintenance_Mode $maintenance_mode
109
-     */
110
-    private $maintenance_mode;
111
-
112
-    /**
113
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
114
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
115
-     *
116
-     * @var int $_req_type
117
-     */
118
-    private $_req_type;
119
-
120
-    /**
121
-     * Whether or not there was a non-micro version change in EE core version during this request
122
-     *
123
-     * @var boolean $_major_version_change
124
-     */
125
-    private $_major_version_change = false;
126
-
127
-    /**
128
-     * A Context DTO dedicated solely to identifying the current request type.
129
-     *
130
-     * @var RequestTypeContextCheckerInterface $request_type
131
-     */
132
-    private $request_type;
133
-
134
-
135
-
136
-    /**
137
-     * @singleton method used to instantiate class object
138
-     * @param EE_Registry|null         $registry
139
-     * @param LoaderInterface|null     $loader
140
-     * @param RequestInterface|null          $request
141
-     * @param EE_Maintenance_Mode|null $maintenance_mode
142
-     * @return EE_System
143
-     */
144
-    public static function instance(
145
-        EE_Registry $registry = null,
146
-        LoaderInterface $loader = null,
147
-        RequestInterface $request = null,
148
-        EE_Maintenance_Mode $maintenance_mode = null
149
-    ) {
150
-        // check if class object is instantiated
151
-        if (! self::$_instance instanceof EE_System) {
152
-            self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
153
-        }
154
-        return self::$_instance;
155
-    }
156
-
157
-
158
-
159
-    /**
160
-     * resets the instance and returns it
161
-     *
162
-     * @return EE_System
163
-     */
164
-    public static function reset()
165
-    {
166
-        self::$_instance->_req_type = null;
167
-        //make sure none of the old hooks are left hanging around
168
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
169
-        //we need to reset the migration manager in order for it to detect DMSs properly
170
-        EE_Data_Migration_Manager::reset();
171
-        self::instance()->detect_activations_or_upgrades();
172
-        self::instance()->perform_activations_upgrades_and_migrations();
173
-        return self::instance();
174
-    }
175
-
176
-
177
-
178
-    /**
179
-     * sets hooks for running rest of system
180
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
181
-     * starting EE Addons from any other point may lead to problems
182
-     *
183
-     * @param EE_Registry         $registry
184
-     * @param LoaderInterface     $loader
185
-     * @param RequestInterface          $request
186
-     * @param EE_Maintenance_Mode $maintenance_mode
187
-     */
188
-    private function __construct(
189
-        EE_Registry $registry,
190
-        LoaderInterface $loader,
191
-        RequestInterface $request,
192
-        EE_Maintenance_Mode $maintenance_mode
193
-    ) {
194
-        $this->registry         = $registry;
195
-        $this->loader           = $loader;
196
-        $this->request          = $request;
197
-        $this->maintenance_mode = $maintenance_mode;
198
-        do_action('AHEE__EE_System__construct__begin', $this);
199
-        add_action(
200
-            'AHEE__EE_Bootstrap__load_espresso_addons',
201
-            array($this, 'loadCapabilities'),
202
-            5
203
-        );
204
-        add_action(
205
-            'AHEE__EE_Bootstrap__load_espresso_addons',
206
-            array($this, 'loadCommandBus'),
207
-            7
208
-        );
209
-        add_action(
210
-            'AHEE__EE_Bootstrap__load_espresso_addons',
211
-            array($this, 'loadPluginApi'),
212
-            9
213
-        );
214
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
215
-        add_action(
216
-            'AHEE__EE_Bootstrap__load_espresso_addons',
217
-            array($this, 'load_espresso_addons')
218
-        );
219
-        // when an ee addon is activated, we want to call the core hook(s) again
220
-        // because the newly-activated addon didn't get a chance to run at all
221
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
222
-        // detect whether install or upgrade
223
-        add_action(
224
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
225
-            array($this, 'detect_activations_or_upgrades'),
226
-            3
227
-        );
228
-        // load EE_Config, EE_Textdomain, etc
229
-        add_action(
230
-            'AHEE__EE_Bootstrap__load_core_configuration',
231
-            array($this, 'load_core_configuration'),
232
-            5
233
-        );
234
-        // load EE_Config, EE_Textdomain, etc
235
-        add_action(
236
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
237
-            array($this, 'register_shortcodes_modules_and_widgets'),
238
-            7
239
-        );
240
-        // you wanna get going? I wanna get going... let's get going!
241
-        add_action(
242
-            'AHEE__EE_Bootstrap__brew_espresso',
243
-            array($this, 'brew_espresso'),
244
-            9
245
-        );
246
-        //other housekeeping
247
-        //exclude EE critical pages from wp_list_pages
248
-        add_filter(
249
-            'wp_list_pages_excludes',
250
-            array($this, 'remove_pages_from_wp_list_pages'),
251
-            10
252
-        );
253
-        // ALL EE Addons should use the following hook point to attach their initial setup too
254
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
255
-        do_action('AHEE__EE_System__construct__complete', $this);
256
-    }
257
-
258
-
259
-    /**
260
-     * load and setup EE_Capabilities
261
-     *
262
-     * @return void
263
-     * @throws EE_Error
264
-     */
265
-    public function loadCapabilities()
266
-    {
267
-        $this->capabilities = $this->loader->getShared('EE_Capabilities');
268
-        add_action(
269
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
270
-            function ()
271
-            {
272
-                LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
273
-            }
274
-        );
275
-    }
276
-
277
-
278
-
279
-    /**
280
-     * create and cache the CommandBus, and also add middleware
281
-     * The CapChecker middleware requires the use of EE_Capabilities
282
-     * which is why we need to load the CommandBus after Caps are set up
283
-     *
284
-     * @return void
285
-     * @throws EE_Error
286
-     */
287
-    public function loadCommandBus()
288
-    {
289
-        $this->loader->getShared(
290
-            'CommandBusInterface',
291
-            array(
292
-                null,
293
-                apply_filters(
294
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
295
-                    array(
296
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
297
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
298
-                    )
299
-                ),
300
-            )
301
-        );
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * @return void
308
-     * @throws EE_Error
309
-     */
310
-    public function loadPluginApi()
311
-    {
312
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
313
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
314
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
315
-        $this->loader->getShared('EE_Request_Handler');
316
-    }
317
-
318
-
319
-    /**
320
-     * @param string $addon_name
321
-     * @param string $version_constant
322
-     * @param string $min_version_required
323
-     * @param string $load_callback
324
-     * @param string $plugin_file_constant
325
-     * @return void
326
-     */
327
-    private function deactivateIncompatibleAddon(
328
-        $addon_name,
329
-        $version_constant,
330
-        $min_version_required,
331
-        $load_callback,
332
-        $plugin_file_constant
333
-    ) {
334
-        if (! defined($version_constant)) {
335
-            return;
336
-        }
337
-        $addon_version = constant($version_constant);
338
-        if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
339
-            remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
340
-            if (! function_exists('deactivate_plugins')) {
341
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
342
-            }
343
-            deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
344
-            unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
345
-            EE_Error::add_error(
346
-                sprintf(
347
-                    esc_html__(
348
-                        'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
349
-                        'event_espresso'
350
-                    ),
351
-                    $addon_name,
352
-                    $min_version_required
353
-                ),
354
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
355
-            );
356
-            EE_Error::get_notices(false, true);
357
-        }
358
-    }
359
-
360
-
361
-    /**
362
-     * load_espresso_addons
363
-     * allow addons to load first so that they can set hooks for running DMS's, etc
364
-     * this is hooked into both:
365
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
366
-     *        which runs during the WP 'plugins_loaded' action at priority 5
367
-     *    and the WP 'activate_plugin' hook point
368
-     *
369
-     * @access public
370
-     * @return void
371
-     */
372
-    public function load_espresso_addons()
373
-    {
374
-        $this->deactivateIncompatibleAddon(
375
-            'Wait Lists',
376
-            'EE_WAIT_LISTS_VERSION',
377
-            '1.0.0.beta.074',
378
-            'load_espresso_wait_lists',
379
-            'EE_WAIT_LISTS_PLUGIN_FILE'
380
-        );
381
-        $this->deactivateIncompatibleAddon(
382
-            'Automated Upcoming Event Notifications',
383
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
384
-            '1.0.0.beta.091',
385
-            'load_espresso_automated_upcoming_event_notification',
386
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
387
-        );
388
-        do_action('AHEE__EE_System__load_espresso_addons');
389
-        //if the WP API basic auth plugin isn't already loaded, load it now.
390
-        //We want it for mobile apps. Just include the entire plugin
391
-        //also, don't load the basic auth when a plugin is getting activated, because
392
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
393
-        //and causes a fatal error
394
-        if (
395
-            $this->request->getRequestParam('activate') !== 'true'
396
-            && ! function_exists('json_basic_auth_handler')
397
-            && ! function_exists('json_basic_auth_error')
398
-            && ! in_array(
399
-                $this->request->getRequestParam('action'),
400
-                array('activate', 'activate-selected'),
401
-                true
402
-            )
403
-        ) {
404
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
405
-        }
406
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
407
-    }
408
-
409
-
410
-
411
-    /**
412
-     * detect_activations_or_upgrades
413
-     * Checks for activation or upgrade of core first;
414
-     * then also checks if any registered addons have been activated or upgraded
415
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
416
-     * which runs during the WP 'plugins_loaded' action at priority 3
417
-     *
418
-     * @access public
419
-     * @return void
420
-     */
421
-    public function detect_activations_or_upgrades()
422
-    {
423
-        //first off: let's make sure to handle core
424
-        $this->detect_if_activation_or_upgrade();
425
-        foreach ($this->registry->addons as $addon) {
426
-            if ($addon instanceof EE_Addon) {
427
-                //detect teh request type for that addon
428
-                $addon->detect_activation_or_upgrade();
429
-            }
430
-        }
431
-    }
432
-
433
-
434
-
435
-    /**
436
-     * detect_if_activation_or_upgrade
437
-     * Takes care of detecting whether this is a brand new install or code upgrade,
438
-     * and either setting up the DB or setting up maintenance mode etc.
439
-     *
440
-     * @access public
441
-     * @return void
442
-     */
443
-    public function detect_if_activation_or_upgrade()
444
-    {
445
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
446
-        // check if db has been updated, or if its a brand-new installation
447
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
448
-        $request_type       = $this->detect_req_type($espresso_db_update);
449
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
450
-        switch ($request_type) {
451
-            case EE_System::req_type_new_activation:
452
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
453
-                $this->_handle_core_version_change($espresso_db_update);
454
-                break;
455
-            case EE_System::req_type_reactivation:
456
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
457
-                $this->_handle_core_version_change($espresso_db_update);
458
-                break;
459
-            case EE_System::req_type_upgrade:
460
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
461
-                //migrations may be required now that we've upgraded
462
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
463
-                $this->_handle_core_version_change($espresso_db_update);
464
-                //				echo "done upgrade";die;
465
-                break;
466
-            case EE_System::req_type_downgrade:
467
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
468
-                //its possible migrations are no longer required
469
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
470
-                $this->_handle_core_version_change($espresso_db_update);
471
-                break;
472
-            case EE_System::req_type_normal:
473
-            default:
474
-                break;
475
-        }
476
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
477
-    }
478
-
479
-
480
-
481
-    /**
482
-     * Updates the list of installed versions and sets hooks for
483
-     * initializing the database later during the request
484
-     *
485
-     * @param array $espresso_db_update
486
-     */
487
-    private function _handle_core_version_change($espresso_db_update)
488
-    {
489
-        $this->update_list_of_installed_versions($espresso_db_update);
490
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
491
-        add_action(
492
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
493
-            array($this, 'initialize_db_if_no_migrations_required')
494
-        );
495
-    }
496
-
497
-
498
-
499
-    /**
500
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
501
-     * information about what versions of EE have been installed and activated,
502
-     * NOT necessarily the state of the database
503
-     *
504
-     * @param mixed $espresso_db_update           the value of the WordPress option.
505
-     *                                            If not supplied, fetches it from the options table
506
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
507
-     */
508
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
509
-    {
510
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
511
-        if (! $espresso_db_update) {
512
-            $espresso_db_update = get_option('espresso_db_update');
513
-        }
514
-        // check that option is an array
515
-        if (! is_array($espresso_db_update)) {
516
-            // if option is FALSE, then it never existed
517
-            if ($espresso_db_update === false) {
518
-                // make $espresso_db_update an array and save option with autoload OFF
519
-                $espresso_db_update = array();
520
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
521
-            } else {
522
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
523
-                $espresso_db_update = array($espresso_db_update => array());
524
-                update_option('espresso_db_update', $espresso_db_update);
525
-            }
526
-        } else {
527
-            $corrected_db_update = array();
528
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
529
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
530
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
531
-                    //the key is an int, and the value IS NOT an array
532
-                    //so it must be numerically-indexed, where values are versions installed...
533
-                    //fix it!
534
-                    $version_string                         = $should_be_array;
535
-                    $corrected_db_update[ $version_string ] = array('unknown-date');
536
-                } else {
537
-                    //ok it checks out
538
-                    $corrected_db_update[ $should_be_version_string ] = $should_be_array;
539
-                }
540
-            }
541
-            $espresso_db_update = $corrected_db_update;
542
-            update_option('espresso_db_update', $espresso_db_update);
543
-        }
544
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
545
-        return $espresso_db_update;
546
-    }
547
-
548
-
549
-
550
-    /**
551
-     * Does the traditional work of setting up the plugin's database and adding default data.
552
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
553
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
554
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
555
-     * so that it will be done when migrations are finished
556
-     *
557
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
558
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
559
-     *                                       This is a resource-intensive job
560
-     *                                       so we prefer to only do it when necessary
561
-     * @return void
562
-     * @throws EE_Error
563
-     */
564
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
565
-    {
566
-        $request_type = $this->detect_req_type();
567
-        //only initialize system if we're not in maintenance mode.
568
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
569
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
570
-            $rewrite_rules = $this->loader->getShared(
571
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
572
-            );
573
-            $rewrite_rules->flush();
574
-            if ($verify_schema) {
575
-                EEH_Activation::initialize_db_and_folders();
576
-            }
577
-            EEH_Activation::initialize_db_content();
578
-            EEH_Activation::system_initialization();
579
-            if ($initialize_addons_too) {
580
-                $this->initialize_addons();
581
-            }
582
-        } else {
583
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
584
-        }
585
-        if ($request_type === EE_System::req_type_new_activation
586
-            || $request_type === EE_System::req_type_reactivation
587
-            || (
588
-                $request_type === EE_System::req_type_upgrade
589
-                && $this->is_major_version_change()
590
-            )
591
-        ) {
592
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
593
-        }
594
-    }
595
-
596
-
597
-
598
-    /**
599
-     * Initializes the db for all registered addons
600
-     *
601
-     * @throws EE_Error
602
-     */
603
-    public function initialize_addons()
604
-    {
605
-        //foreach registered addon, make sure its db is up-to-date too
606
-        foreach ($this->registry->addons as $addon) {
607
-            if ($addon instanceof EE_Addon) {
608
-                $addon->initialize_db_if_no_migrations_required();
609
-            }
610
-        }
611
-    }
612
-
613
-
614
-
615
-    /**
616
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
617
-     *
618
-     * @param    array  $version_history
619
-     * @param    string $current_version_to_add version to be added to the version history
620
-     * @return    boolean success as to whether or not this option was changed
621
-     */
622
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
623
-    {
624
-        if (! $version_history) {
625
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
626
-        }
627
-        if ($current_version_to_add === null) {
628
-            $current_version_to_add = espresso_version();
629
-        }
630
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
631
-        // re-save
632
-        return update_option('espresso_db_update', $version_history);
633
-    }
634
-
635
-
636
-
637
-    /**
638
-     * Detects if the current version indicated in the has existed in the list of
639
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
640
-     *
641
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
642
-     *                                  If not supplied, fetches it from the options table.
643
-     *                                  Also, caches its result so later parts of the code can also know whether
644
-     *                                  there's been an update or not. This way we can add the current version to
645
-     *                                  espresso_db_update, but still know if this is a new install or not
646
-     * @return int one of the constants on EE_System::req_type_
647
-     */
648
-    public function detect_req_type($espresso_db_update = null)
649
-    {
650
-        if ($this->_req_type === null) {
651
-            $espresso_db_update          = ! empty($espresso_db_update)
652
-                ? $espresso_db_update
653
-                : $this->fix_espresso_db_upgrade_option();
654
-            $this->_req_type             = EE_System::detect_req_type_given_activation_history(
655
-                $espresso_db_update,
656
-                'ee_espresso_activation', espresso_version()
657
-            );
658
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
659
-            $this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
660
-        }
661
-        return $this->_req_type;
662
-    }
663
-
664
-
665
-
666
-    /**
667
-     * Returns whether or not there was a non-micro version change (ie, change in either
668
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
669
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
670
-     *
671
-     * @param $activation_history
672
-     * @return bool
673
-     */
674
-    private function _detect_major_version_change($activation_history)
675
-    {
676
-        $previous_version       = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
677
-        $previous_version_parts = explode('.', $previous_version);
678
-        $current_version_parts  = explode('.', espresso_version());
679
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
680
-               && ($previous_version_parts[0] !== $current_version_parts[0]
681
-                   || $previous_version_parts[1] !== $current_version_parts[1]
682
-               );
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns true if either the major or minor version of EE changed during this request.
689
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
690
-     *
691
-     * @return bool
692
-     */
693
-    public function is_major_version_change()
694
-    {
695
-        return $this->_major_version_change;
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
702
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
703
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
704
-     * just activated to (for core that will always be espresso_version())
705
-     *
706
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
707
-     *                                                 ee plugin. for core that's 'espresso_db_update'
708
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
709
-     *                                                 indicate that this plugin was just activated
710
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
711
-     *                                                 espresso_version())
712
-     * @return int one of the constants on EE_System::req_type_*
713
-     */
714
-    public static function detect_req_type_given_activation_history(
715
-        $activation_history_for_addon,
716
-        $activation_indicator_option_name,
717
-        $version_to_upgrade_to
718
-    ) {
719
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
720
-        if ($activation_history_for_addon) {
721
-            //it exists, so this isn't a completely new install
722
-            //check if this version already in that list of previously installed versions
723
-            if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
724
-                //it a version we haven't seen before
725
-                if ($version_is_higher === 1) {
726
-                    $req_type = EE_System::req_type_upgrade;
727
-                } else {
728
-                    $req_type = EE_System::req_type_downgrade;
729
-                }
730
-                delete_option($activation_indicator_option_name);
731
-            } else {
732
-                // its not an update. maybe a reactivation?
733
-                if (get_option($activation_indicator_option_name, false)) {
734
-                    if ($version_is_higher === -1) {
735
-                        $req_type = EE_System::req_type_downgrade;
736
-                    } elseif ($version_is_higher === 0) {
737
-                        //we've seen this version before, but it's an activation. must be a reactivation
738
-                        $req_type = EE_System::req_type_reactivation;
739
-                    } else {//$version_is_higher === 1
740
-                        $req_type = EE_System::req_type_upgrade;
741
-                    }
742
-                    delete_option($activation_indicator_option_name);
743
-                } else {
744
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
745
-                    if ($version_is_higher === -1) {
746
-                        $req_type = EE_System::req_type_downgrade;
747
-                    } elseif ($version_is_higher === 0) {
748
-                        //we've seen this version before and it's not an activation. its normal request
749
-                        $req_type = EE_System::req_type_normal;
750
-                    } else {//$version_is_higher === 1
751
-                        $req_type = EE_System::req_type_upgrade;
752
-                    }
753
-                }
754
-            }
755
-        } else {
756
-            //brand new install
757
-            $req_type = EE_System::req_type_new_activation;
758
-            delete_option($activation_indicator_option_name);
759
-        }
760
-        return $req_type;
761
-    }
762
-
763
-
764
-
765
-    /**
766
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
767
-     * the $activation_history_for_addon
768
-     *
769
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
770
-     *                                             sometimes containing 'unknown-date'
771
-     * @param string $version_to_upgrade_to        (current version)
772
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
773
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
774
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
775
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
776
-     */
777
-    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
778
-    {
779
-        //find the most recently-activated version
780
-        $most_recently_active_version =
781
-            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
782
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
783
-    }
784
-
785
-
786
-
787
-    /**
788
-     * Gets the most recently active version listed in the activation history,
789
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
790
-     *
791
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
792
-     *                                   sometimes containing 'unknown-date'
793
-     * @return string
794
-     */
795
-    private static function _get_most_recently_active_version_from_activation_history($activation_history)
796
-    {
797
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
798
-        $most_recently_active_version            = '0.0.0.dev.000';
799
-        if (is_array($activation_history)) {
800
-            foreach ($activation_history as $version => $times_activated) {
801
-                //check there is a record of when this version was activated. Otherwise,
802
-                //mark it as unknown
803
-                if (! $times_activated) {
804
-                    $times_activated = array('unknown-date');
805
-                }
806
-                if (is_string($times_activated)) {
807
-                    $times_activated = array($times_activated);
808
-                }
809
-                foreach ($times_activated as $an_activation) {
810
-                    if ($an_activation !== 'unknown-date'
811
-                        && $an_activation
812
-                           > $most_recently_active_version_activation) {
813
-                        $most_recently_active_version            = $version;
814
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
815
-                            ? '1970-01-01 00:00:00'
816
-                            : $an_activation;
817
-                    }
818
-                }
819
-            }
820
-        }
821
-        return $most_recently_active_version;
822
-    }
823
-
824
-
825
-
826
-    /**
827
-     * This redirects to the about EE page after activation
828
-     *
829
-     * @return void
830
-     */
831
-    public function redirect_to_about_ee()
832
-    {
833
-        $notices = EE_Error::get_notices(false);
834
-        //if current user is an admin and it's not an ajax or rest request
835
-        if (
836
-            ! isset($notices['errors'])
837
-            && $this->request->isAdmin()
838
-            && apply_filters(
839
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
840
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
841
-            )
842
-        ) {
843
-            $query_params = array('page' => 'espresso_about');
844
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
845
-                $query_params['new_activation'] = true;
846
-            }
847
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
848
-                $query_params['reactivation'] = true;
849
-            }
850
-            $url = add_query_arg($query_params, admin_url('admin.php'));
851
-            wp_safe_redirect($url);
852
-            exit();
853
-        }
854
-    }
855
-
856
-
857
-
858
-    /**
859
-     * load_core_configuration
860
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
861
-     * which runs during the WP 'plugins_loaded' action at priority 5
862
-     *
863
-     * @return void
864
-     * @throws ReflectionException
865
-     */
866
-    public function load_core_configuration()
867
-    {
868
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
869
-        $this->loader->getShared('EE_Load_Textdomain');
870
-        //load textdomain
871
-        EE_Load_Textdomain::load_textdomain();
872
-        // load and setup EE_Config and EE_Network_Config
873
-        $config = $this->loader->getShared('EE_Config');
874
-        $this->loader->getShared('EE_Network_Config');
875
-        // setup autoloaders
876
-        // enable logging?
877
-        if ($config->admin->use_full_logging) {
878
-            $this->loader->getShared('EE_Log');
879
-        }
880
-        // check for activation errors
881
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
882
-        if ($activation_errors) {
883
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
884
-            update_option('ee_plugin_activation_errors', false);
885
-        }
886
-        // get model names
887
-        $this->_parse_model_names();
888
-        //load caf stuff a chance to play during the activation process too.
889
-        $this->_maybe_brew_regular();
890
-        // configure custom post type definitions
891
-        $this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions');
892
-        $this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions');
893
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
894
-    }
895
-
896
-
897
-
898
-    /**
899
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
900
-     *
901
-     * @return void
902
-     * @throws ReflectionException
903
-     */
904
-    private function _parse_model_names()
905
-    {
906
-        //get all the files in the EE_MODELS folder that end in .model.php
907
-        $models                 = glob(EE_MODELS . '*.model.php');
908
-        $model_names            = array();
909
-        $non_abstract_db_models = array();
910
-        foreach ($models as $model) {
911
-            // get model classname
912
-            $classname       = EEH_File::get_classname_from_filepath_with_standard_filename($model);
913
-            $short_name      = str_replace('EEM_', '', $classname);
914
-            $reflectionClass = new ReflectionClass($classname);
915
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
916
-                $non_abstract_db_models[ $short_name ] = $classname;
917
-            }
918
-            $model_names[ $short_name ] = $classname;
919
-        }
920
-        $this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
921
-        $this->registry->non_abstract_db_models = apply_filters(
922
-            'FHEE__EE_System__parse_implemented_model_names',
923
-            $non_abstract_db_models
924
-        );
925
-    }
926
-
927
-
928
-    /**
929
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
930
-     * that need to be setup before our EE_System launches.
931
-     *
932
-     * @return void
933
-     * @throws DomainException
934
-     * @throws InvalidArgumentException
935
-     * @throws InvalidDataTypeException
936
-     * @throws InvalidInterfaceException
937
-     * @throws InvalidClassException
938
-     * @throws InvalidFilePathException
939
-     */
940
-    private function _maybe_brew_regular()
941
-    {
942
-        /** @var Domain $domain */
943
-        $domain = DomainFactory::getShared(
944
-            new FullyQualifiedName(
945
-                'EventEspresso\core\domain\Domain'
946
-            ),
947
-            array(
948
-                new FilePath(EVENT_ESPRESSO_MAIN_FILE),
949
-                Version::fromString(espresso_version())
950
-            )
951
-        );
952
-        if ($domain->isCaffeinated()) {
953
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
954
-        }
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * register_shortcodes_modules_and_widgets
961
-     * generate lists of shortcodes and modules, then verify paths and classes
962
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
963
-     * which runs during the WP 'plugins_loaded' action at priority 7
964
-     *
965
-     * @access public
966
-     * @return void
967
-     * @throws Exception
968
-     */
969
-    public function register_shortcodes_modules_and_widgets()
970
-    {
971
-        if ($this->request->isFrontend() || $this->request->isIframe()) {
972
-            try {
973
-                // load, register, and add shortcodes the new way
974
-                $this->loader->getShared(
975
-                    'EventEspresso\core\services\shortcodes\ShortcodesManager',
976
-                    array(
977
-                        // and the old way, but we'll put it under control of the new system
978
-                        EE_Config::getLegacyShortcodesManager(),
979
-                    )
980
-                );
981
-            } catch (Exception $exception) {
982
-                new ExceptionStackTraceDisplay($exception);
983
-            }
984
-        }
985
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
986
-        // check for addons using old hook point
987
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
988
-            $this->_incompatible_addon_error();
989
-        }
990
-    }
991
-
992
-
993
-
994
-    /**
995
-     * _incompatible_addon_error
996
-     *
997
-     * @access public
998
-     * @return void
999
-     */
1000
-    private function _incompatible_addon_error()
1001
-    {
1002
-        // get array of classes hooking into here
1003
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
1004
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
1005
-        );
1006
-        if (! empty($class_names)) {
1007
-            $msg = __(
1008
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
1009
-                'event_espresso'
1010
-            );
1011
-            $msg .= '<ul>';
1012
-            foreach ($class_names as $class_name) {
1013
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
1014
-                        array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
1015
-                        $class_name
1016
-                    ) . '</b></li>';
1017
-            }
1018
-            $msg .= '</ul>';
1019
-            $msg .= __(
1020
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
1021
-                'event_espresso'
1022
-            );
1023
-            // save list of incompatible addons to wp-options for later use
1024
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
1025
-            if (is_admin()) {
1026
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1027
-            }
1028
-        }
1029
-    }
1030
-
1031
-
1032
-
1033
-    /**
1034
-     * brew_espresso
1035
-     * begins the process of setting hooks for initializing EE in the correct order
1036
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1037
-     * which runs during the WP 'plugins_loaded' action at priority 9
1038
-     *
1039
-     * @return void
1040
-     */
1041
-    public function brew_espresso()
1042
-    {
1043
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
1044
-        // load some final core systems
1045
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
1046
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1047
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
1048
-        add_action('init', array($this, 'load_controllers'), 7);
1049
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
1050
-        add_action('init', array($this, 'initialize'), 10);
1051
-        add_action('init', array($this, 'initialize_last'), 100);
1052
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1053
-            // pew pew pew
1054
-            $this->loader->getShared('EventEspresso\core\services\licensing\LicenseService');
1055
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1056
-        }
1057
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     *    set_hooks_for_core
1064
-     *
1065
-     * @access public
1066
-     * @return    void
1067
-     * @throws EE_Error
1068
-     */
1069
-    public function set_hooks_for_core()
1070
-    {
1071
-        $this->_deactivate_incompatible_addons();
1072
-        do_action('AHEE__EE_System__set_hooks_for_core');
1073
-        $this->loader->getShared('EventEspresso\core\domain\values\session\SessionLifespan');
1074
-        //caps need to be initialized on every request so that capability maps are set.
1075
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1076
-        $this->registry->CAP->init_caps();
1077
-    }
1078
-
1079
-
1080
-
1081
-    /**
1082
-     * Using the information gathered in EE_System::_incompatible_addon_error,
1083
-     * deactivates any addons considered incompatible with the current version of EE
1084
-     */
1085
-    private function _deactivate_incompatible_addons()
1086
-    {
1087
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
1088
-        if (! empty($incompatible_addons)) {
1089
-            $active_plugins = get_option('active_plugins', array());
1090
-            foreach ($active_plugins as $active_plugin) {
1091
-                foreach ($incompatible_addons as $incompatible_addon) {
1092
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1093
-                        unset($_GET['activate']);
1094
-                        espresso_deactivate_plugin($active_plugin);
1095
-                    }
1096
-                }
1097
-            }
1098
-        }
1099
-    }
1100
-
1101
-
1102
-
1103
-    /**
1104
-     *    perform_activations_upgrades_and_migrations
1105
-     *
1106
-     * @access public
1107
-     * @return    void
1108
-     */
1109
-    public function perform_activations_upgrades_and_migrations()
1110
-    {
1111
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1112
-    }
1113
-
1114
-
1115
-    /**
1116
-     * @return void
1117
-     * @throws DomainException
1118
-     */
1119
-    public function load_CPTs_and_session()
1120
-    {
1121
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1122
-        /** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies $register_custom_taxonomies */
1123
-        $register_custom_taxonomies = $this->loader->getShared(
1124
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'
1125
-        );
1126
-        $register_custom_taxonomies->registerCustomTaxonomies();
1127
-        /** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes $register_custom_post_types */
1128
-        $register_custom_post_types = $this->loader->getShared(
1129
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'
1130
-        );
1131
-        $register_custom_post_types->registerCustomPostTypes();
1132
-        /** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms $register_custom_taxonomy_terms */
1133
-        $register_custom_taxonomy_terms = $this->loader->getShared(
1134
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms'
1135
-        );
1136
-        $register_custom_taxonomy_terms->registerCustomTaxonomyTerms();
1137
-        // load legacy Custom Post Types and Taxonomies
1138
-        $this->loader->getShared('EE_Register_CPTs');
1139
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1140
-    }
1141
-
1142
-
1143
-
1144
-    /**
1145
-     * load_controllers
1146
-     * this is the best place to load any additional controllers that needs access to EE core.
1147
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1148
-     * time
1149
-     *
1150
-     * @access public
1151
-     * @return void
1152
-     */
1153
-    public function load_controllers()
1154
-    {
1155
-        do_action('AHEE__EE_System__load_controllers__start');
1156
-        // let's get it started
1157
-        if (
1158
-            ! $this->maintenance_mode->level()
1159
-            && ($this->request->isFrontend() || $this->request->isFrontAjax())
1160
-        ) {
1161
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1162
-            $this->loader->getShared('EE_Front_Controller');
1163
-        } elseif ($this->request->isAdmin() || $this->request->isAdminAjax()) {
1164
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1165
-            $this->loader->getShared('EE_Admin');
1166
-        }
1167
-        do_action('AHEE__EE_System__load_controllers__complete');
1168
-    }
1169
-
1170
-
1171
-
1172
-    /**
1173
-     * core_loaded_and_ready
1174
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1175
-     *
1176
-     * @access public
1177
-     * @return void
1178
-     */
1179
-    public function core_loaded_and_ready()
1180
-    {
1181
-        if (
1182
-            $this->request->isAdmin()
1183
-            || $this->request->isEeAjax()
1184
-            || $this->request->isFrontend()
1185
-        ) {
1186
-            $this->loader->getShared('EE_Session');
1187
-        }
1188
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1189
-        // load_espresso_template_tags
1190
-        if (
1191
-            is_readable(EE_PUBLIC . 'template_tags.php')
1192
-            && ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isFeed())
1193
-        ) {
1194
-            require_once EE_PUBLIC . 'template_tags.php';
1195
-        }
1196
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1197
-        if ($this->request->isAdmin() || $this->request->isFrontend() || $this->request->isIframe()) {
1198
-            $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1199
-        }
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * initialize
1206
-     * this is the best place to begin initializing client code
1207
-     *
1208
-     * @access public
1209
-     * @return void
1210
-     */
1211
-    public function initialize()
1212
-    {
1213
-        do_action('AHEE__EE_System__initialize');
1214
-    }
1215
-
1216
-
1217
-
1218
-    /**
1219
-     * initialize_last
1220
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1221
-     * initialize has done so
1222
-     *
1223
-     * @access public
1224
-     * @return void
1225
-     */
1226
-    public function initialize_last()
1227
-    {
1228
-        do_action('AHEE__EE_System__initialize_last');
1229
-        /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
1230
-        $rewrite_rules = $this->loader->getShared(
1231
-            'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
1232
-        );
1233
-        $rewrite_rules->flushRewriteRules();
1234
-        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1235
-    }
1236
-
1237
-
1238
-
1239
-    /**
1240
-     * @return void
1241
-     * @throws EE_Error
1242
-     */
1243
-    public function addEspressoToolbar()
1244
-    {
1245
-        $this->loader->getShared(
1246
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1247
-            array($this->registry->CAP)
1248
-        );
1249
-    }
1250
-
1251
-
1252
-
1253
-    /**
1254
-     * do_not_cache
1255
-     * sets no cache headers and defines no cache constants for WP plugins
1256
-     *
1257
-     * @access public
1258
-     * @return void
1259
-     */
1260
-    public static function do_not_cache()
1261
-    {
1262
-        // set no cache constants
1263
-        if (! defined('DONOTCACHEPAGE')) {
1264
-            define('DONOTCACHEPAGE', true);
1265
-        }
1266
-        if (! defined('DONOTCACHCEOBJECT')) {
1267
-            define('DONOTCACHCEOBJECT', true);
1268
-        }
1269
-        if (! defined('DONOTCACHEDB')) {
1270
-            define('DONOTCACHEDB', true);
1271
-        }
1272
-        // add no cache headers
1273
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1274
-        // plus a little extra for nginx and Google Chrome
1275
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1276
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1277
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1278
-    }
1279
-
1280
-
1281
-
1282
-    /**
1283
-     *    extra_nocache_headers
1284
-     *
1285
-     * @access    public
1286
-     * @param $headers
1287
-     * @return    array
1288
-     */
1289
-    public static function extra_nocache_headers($headers)
1290
-    {
1291
-        // for NGINX
1292
-        $headers['X-Accel-Expires'] = 0;
1293
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1294
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1295
-        return $headers;
1296
-    }
1297
-
1298
-
1299
-
1300
-    /**
1301
-     *    nocache_headers
1302
-     *
1303
-     * @access    public
1304
-     * @return    void
1305
-     */
1306
-    public static function nocache_headers()
1307
-    {
1308
-        nocache_headers();
1309
-    }
1310
-
1311
-
1312
-
1313
-    /**
1314
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1315
-     * never returned with the function.
1316
-     *
1317
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1318
-     * @return array
1319
-     */
1320
-    public function remove_pages_from_wp_list_pages($exclude_array)
1321
-    {
1322
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1323
-    }
35
+	/**
36
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
37
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
38
+	 */
39
+	const req_type_normal = 0;
40
+
41
+	/**
42
+	 * Indicates this is a brand new installation of EE so we should install
43
+	 * tables and default data etc
44
+	 */
45
+	const req_type_new_activation = 1;
46
+
47
+	/**
48
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
49
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
50
+	 * and that default data is setup too
51
+	 */
52
+	const req_type_reactivation = 2;
53
+
54
+	/**
55
+	 * indicates that EE has been upgraded since its previous request.
56
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
57
+	 */
58
+	const req_type_upgrade = 3;
59
+
60
+	/**
61
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
62
+	 */
63
+	const req_type_downgrade = 4;
64
+
65
+	/**
66
+	 * @deprecated since version 4.6.0.dev.006
67
+	 * Now whenever a new_activation is detected the request type is still just
68
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
69
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
70
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
71
+	 * (Specifically, when the migration manager indicates migrations are finished
72
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
73
+	 */
74
+	const req_type_activation_but_not_installed = 5;
75
+
76
+	/**
77
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
78
+	 */
79
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
80
+
81
+
82
+	/**
83
+	 * @var EE_System $_instance
84
+	 */
85
+	private static $_instance;
86
+
87
+	/**
88
+	 * @var EE_Registry $registry
89
+	 */
90
+	private $registry;
91
+
92
+	/**
93
+	 * @var LoaderInterface $loader
94
+	 */
95
+	private $loader;
96
+
97
+	/**
98
+	 * @var EE_Capabilities $capabilities
99
+	 */
100
+	private $capabilities;
101
+
102
+	/**
103
+	 * @var RequestInterface $request
104
+	 */
105
+	private $request;
106
+
107
+	/**
108
+	 * @var EE_Maintenance_Mode $maintenance_mode
109
+	 */
110
+	private $maintenance_mode;
111
+
112
+	/**
113
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
114
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
115
+	 *
116
+	 * @var int $_req_type
117
+	 */
118
+	private $_req_type;
119
+
120
+	/**
121
+	 * Whether or not there was a non-micro version change in EE core version during this request
122
+	 *
123
+	 * @var boolean $_major_version_change
124
+	 */
125
+	private $_major_version_change = false;
126
+
127
+	/**
128
+	 * A Context DTO dedicated solely to identifying the current request type.
129
+	 *
130
+	 * @var RequestTypeContextCheckerInterface $request_type
131
+	 */
132
+	private $request_type;
133
+
134
+
135
+
136
+	/**
137
+	 * @singleton method used to instantiate class object
138
+	 * @param EE_Registry|null         $registry
139
+	 * @param LoaderInterface|null     $loader
140
+	 * @param RequestInterface|null          $request
141
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
142
+	 * @return EE_System
143
+	 */
144
+	public static function instance(
145
+		EE_Registry $registry = null,
146
+		LoaderInterface $loader = null,
147
+		RequestInterface $request = null,
148
+		EE_Maintenance_Mode $maintenance_mode = null
149
+	) {
150
+		// check if class object is instantiated
151
+		if (! self::$_instance instanceof EE_System) {
152
+			self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
153
+		}
154
+		return self::$_instance;
155
+	}
156
+
157
+
158
+
159
+	/**
160
+	 * resets the instance and returns it
161
+	 *
162
+	 * @return EE_System
163
+	 */
164
+	public static function reset()
165
+	{
166
+		self::$_instance->_req_type = null;
167
+		//make sure none of the old hooks are left hanging around
168
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
169
+		//we need to reset the migration manager in order for it to detect DMSs properly
170
+		EE_Data_Migration_Manager::reset();
171
+		self::instance()->detect_activations_or_upgrades();
172
+		self::instance()->perform_activations_upgrades_and_migrations();
173
+		return self::instance();
174
+	}
175
+
176
+
177
+
178
+	/**
179
+	 * sets hooks for running rest of system
180
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
181
+	 * starting EE Addons from any other point may lead to problems
182
+	 *
183
+	 * @param EE_Registry         $registry
184
+	 * @param LoaderInterface     $loader
185
+	 * @param RequestInterface          $request
186
+	 * @param EE_Maintenance_Mode $maintenance_mode
187
+	 */
188
+	private function __construct(
189
+		EE_Registry $registry,
190
+		LoaderInterface $loader,
191
+		RequestInterface $request,
192
+		EE_Maintenance_Mode $maintenance_mode
193
+	) {
194
+		$this->registry         = $registry;
195
+		$this->loader           = $loader;
196
+		$this->request          = $request;
197
+		$this->maintenance_mode = $maintenance_mode;
198
+		do_action('AHEE__EE_System__construct__begin', $this);
199
+		add_action(
200
+			'AHEE__EE_Bootstrap__load_espresso_addons',
201
+			array($this, 'loadCapabilities'),
202
+			5
203
+		);
204
+		add_action(
205
+			'AHEE__EE_Bootstrap__load_espresso_addons',
206
+			array($this, 'loadCommandBus'),
207
+			7
208
+		);
209
+		add_action(
210
+			'AHEE__EE_Bootstrap__load_espresso_addons',
211
+			array($this, 'loadPluginApi'),
212
+			9
213
+		);
214
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
215
+		add_action(
216
+			'AHEE__EE_Bootstrap__load_espresso_addons',
217
+			array($this, 'load_espresso_addons')
218
+		);
219
+		// when an ee addon is activated, we want to call the core hook(s) again
220
+		// because the newly-activated addon didn't get a chance to run at all
221
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
222
+		// detect whether install or upgrade
223
+		add_action(
224
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
225
+			array($this, 'detect_activations_or_upgrades'),
226
+			3
227
+		);
228
+		// load EE_Config, EE_Textdomain, etc
229
+		add_action(
230
+			'AHEE__EE_Bootstrap__load_core_configuration',
231
+			array($this, 'load_core_configuration'),
232
+			5
233
+		);
234
+		// load EE_Config, EE_Textdomain, etc
235
+		add_action(
236
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
237
+			array($this, 'register_shortcodes_modules_and_widgets'),
238
+			7
239
+		);
240
+		// you wanna get going? I wanna get going... let's get going!
241
+		add_action(
242
+			'AHEE__EE_Bootstrap__brew_espresso',
243
+			array($this, 'brew_espresso'),
244
+			9
245
+		);
246
+		//other housekeeping
247
+		//exclude EE critical pages from wp_list_pages
248
+		add_filter(
249
+			'wp_list_pages_excludes',
250
+			array($this, 'remove_pages_from_wp_list_pages'),
251
+			10
252
+		);
253
+		// ALL EE Addons should use the following hook point to attach their initial setup too
254
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
255
+		do_action('AHEE__EE_System__construct__complete', $this);
256
+	}
257
+
258
+
259
+	/**
260
+	 * load and setup EE_Capabilities
261
+	 *
262
+	 * @return void
263
+	 * @throws EE_Error
264
+	 */
265
+	public function loadCapabilities()
266
+	{
267
+		$this->capabilities = $this->loader->getShared('EE_Capabilities');
268
+		add_action(
269
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
270
+			function ()
271
+			{
272
+				LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
273
+			}
274
+		);
275
+	}
276
+
277
+
278
+
279
+	/**
280
+	 * create and cache the CommandBus, and also add middleware
281
+	 * The CapChecker middleware requires the use of EE_Capabilities
282
+	 * which is why we need to load the CommandBus after Caps are set up
283
+	 *
284
+	 * @return void
285
+	 * @throws EE_Error
286
+	 */
287
+	public function loadCommandBus()
288
+	{
289
+		$this->loader->getShared(
290
+			'CommandBusInterface',
291
+			array(
292
+				null,
293
+				apply_filters(
294
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
295
+					array(
296
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
297
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
298
+					)
299
+				),
300
+			)
301
+		);
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * @return void
308
+	 * @throws EE_Error
309
+	 */
310
+	public function loadPluginApi()
311
+	{
312
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
313
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
314
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
315
+		$this->loader->getShared('EE_Request_Handler');
316
+	}
317
+
318
+
319
+	/**
320
+	 * @param string $addon_name
321
+	 * @param string $version_constant
322
+	 * @param string $min_version_required
323
+	 * @param string $load_callback
324
+	 * @param string $plugin_file_constant
325
+	 * @return void
326
+	 */
327
+	private function deactivateIncompatibleAddon(
328
+		$addon_name,
329
+		$version_constant,
330
+		$min_version_required,
331
+		$load_callback,
332
+		$plugin_file_constant
333
+	) {
334
+		if (! defined($version_constant)) {
335
+			return;
336
+		}
337
+		$addon_version = constant($version_constant);
338
+		if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
339
+			remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
340
+			if (! function_exists('deactivate_plugins')) {
341
+				require_once ABSPATH . 'wp-admin/includes/plugin.php';
342
+			}
343
+			deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
344
+			unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
345
+			EE_Error::add_error(
346
+				sprintf(
347
+					esc_html__(
348
+						'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
349
+						'event_espresso'
350
+					),
351
+					$addon_name,
352
+					$min_version_required
353
+				),
354
+				__FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
355
+			);
356
+			EE_Error::get_notices(false, true);
357
+		}
358
+	}
359
+
360
+
361
+	/**
362
+	 * load_espresso_addons
363
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
364
+	 * this is hooked into both:
365
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
366
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
367
+	 *    and the WP 'activate_plugin' hook point
368
+	 *
369
+	 * @access public
370
+	 * @return void
371
+	 */
372
+	public function load_espresso_addons()
373
+	{
374
+		$this->deactivateIncompatibleAddon(
375
+			'Wait Lists',
376
+			'EE_WAIT_LISTS_VERSION',
377
+			'1.0.0.beta.074',
378
+			'load_espresso_wait_lists',
379
+			'EE_WAIT_LISTS_PLUGIN_FILE'
380
+		);
381
+		$this->deactivateIncompatibleAddon(
382
+			'Automated Upcoming Event Notifications',
383
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
384
+			'1.0.0.beta.091',
385
+			'load_espresso_automated_upcoming_event_notification',
386
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
387
+		);
388
+		do_action('AHEE__EE_System__load_espresso_addons');
389
+		//if the WP API basic auth plugin isn't already loaded, load it now.
390
+		//We want it for mobile apps. Just include the entire plugin
391
+		//also, don't load the basic auth when a plugin is getting activated, because
392
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
393
+		//and causes a fatal error
394
+		if (
395
+			$this->request->getRequestParam('activate') !== 'true'
396
+			&& ! function_exists('json_basic_auth_handler')
397
+			&& ! function_exists('json_basic_auth_error')
398
+			&& ! in_array(
399
+				$this->request->getRequestParam('action'),
400
+				array('activate', 'activate-selected'),
401
+				true
402
+			)
403
+		) {
404
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
405
+		}
406
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
407
+	}
408
+
409
+
410
+
411
+	/**
412
+	 * detect_activations_or_upgrades
413
+	 * Checks for activation or upgrade of core first;
414
+	 * then also checks if any registered addons have been activated or upgraded
415
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
416
+	 * which runs during the WP 'plugins_loaded' action at priority 3
417
+	 *
418
+	 * @access public
419
+	 * @return void
420
+	 */
421
+	public function detect_activations_or_upgrades()
422
+	{
423
+		//first off: let's make sure to handle core
424
+		$this->detect_if_activation_or_upgrade();
425
+		foreach ($this->registry->addons as $addon) {
426
+			if ($addon instanceof EE_Addon) {
427
+				//detect teh request type for that addon
428
+				$addon->detect_activation_or_upgrade();
429
+			}
430
+		}
431
+	}
432
+
433
+
434
+
435
+	/**
436
+	 * detect_if_activation_or_upgrade
437
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
438
+	 * and either setting up the DB or setting up maintenance mode etc.
439
+	 *
440
+	 * @access public
441
+	 * @return void
442
+	 */
443
+	public function detect_if_activation_or_upgrade()
444
+	{
445
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
446
+		// check if db has been updated, or if its a brand-new installation
447
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
448
+		$request_type       = $this->detect_req_type($espresso_db_update);
449
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
450
+		switch ($request_type) {
451
+			case EE_System::req_type_new_activation:
452
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
453
+				$this->_handle_core_version_change($espresso_db_update);
454
+				break;
455
+			case EE_System::req_type_reactivation:
456
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
457
+				$this->_handle_core_version_change($espresso_db_update);
458
+				break;
459
+			case EE_System::req_type_upgrade:
460
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
461
+				//migrations may be required now that we've upgraded
462
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
463
+				$this->_handle_core_version_change($espresso_db_update);
464
+				//				echo "done upgrade";die;
465
+				break;
466
+			case EE_System::req_type_downgrade:
467
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
468
+				//its possible migrations are no longer required
469
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
470
+				$this->_handle_core_version_change($espresso_db_update);
471
+				break;
472
+			case EE_System::req_type_normal:
473
+			default:
474
+				break;
475
+		}
476
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
477
+	}
478
+
479
+
480
+
481
+	/**
482
+	 * Updates the list of installed versions and sets hooks for
483
+	 * initializing the database later during the request
484
+	 *
485
+	 * @param array $espresso_db_update
486
+	 */
487
+	private function _handle_core_version_change($espresso_db_update)
488
+	{
489
+		$this->update_list_of_installed_versions($espresso_db_update);
490
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
491
+		add_action(
492
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
493
+			array($this, 'initialize_db_if_no_migrations_required')
494
+		);
495
+	}
496
+
497
+
498
+
499
+	/**
500
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
501
+	 * information about what versions of EE have been installed and activated,
502
+	 * NOT necessarily the state of the database
503
+	 *
504
+	 * @param mixed $espresso_db_update           the value of the WordPress option.
505
+	 *                                            If not supplied, fetches it from the options table
506
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
507
+	 */
508
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
509
+	{
510
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
511
+		if (! $espresso_db_update) {
512
+			$espresso_db_update = get_option('espresso_db_update');
513
+		}
514
+		// check that option is an array
515
+		if (! is_array($espresso_db_update)) {
516
+			// if option is FALSE, then it never existed
517
+			if ($espresso_db_update === false) {
518
+				// make $espresso_db_update an array and save option with autoload OFF
519
+				$espresso_db_update = array();
520
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
521
+			} else {
522
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
523
+				$espresso_db_update = array($espresso_db_update => array());
524
+				update_option('espresso_db_update', $espresso_db_update);
525
+			}
526
+		} else {
527
+			$corrected_db_update = array();
528
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
529
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
530
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
531
+					//the key is an int, and the value IS NOT an array
532
+					//so it must be numerically-indexed, where values are versions installed...
533
+					//fix it!
534
+					$version_string                         = $should_be_array;
535
+					$corrected_db_update[ $version_string ] = array('unknown-date');
536
+				} else {
537
+					//ok it checks out
538
+					$corrected_db_update[ $should_be_version_string ] = $should_be_array;
539
+				}
540
+			}
541
+			$espresso_db_update = $corrected_db_update;
542
+			update_option('espresso_db_update', $espresso_db_update);
543
+		}
544
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
545
+		return $espresso_db_update;
546
+	}
547
+
548
+
549
+
550
+	/**
551
+	 * Does the traditional work of setting up the plugin's database and adding default data.
552
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
553
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
554
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
555
+	 * so that it will be done when migrations are finished
556
+	 *
557
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
558
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
559
+	 *                                       This is a resource-intensive job
560
+	 *                                       so we prefer to only do it when necessary
561
+	 * @return void
562
+	 * @throws EE_Error
563
+	 */
564
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
565
+	{
566
+		$request_type = $this->detect_req_type();
567
+		//only initialize system if we're not in maintenance mode.
568
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
569
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
570
+			$rewrite_rules = $this->loader->getShared(
571
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
572
+			);
573
+			$rewrite_rules->flush();
574
+			if ($verify_schema) {
575
+				EEH_Activation::initialize_db_and_folders();
576
+			}
577
+			EEH_Activation::initialize_db_content();
578
+			EEH_Activation::system_initialization();
579
+			if ($initialize_addons_too) {
580
+				$this->initialize_addons();
581
+			}
582
+		} else {
583
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
584
+		}
585
+		if ($request_type === EE_System::req_type_new_activation
586
+			|| $request_type === EE_System::req_type_reactivation
587
+			|| (
588
+				$request_type === EE_System::req_type_upgrade
589
+				&& $this->is_major_version_change()
590
+			)
591
+		) {
592
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
593
+		}
594
+	}
595
+
596
+
597
+
598
+	/**
599
+	 * Initializes the db for all registered addons
600
+	 *
601
+	 * @throws EE_Error
602
+	 */
603
+	public function initialize_addons()
604
+	{
605
+		//foreach registered addon, make sure its db is up-to-date too
606
+		foreach ($this->registry->addons as $addon) {
607
+			if ($addon instanceof EE_Addon) {
608
+				$addon->initialize_db_if_no_migrations_required();
609
+			}
610
+		}
611
+	}
612
+
613
+
614
+
615
+	/**
616
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
617
+	 *
618
+	 * @param    array  $version_history
619
+	 * @param    string $current_version_to_add version to be added to the version history
620
+	 * @return    boolean success as to whether or not this option was changed
621
+	 */
622
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
623
+	{
624
+		if (! $version_history) {
625
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
626
+		}
627
+		if ($current_version_to_add === null) {
628
+			$current_version_to_add = espresso_version();
629
+		}
630
+		$version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
631
+		// re-save
632
+		return update_option('espresso_db_update', $version_history);
633
+	}
634
+
635
+
636
+
637
+	/**
638
+	 * Detects if the current version indicated in the has existed in the list of
639
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
640
+	 *
641
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
642
+	 *                                  If not supplied, fetches it from the options table.
643
+	 *                                  Also, caches its result so later parts of the code can also know whether
644
+	 *                                  there's been an update or not. This way we can add the current version to
645
+	 *                                  espresso_db_update, but still know if this is a new install or not
646
+	 * @return int one of the constants on EE_System::req_type_
647
+	 */
648
+	public function detect_req_type($espresso_db_update = null)
649
+	{
650
+		if ($this->_req_type === null) {
651
+			$espresso_db_update          = ! empty($espresso_db_update)
652
+				? $espresso_db_update
653
+				: $this->fix_espresso_db_upgrade_option();
654
+			$this->_req_type             = EE_System::detect_req_type_given_activation_history(
655
+				$espresso_db_update,
656
+				'ee_espresso_activation', espresso_version()
657
+			);
658
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
659
+			$this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
660
+		}
661
+		return $this->_req_type;
662
+	}
663
+
664
+
665
+
666
+	/**
667
+	 * Returns whether or not there was a non-micro version change (ie, change in either
668
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
669
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
670
+	 *
671
+	 * @param $activation_history
672
+	 * @return bool
673
+	 */
674
+	private function _detect_major_version_change($activation_history)
675
+	{
676
+		$previous_version       = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
677
+		$previous_version_parts = explode('.', $previous_version);
678
+		$current_version_parts  = explode('.', espresso_version());
679
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
680
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
681
+				   || $previous_version_parts[1] !== $current_version_parts[1]
682
+			   );
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns true if either the major or minor version of EE changed during this request.
689
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
690
+	 *
691
+	 * @return bool
692
+	 */
693
+	public function is_major_version_change()
694
+	{
695
+		return $this->_major_version_change;
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
702
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
703
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
704
+	 * just activated to (for core that will always be espresso_version())
705
+	 *
706
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
707
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
708
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
709
+	 *                                                 indicate that this plugin was just activated
710
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
711
+	 *                                                 espresso_version())
712
+	 * @return int one of the constants on EE_System::req_type_*
713
+	 */
714
+	public static function detect_req_type_given_activation_history(
715
+		$activation_history_for_addon,
716
+		$activation_indicator_option_name,
717
+		$version_to_upgrade_to
718
+	) {
719
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
720
+		if ($activation_history_for_addon) {
721
+			//it exists, so this isn't a completely new install
722
+			//check if this version already in that list of previously installed versions
723
+			if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
724
+				//it a version we haven't seen before
725
+				if ($version_is_higher === 1) {
726
+					$req_type = EE_System::req_type_upgrade;
727
+				} else {
728
+					$req_type = EE_System::req_type_downgrade;
729
+				}
730
+				delete_option($activation_indicator_option_name);
731
+			} else {
732
+				// its not an update. maybe a reactivation?
733
+				if (get_option($activation_indicator_option_name, false)) {
734
+					if ($version_is_higher === -1) {
735
+						$req_type = EE_System::req_type_downgrade;
736
+					} elseif ($version_is_higher === 0) {
737
+						//we've seen this version before, but it's an activation. must be a reactivation
738
+						$req_type = EE_System::req_type_reactivation;
739
+					} else {//$version_is_higher === 1
740
+						$req_type = EE_System::req_type_upgrade;
741
+					}
742
+					delete_option($activation_indicator_option_name);
743
+				} else {
744
+					//we've seen this version before and the activation indicate doesn't show it was just activated
745
+					if ($version_is_higher === -1) {
746
+						$req_type = EE_System::req_type_downgrade;
747
+					} elseif ($version_is_higher === 0) {
748
+						//we've seen this version before and it's not an activation. its normal request
749
+						$req_type = EE_System::req_type_normal;
750
+					} else {//$version_is_higher === 1
751
+						$req_type = EE_System::req_type_upgrade;
752
+					}
753
+				}
754
+			}
755
+		} else {
756
+			//brand new install
757
+			$req_type = EE_System::req_type_new_activation;
758
+			delete_option($activation_indicator_option_name);
759
+		}
760
+		return $req_type;
761
+	}
762
+
763
+
764
+
765
+	/**
766
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
767
+	 * the $activation_history_for_addon
768
+	 *
769
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
770
+	 *                                             sometimes containing 'unknown-date'
771
+	 * @param string $version_to_upgrade_to        (current version)
772
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
773
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
774
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
775
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
776
+	 */
777
+	private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
778
+	{
779
+		//find the most recently-activated version
780
+		$most_recently_active_version =
781
+			EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
782
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
783
+	}
784
+
785
+
786
+
787
+	/**
788
+	 * Gets the most recently active version listed in the activation history,
789
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
790
+	 *
791
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
792
+	 *                                   sometimes containing 'unknown-date'
793
+	 * @return string
794
+	 */
795
+	private static function _get_most_recently_active_version_from_activation_history($activation_history)
796
+	{
797
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
798
+		$most_recently_active_version            = '0.0.0.dev.000';
799
+		if (is_array($activation_history)) {
800
+			foreach ($activation_history as $version => $times_activated) {
801
+				//check there is a record of when this version was activated. Otherwise,
802
+				//mark it as unknown
803
+				if (! $times_activated) {
804
+					$times_activated = array('unknown-date');
805
+				}
806
+				if (is_string($times_activated)) {
807
+					$times_activated = array($times_activated);
808
+				}
809
+				foreach ($times_activated as $an_activation) {
810
+					if ($an_activation !== 'unknown-date'
811
+						&& $an_activation
812
+						   > $most_recently_active_version_activation) {
813
+						$most_recently_active_version            = $version;
814
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
815
+							? '1970-01-01 00:00:00'
816
+							: $an_activation;
817
+					}
818
+				}
819
+			}
820
+		}
821
+		return $most_recently_active_version;
822
+	}
823
+
824
+
825
+
826
+	/**
827
+	 * This redirects to the about EE page after activation
828
+	 *
829
+	 * @return void
830
+	 */
831
+	public function redirect_to_about_ee()
832
+	{
833
+		$notices = EE_Error::get_notices(false);
834
+		//if current user is an admin and it's not an ajax or rest request
835
+		if (
836
+			! isset($notices['errors'])
837
+			&& $this->request->isAdmin()
838
+			&& apply_filters(
839
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
840
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
841
+			)
842
+		) {
843
+			$query_params = array('page' => 'espresso_about');
844
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
845
+				$query_params['new_activation'] = true;
846
+			}
847
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
848
+				$query_params['reactivation'] = true;
849
+			}
850
+			$url = add_query_arg($query_params, admin_url('admin.php'));
851
+			wp_safe_redirect($url);
852
+			exit();
853
+		}
854
+	}
855
+
856
+
857
+
858
+	/**
859
+	 * load_core_configuration
860
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
861
+	 * which runs during the WP 'plugins_loaded' action at priority 5
862
+	 *
863
+	 * @return void
864
+	 * @throws ReflectionException
865
+	 */
866
+	public function load_core_configuration()
867
+	{
868
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
869
+		$this->loader->getShared('EE_Load_Textdomain');
870
+		//load textdomain
871
+		EE_Load_Textdomain::load_textdomain();
872
+		// load and setup EE_Config and EE_Network_Config
873
+		$config = $this->loader->getShared('EE_Config');
874
+		$this->loader->getShared('EE_Network_Config');
875
+		// setup autoloaders
876
+		// enable logging?
877
+		if ($config->admin->use_full_logging) {
878
+			$this->loader->getShared('EE_Log');
879
+		}
880
+		// check for activation errors
881
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
882
+		if ($activation_errors) {
883
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
884
+			update_option('ee_plugin_activation_errors', false);
885
+		}
886
+		// get model names
887
+		$this->_parse_model_names();
888
+		//load caf stuff a chance to play during the activation process too.
889
+		$this->_maybe_brew_regular();
890
+		// configure custom post type definitions
891
+		$this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions');
892
+		$this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions');
893
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
894
+	}
895
+
896
+
897
+
898
+	/**
899
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
900
+	 *
901
+	 * @return void
902
+	 * @throws ReflectionException
903
+	 */
904
+	private function _parse_model_names()
905
+	{
906
+		//get all the files in the EE_MODELS folder that end in .model.php
907
+		$models                 = glob(EE_MODELS . '*.model.php');
908
+		$model_names            = array();
909
+		$non_abstract_db_models = array();
910
+		foreach ($models as $model) {
911
+			// get model classname
912
+			$classname       = EEH_File::get_classname_from_filepath_with_standard_filename($model);
913
+			$short_name      = str_replace('EEM_', '', $classname);
914
+			$reflectionClass = new ReflectionClass($classname);
915
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
916
+				$non_abstract_db_models[ $short_name ] = $classname;
917
+			}
918
+			$model_names[ $short_name ] = $classname;
919
+		}
920
+		$this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
921
+		$this->registry->non_abstract_db_models = apply_filters(
922
+			'FHEE__EE_System__parse_implemented_model_names',
923
+			$non_abstract_db_models
924
+		);
925
+	}
926
+
927
+
928
+	/**
929
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
930
+	 * that need to be setup before our EE_System launches.
931
+	 *
932
+	 * @return void
933
+	 * @throws DomainException
934
+	 * @throws InvalidArgumentException
935
+	 * @throws InvalidDataTypeException
936
+	 * @throws InvalidInterfaceException
937
+	 * @throws InvalidClassException
938
+	 * @throws InvalidFilePathException
939
+	 */
940
+	private function _maybe_brew_regular()
941
+	{
942
+		/** @var Domain $domain */
943
+		$domain = DomainFactory::getShared(
944
+			new FullyQualifiedName(
945
+				'EventEspresso\core\domain\Domain'
946
+			),
947
+			array(
948
+				new FilePath(EVENT_ESPRESSO_MAIN_FILE),
949
+				Version::fromString(espresso_version())
950
+			)
951
+		);
952
+		if ($domain->isCaffeinated()) {
953
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
954
+		}
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * register_shortcodes_modules_and_widgets
961
+	 * generate lists of shortcodes and modules, then verify paths and classes
962
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
963
+	 * which runs during the WP 'plugins_loaded' action at priority 7
964
+	 *
965
+	 * @access public
966
+	 * @return void
967
+	 * @throws Exception
968
+	 */
969
+	public function register_shortcodes_modules_and_widgets()
970
+	{
971
+		if ($this->request->isFrontend() || $this->request->isIframe()) {
972
+			try {
973
+				// load, register, and add shortcodes the new way
974
+				$this->loader->getShared(
975
+					'EventEspresso\core\services\shortcodes\ShortcodesManager',
976
+					array(
977
+						// and the old way, but we'll put it under control of the new system
978
+						EE_Config::getLegacyShortcodesManager(),
979
+					)
980
+				);
981
+			} catch (Exception $exception) {
982
+				new ExceptionStackTraceDisplay($exception);
983
+			}
984
+		}
985
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
986
+		// check for addons using old hook point
987
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
988
+			$this->_incompatible_addon_error();
989
+		}
990
+	}
991
+
992
+
993
+
994
+	/**
995
+	 * _incompatible_addon_error
996
+	 *
997
+	 * @access public
998
+	 * @return void
999
+	 */
1000
+	private function _incompatible_addon_error()
1001
+	{
1002
+		// get array of classes hooking into here
1003
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
1004
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
1005
+		);
1006
+		if (! empty($class_names)) {
1007
+			$msg = __(
1008
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
1009
+				'event_espresso'
1010
+			);
1011
+			$msg .= '<ul>';
1012
+			foreach ($class_names as $class_name) {
1013
+				$msg .= '<li><b>Event Espresso - ' . str_replace(
1014
+						array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
1015
+						$class_name
1016
+					) . '</b></li>';
1017
+			}
1018
+			$msg .= '</ul>';
1019
+			$msg .= __(
1020
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
1021
+				'event_espresso'
1022
+			);
1023
+			// save list of incompatible addons to wp-options for later use
1024
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
1025
+			if (is_admin()) {
1026
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1027
+			}
1028
+		}
1029
+	}
1030
+
1031
+
1032
+
1033
+	/**
1034
+	 * brew_espresso
1035
+	 * begins the process of setting hooks for initializing EE in the correct order
1036
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1037
+	 * which runs during the WP 'plugins_loaded' action at priority 9
1038
+	 *
1039
+	 * @return void
1040
+	 */
1041
+	public function brew_espresso()
1042
+	{
1043
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
1044
+		// load some final core systems
1045
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
1046
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1047
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
1048
+		add_action('init', array($this, 'load_controllers'), 7);
1049
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
1050
+		add_action('init', array($this, 'initialize'), 10);
1051
+		add_action('init', array($this, 'initialize_last'), 100);
1052
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1053
+			// pew pew pew
1054
+			$this->loader->getShared('EventEspresso\core\services\licensing\LicenseService');
1055
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1056
+		}
1057
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 *    set_hooks_for_core
1064
+	 *
1065
+	 * @access public
1066
+	 * @return    void
1067
+	 * @throws EE_Error
1068
+	 */
1069
+	public function set_hooks_for_core()
1070
+	{
1071
+		$this->_deactivate_incompatible_addons();
1072
+		do_action('AHEE__EE_System__set_hooks_for_core');
1073
+		$this->loader->getShared('EventEspresso\core\domain\values\session\SessionLifespan');
1074
+		//caps need to be initialized on every request so that capability maps are set.
1075
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1076
+		$this->registry->CAP->init_caps();
1077
+	}
1078
+
1079
+
1080
+
1081
+	/**
1082
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
1083
+	 * deactivates any addons considered incompatible with the current version of EE
1084
+	 */
1085
+	private function _deactivate_incompatible_addons()
1086
+	{
1087
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
1088
+		if (! empty($incompatible_addons)) {
1089
+			$active_plugins = get_option('active_plugins', array());
1090
+			foreach ($active_plugins as $active_plugin) {
1091
+				foreach ($incompatible_addons as $incompatible_addon) {
1092
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1093
+						unset($_GET['activate']);
1094
+						espresso_deactivate_plugin($active_plugin);
1095
+					}
1096
+				}
1097
+			}
1098
+		}
1099
+	}
1100
+
1101
+
1102
+
1103
+	/**
1104
+	 *    perform_activations_upgrades_and_migrations
1105
+	 *
1106
+	 * @access public
1107
+	 * @return    void
1108
+	 */
1109
+	public function perform_activations_upgrades_and_migrations()
1110
+	{
1111
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1112
+	}
1113
+
1114
+
1115
+	/**
1116
+	 * @return void
1117
+	 * @throws DomainException
1118
+	 */
1119
+	public function load_CPTs_and_session()
1120
+	{
1121
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1122
+		/** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies $register_custom_taxonomies */
1123
+		$register_custom_taxonomies = $this->loader->getShared(
1124
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'
1125
+		);
1126
+		$register_custom_taxonomies->registerCustomTaxonomies();
1127
+		/** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes $register_custom_post_types */
1128
+		$register_custom_post_types = $this->loader->getShared(
1129
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'
1130
+		);
1131
+		$register_custom_post_types->registerCustomPostTypes();
1132
+		/** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms $register_custom_taxonomy_terms */
1133
+		$register_custom_taxonomy_terms = $this->loader->getShared(
1134
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms'
1135
+		);
1136
+		$register_custom_taxonomy_terms->registerCustomTaxonomyTerms();
1137
+		// load legacy Custom Post Types and Taxonomies
1138
+		$this->loader->getShared('EE_Register_CPTs');
1139
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1140
+	}
1141
+
1142
+
1143
+
1144
+	/**
1145
+	 * load_controllers
1146
+	 * this is the best place to load any additional controllers that needs access to EE core.
1147
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1148
+	 * time
1149
+	 *
1150
+	 * @access public
1151
+	 * @return void
1152
+	 */
1153
+	public function load_controllers()
1154
+	{
1155
+		do_action('AHEE__EE_System__load_controllers__start');
1156
+		// let's get it started
1157
+		if (
1158
+			! $this->maintenance_mode->level()
1159
+			&& ($this->request->isFrontend() || $this->request->isFrontAjax())
1160
+		) {
1161
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1162
+			$this->loader->getShared('EE_Front_Controller');
1163
+		} elseif ($this->request->isAdmin() || $this->request->isAdminAjax()) {
1164
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1165
+			$this->loader->getShared('EE_Admin');
1166
+		}
1167
+		do_action('AHEE__EE_System__load_controllers__complete');
1168
+	}
1169
+
1170
+
1171
+
1172
+	/**
1173
+	 * core_loaded_and_ready
1174
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1175
+	 *
1176
+	 * @access public
1177
+	 * @return void
1178
+	 */
1179
+	public function core_loaded_and_ready()
1180
+	{
1181
+		if (
1182
+			$this->request->isAdmin()
1183
+			|| $this->request->isEeAjax()
1184
+			|| $this->request->isFrontend()
1185
+		) {
1186
+			$this->loader->getShared('EE_Session');
1187
+		}
1188
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1189
+		// load_espresso_template_tags
1190
+		if (
1191
+			is_readable(EE_PUBLIC . 'template_tags.php')
1192
+			&& ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isFeed())
1193
+		) {
1194
+			require_once EE_PUBLIC . 'template_tags.php';
1195
+		}
1196
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1197
+		if ($this->request->isAdmin() || $this->request->isFrontend() || $this->request->isIframe()) {
1198
+			$this->loader->getShared('EventEspresso\core\services\assets\Registry');
1199
+		}
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * initialize
1206
+	 * this is the best place to begin initializing client code
1207
+	 *
1208
+	 * @access public
1209
+	 * @return void
1210
+	 */
1211
+	public function initialize()
1212
+	{
1213
+		do_action('AHEE__EE_System__initialize');
1214
+	}
1215
+
1216
+
1217
+
1218
+	/**
1219
+	 * initialize_last
1220
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1221
+	 * initialize has done so
1222
+	 *
1223
+	 * @access public
1224
+	 * @return void
1225
+	 */
1226
+	public function initialize_last()
1227
+	{
1228
+		do_action('AHEE__EE_System__initialize_last');
1229
+		/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
1230
+		$rewrite_rules = $this->loader->getShared(
1231
+			'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
1232
+		);
1233
+		$rewrite_rules->flushRewriteRules();
1234
+		add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1235
+	}
1236
+
1237
+
1238
+
1239
+	/**
1240
+	 * @return void
1241
+	 * @throws EE_Error
1242
+	 */
1243
+	public function addEspressoToolbar()
1244
+	{
1245
+		$this->loader->getShared(
1246
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1247
+			array($this->registry->CAP)
1248
+		);
1249
+	}
1250
+
1251
+
1252
+
1253
+	/**
1254
+	 * do_not_cache
1255
+	 * sets no cache headers and defines no cache constants for WP plugins
1256
+	 *
1257
+	 * @access public
1258
+	 * @return void
1259
+	 */
1260
+	public static function do_not_cache()
1261
+	{
1262
+		// set no cache constants
1263
+		if (! defined('DONOTCACHEPAGE')) {
1264
+			define('DONOTCACHEPAGE', true);
1265
+		}
1266
+		if (! defined('DONOTCACHCEOBJECT')) {
1267
+			define('DONOTCACHCEOBJECT', true);
1268
+		}
1269
+		if (! defined('DONOTCACHEDB')) {
1270
+			define('DONOTCACHEDB', true);
1271
+		}
1272
+		// add no cache headers
1273
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1274
+		// plus a little extra for nginx and Google Chrome
1275
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1276
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1277
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1278
+	}
1279
+
1280
+
1281
+
1282
+	/**
1283
+	 *    extra_nocache_headers
1284
+	 *
1285
+	 * @access    public
1286
+	 * @param $headers
1287
+	 * @return    array
1288
+	 */
1289
+	public static function extra_nocache_headers($headers)
1290
+	{
1291
+		// for NGINX
1292
+		$headers['X-Accel-Expires'] = 0;
1293
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1294
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1295
+		return $headers;
1296
+	}
1297
+
1298
+
1299
+
1300
+	/**
1301
+	 *    nocache_headers
1302
+	 *
1303
+	 * @access    public
1304
+	 * @return    void
1305
+	 */
1306
+	public static function nocache_headers()
1307
+	{
1308
+		nocache_headers();
1309
+	}
1310
+
1311
+
1312
+
1313
+	/**
1314
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1315
+	 * never returned with the function.
1316
+	 *
1317
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1318
+	 * @return array
1319
+	 */
1320
+	public function remove_pages_from_wp_list_pages($exclude_array)
1321
+	{
1322
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1323
+	}
1324 1324
 
1325 1325
 
1326 1326
 
Please login to merge, or discard this patch.