Completed
Branch FET-9222-rest-api-writes (b5e9a6)
by
unknown
164:32 queued 152:41
created
core/helpers/EEH_Activation.helper.php 1 patch
Indentation   +1652 added lines, -1652 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 
5 5
 
@@ -14,243 +14,243 @@  discard block
 block discarded – undo
14 14
 class EEH_Activation
15 15
 {
16 16
 
17
-    /**
18
-     * constant used to indicate a cron task is no longer in use
19
-     */
20
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
21
-
22
-    /**
23
-     * option name that will indicate whether or not we still
24
-     * need to create EE's folders in the uploads directory
25
-     * (because if EE was installed without file system access,
26
-     * we need to request credentials before we can create them)
27
-     */
28
-    const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
29
-
30
-    /**
31
-     * WP_User->ID
32
-     *
33
-     * @var int
34
-     */
35
-    private static $_default_creator_id;
36
-
37
-    /**
38
-     * indicates whether or not we've already verified core's default data during this request,
39
-     * because after migrations are done, any addons activated while in maintenance mode
40
-     * will want to setup their own default data, and they might hook into core's default data
41
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
42
-     * This prevents doing that for EVERY single addon.
43
-     *
44
-     * @var boolean
45
-     */
46
-    protected static $_initialized_db_content_already_in_this_request = false;
47
-
48
-    /**
49
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
50
-     */
51
-    private static $table_analysis;
52
-
53
-    /**
54
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
55
-     */
56
-    private static $table_manager;
57
-
58
-
59
-    /**
60
-     * @return \EventEspresso\core\services\database\TableAnalysis
61
-     */
62
-    public static function getTableAnalysis()
63
-    {
64
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
65
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
66
-        }
67
-        return self::$table_analysis;
68
-    }
69
-
70
-
71
-    /**
72
-     * @return \EventEspresso\core\services\database\TableManager
73
-     */
74
-    public static function getTableManager()
75
-    {
76
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
77
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
78
-        }
79
-        return self::$table_manager;
80
-    }
81
-
82
-
83
-    /**
84
-     *    _ensure_table_name_has_prefix
85
-     *
86
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
87
-     * @access     public
88
-     * @static
89
-     * @param $table_name
90
-     * @return string
91
-     */
92
-    public static function ensure_table_name_has_prefix($table_name)
93
-    {
94
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
95
-    }
96
-
97
-
98
-    /**
99
-     *    system_initialization
100
-     *    ensures the EE configuration settings are loaded with at least default options set
101
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
102
-     *
103
-     * @access public
104
-     * @static
105
-     * @return void
106
-     */
107
-    public static function system_initialization()
108
-    {
109
-        EEH_Activation::reset_and_update_config();
110
-        //which is fired BEFORE activation of plugin anyways
111
-        EEH_Activation::verify_default_pages_exist();
112
-    }
113
-
114
-
115
-    /**
116
-     * Sets the database schema and creates folders. This should
117
-     * be called on plugin activation and reactivation
118
-     *
119
-     * @return boolean success, whether the database and folders are setup properly
120
-     * @throws \EE_Error
121
-     */
122
-    public static function initialize_db_and_folders()
123
-    {
124
-        $good_filesystem = EEH_Activation::create_upload_directories();
125
-        $good_db         = EEH_Activation::create_database_tables();
126
-        return $good_filesystem && $good_db;
127
-    }
128
-
129
-
130
-    /**
131
-     * assuming we have an up-to-date database schema, this will populate it
132
-     * with default and initial data. This should be called
133
-     * upon activation of a new plugin, reactivation, and at the end
134
-     * of running migration scripts
135
-     *
136
-     * @throws \EE_Error
137
-     */
138
-    public static function initialize_db_content()
139
-    {
140
-        //let's avoid doing all this logic repeatedly, especially when addons are requesting it
141
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
142
-            return;
143
-        }
144
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
145
-
146
-        EEH_Activation::initialize_system_questions();
147
-        EEH_Activation::insert_default_status_codes();
148
-        EEH_Activation::generate_default_message_templates();
149
-        EEH_Activation::create_no_ticket_prices_array();
150
-        EEH_Activation::validate_messages_system();
151
-        EEH_Activation::insert_default_payment_methods();
152
-        //in case we've
153
-        EEH_Activation::remove_cron_tasks();
154
-        EEH_Activation::create_cron_tasks();
155
-        // remove all TXN locks since that is being done via extra meta now
156
-        delete_option('ee_locked_transactions');
157
-        //also, check for CAF default db content
158
-        do_action('AHEE__EEH_Activation__initialize_db_content');
159
-        //also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
160
-        //which users really won't care about on initial activation
161
-        EE_Error::overwrite_success();
162
-    }
163
-
164
-
165
-    /**
166
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
167
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
168
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
169
-     * (null)
170
-     *
171
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
172
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
173
-     * @return array
174
-     * @throws \EE_Error
175
-     */
176
-    public static function get_cron_tasks($which_to_include)
177
-    {
178
-        $cron_tasks = apply_filters(
179
-            'FHEE__EEH_Activation__get_cron_tasks',
180
-            array(
181
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
17
+	/**
18
+	 * constant used to indicate a cron task is no longer in use
19
+	 */
20
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
21
+
22
+	/**
23
+	 * option name that will indicate whether or not we still
24
+	 * need to create EE's folders in the uploads directory
25
+	 * (because if EE was installed without file system access,
26
+	 * we need to request credentials before we can create them)
27
+	 */
28
+	const upload_directories_incomplete_option_name = 'ee_upload_directories_incomplete';
29
+
30
+	/**
31
+	 * WP_User->ID
32
+	 *
33
+	 * @var int
34
+	 */
35
+	private static $_default_creator_id;
36
+
37
+	/**
38
+	 * indicates whether or not we've already verified core's default data during this request,
39
+	 * because after migrations are done, any addons activated while in maintenance mode
40
+	 * will want to setup their own default data, and they might hook into core's default data
41
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
42
+	 * This prevents doing that for EVERY single addon.
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	protected static $_initialized_db_content_already_in_this_request = false;
47
+
48
+	/**
49
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
50
+	 */
51
+	private static $table_analysis;
52
+
53
+	/**
54
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
55
+	 */
56
+	private static $table_manager;
57
+
58
+
59
+	/**
60
+	 * @return \EventEspresso\core\services\database\TableAnalysis
61
+	 */
62
+	public static function getTableAnalysis()
63
+	{
64
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
65
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
66
+		}
67
+		return self::$table_analysis;
68
+	}
69
+
70
+
71
+	/**
72
+	 * @return \EventEspresso\core\services\database\TableManager
73
+	 */
74
+	public static function getTableManager()
75
+	{
76
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
77
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
78
+		}
79
+		return self::$table_manager;
80
+	}
81
+
82
+
83
+	/**
84
+	 *    _ensure_table_name_has_prefix
85
+	 *
86
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
87
+	 * @access     public
88
+	 * @static
89
+	 * @param $table_name
90
+	 * @return string
91
+	 */
92
+	public static function ensure_table_name_has_prefix($table_name)
93
+	{
94
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
95
+	}
96
+
97
+
98
+	/**
99
+	 *    system_initialization
100
+	 *    ensures the EE configuration settings are loaded with at least default options set
101
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
102
+	 *
103
+	 * @access public
104
+	 * @static
105
+	 * @return void
106
+	 */
107
+	public static function system_initialization()
108
+	{
109
+		EEH_Activation::reset_and_update_config();
110
+		//which is fired BEFORE activation of plugin anyways
111
+		EEH_Activation::verify_default_pages_exist();
112
+	}
113
+
114
+
115
+	/**
116
+	 * Sets the database schema and creates folders. This should
117
+	 * be called on plugin activation and reactivation
118
+	 *
119
+	 * @return boolean success, whether the database and folders are setup properly
120
+	 * @throws \EE_Error
121
+	 */
122
+	public static function initialize_db_and_folders()
123
+	{
124
+		$good_filesystem = EEH_Activation::create_upload_directories();
125
+		$good_db         = EEH_Activation::create_database_tables();
126
+		return $good_filesystem && $good_db;
127
+	}
128
+
129
+
130
+	/**
131
+	 * assuming we have an up-to-date database schema, this will populate it
132
+	 * with default and initial data. This should be called
133
+	 * upon activation of a new plugin, reactivation, and at the end
134
+	 * of running migration scripts
135
+	 *
136
+	 * @throws \EE_Error
137
+	 */
138
+	public static function initialize_db_content()
139
+	{
140
+		//let's avoid doing all this logic repeatedly, especially when addons are requesting it
141
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
142
+			return;
143
+		}
144
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
145
+
146
+		EEH_Activation::initialize_system_questions();
147
+		EEH_Activation::insert_default_status_codes();
148
+		EEH_Activation::generate_default_message_templates();
149
+		EEH_Activation::create_no_ticket_prices_array();
150
+		EEH_Activation::validate_messages_system();
151
+		EEH_Activation::insert_default_payment_methods();
152
+		//in case we've
153
+		EEH_Activation::remove_cron_tasks();
154
+		EEH_Activation::create_cron_tasks();
155
+		// remove all TXN locks since that is being done via extra meta now
156
+		delete_option('ee_locked_transactions');
157
+		//also, check for CAF default db content
158
+		do_action('AHEE__EEH_Activation__initialize_db_content');
159
+		//also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
160
+		//which users really won't care about on initial activation
161
+		EE_Error::overwrite_success();
162
+	}
163
+
164
+
165
+	/**
166
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
167
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
168
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
169
+	 * (null)
170
+	 *
171
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
172
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
173
+	 * @return array
174
+	 * @throws \EE_Error
175
+	 */
176
+	public static function get_cron_tasks($which_to_include)
177
+	{
178
+		$cron_tasks = apply_filters(
179
+			'FHEE__EEH_Activation__get_cron_tasks',
180
+			array(
181
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
182 182
 //				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
183
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
184
-                //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
185
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
186
-            )
187
-        );
188
-        if ($which_to_include === 'old') {
189
-            $cron_tasks = array_filter(
190
-                $cron_tasks,
191
-                function ($value) {
192
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
193
-                }
194
-            );
195
-        } elseif ($which_to_include === 'current') {
196
-            $cron_tasks = array_filter($cron_tasks);
197
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
198
-            throw new EE_Error(
199
-                sprintf(
200
-                    __(
201
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
202
-                        'event_espresso'
203
-                    ),
204
-                    $which_to_include
205
-                )
206
-            );
207
-        }
208
-        return $cron_tasks;
209
-    }
210
-
211
-
212
-    /**
213
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
214
-     *
215
-     * @throws \EE_Error
216
-     */
217
-    public static function create_cron_tasks()
218
-    {
219
-
220
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
221
-            if (! wp_next_scheduled($hook_name)) {
222
-                /**
223
-                 * This allows client code to define the initial start timestamp for this schedule.
224
-                 */
225
-                if (is_array($frequency)
226
-                    && count($frequency) === 2
227
-                    && isset($frequency[0], $frequency[1])
228
-                ) {
229
-                    $start_timestamp = $frequency[0];
230
-                    $frequency = $frequency[1];
231
-                } else {
232
-                    $start_timestamp = time();
233
-                }
234
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
235
-            }
236
-        }
237
-
238
-    }
239
-
240
-
241
-
242
-    /**
243
-     * Remove the currently-existing and now-removed cron tasks.
244
-     *
245
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
246
-     * @throws \EE_Error
247
-     */
248
-    public static function remove_cron_tasks($remove_all = true)
249
-    {
250
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
251
-        $crons                = _get_cron_array();
252
-        $crons                = is_array($crons) ? $crons : array();
253
-        /* reminder of what $crons look like:
183
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
184
+				//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
185
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
186
+			)
187
+		);
188
+		if ($which_to_include === 'old') {
189
+			$cron_tasks = array_filter(
190
+				$cron_tasks,
191
+				function ($value) {
192
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
193
+				}
194
+			);
195
+		} elseif ($which_to_include === 'current') {
196
+			$cron_tasks = array_filter($cron_tasks);
197
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
198
+			throw new EE_Error(
199
+				sprintf(
200
+					__(
201
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
202
+						'event_espresso'
203
+					),
204
+					$which_to_include
205
+				)
206
+			);
207
+		}
208
+		return $cron_tasks;
209
+	}
210
+
211
+
212
+	/**
213
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
214
+	 *
215
+	 * @throws \EE_Error
216
+	 */
217
+	public static function create_cron_tasks()
218
+	{
219
+
220
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
221
+			if (! wp_next_scheduled($hook_name)) {
222
+				/**
223
+				 * This allows client code to define the initial start timestamp for this schedule.
224
+				 */
225
+				if (is_array($frequency)
226
+					&& count($frequency) === 2
227
+					&& isset($frequency[0], $frequency[1])
228
+				) {
229
+					$start_timestamp = $frequency[0];
230
+					$frequency = $frequency[1];
231
+				} else {
232
+					$start_timestamp = time();
233
+				}
234
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
235
+			}
236
+		}
237
+
238
+	}
239
+
240
+
241
+
242
+	/**
243
+	 * Remove the currently-existing and now-removed cron tasks.
244
+	 *
245
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
246
+	 * @throws \EE_Error
247
+	 */
248
+	public static function remove_cron_tasks($remove_all = true)
249
+	{
250
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
251
+		$crons                = _get_cron_array();
252
+		$crons                = is_array($crons) ? $crons : array();
253
+		/* reminder of what $crons look like:
254 254
          * Top-level keys are timestamps, and their values are arrays.
255 255
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
256 256
          * and their values are arrays.
@@ -267,912 +267,912 @@  discard block
 block discarded – undo
267 267
          *					...
268 268
          *      ...
269 269
          */
270
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
271
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
272
-            if (is_array($hooks_to_fire_at_time)) {
273
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
274
-                    if (isset($ee_cron_tasks_to_remove[$hook_name])
275
-                        && is_array($ee_cron_tasks_to_remove[$hook_name])
276
-                    ) {
277
-                        unset($crons[$timestamp][$hook_name]);
278
-                    }
279
-                }
280
-                //also take care of any empty cron timestamps.
281
-                if (empty($hooks_to_fire_at_time)) {
282
-                    unset($crons[$timestamp]);
283
-                }
284
-            }
285
-        }
286
-        _set_cron_array($crons);
287
-    }
288
-
289
-
290
-    /**
291
-     *    CPT_initialization
292
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
293
-     *
294
-     * @access public
295
-     * @static
296
-     * @return void
297
-     */
298
-    public static function CPT_initialization()
299
-    {
300
-        // register Custom Post Types
301
-        EE_Registry::instance()->load_core('Register_CPTs');
302
-        flush_rewrite_rules();
303
-    }
304
-
305
-
306
-
307
-    /**
308
-     *    reset_and_update_config
309
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
310
-     * If there is old calendar config data saved, then it will get converted on activation.
311
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
312
-     *
313
-     * @access public
314
-     * @static
315
-     * @return void
316
-     */
317
-    public static function reset_and_update_config()
318
-    {
319
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
320
-        add_filter(
321
-            'FHEE__EE_Config___load_core_config__config_settings',
322
-            array('EEH_Activation', 'migrate_old_config_data'),
323
-            10,
324
-            3
325
-        );
326
-        //EE_Config::reset();
327
-        if (! EE_Config::logging_enabled()) {
328
-            delete_option(EE_Config::LOG_NAME);
329
-        }
330
-    }
331
-
332
-
333
-    /**
334
-     *    load_calendar_config
335
-     *
336
-     * @access    public
337
-     * @return    void
338
-     */
339
-    public static function load_calendar_config()
340
-    {
341
-        // grab array of all plugin folders and loop thru it
342
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
343
-        if (empty($plugins)) {
344
-            return;
345
-        }
346
-        foreach ($plugins as $plugin_path) {
347
-            // grab plugin folder name from path
348
-            $plugin = basename($plugin_path);
349
-            // drill down to Espresso plugins
350
-            // then to calendar related plugins
351
-            if (
352
-                strpos($plugin, 'espresso') !== false
353
-                || strpos($plugin, 'Espresso') !== false
354
-                || strpos($plugin, 'ee4') !== false
355
-                || strpos($plugin, 'EE4') !== false
356
-                || strpos($plugin, 'calendar') !== false
357
-            ) {
358
-                // this is what we are looking for
359
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
360
-                // does it exist in this folder ?
361
-                if (is_readable($calendar_config)) {
362
-                    // YEAH! let's load it
363
-                    require_once($calendar_config);
364
-                }
365
-            }
366
-        }
367
-    }
368
-
369
-
370
-
371
-    /**
372
-     *    _migrate_old_config_data
373
-     *
374
-     * @access    public
375
-     * @param array|stdClass $settings
376
-     * @param string         $config
377
-     * @param \EE_Config     $EE_Config
378
-     * @return \stdClass
379
-     */
380
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
381
-    {
382
-        $convert_from_array = array('addons');
383
-        // in case old settings were saved as an array
384
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
385
-            // convert existing settings to an object
386
-            $config_array = $settings;
387
-            $settings = new stdClass();
388
-            foreach ($config_array as $key => $value) {
389
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
390
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
391
-                } else {
392
-                    $settings->{$key} = $value;
393
-                }
394
-            }
395
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
396
-        }
397
-        return $settings;
398
-    }
399
-
400
-
401
-    /**
402
-     * deactivate_event_espresso
403
-     *
404
-     * @access public
405
-     * @static
406
-     * @return void
407
-     */
408
-    public static function deactivate_event_espresso()
409
-    {
410
-        // check permissions
411
-        if (current_user_can('activate_plugins')) {
412
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
413
-        }
414
-    }
415
-
416
-
417
-
418
-
419
-    /**
420
-     * verify_default_pages_exist
421
-     *
422
-     * @access public
423
-     * @static
424
-     * @return void
425
-     */
426
-    public static function verify_default_pages_exist()
427
-    {
428
-        $critical_page_problem = false;
429
-        $critical_pages = array(
430
-            array(
431
-                'id'   => 'reg_page_id',
432
-                'name' => __('Registration Checkout', 'event_espresso'),
433
-                'post' => null,
434
-                'code' => 'ESPRESSO_CHECKOUT',
435
-            ),
436
-            array(
437
-                'id'   => 'txn_page_id',
438
-                'name' => __('Transactions', 'event_espresso'),
439
-                'post' => null,
440
-                'code' => 'ESPRESSO_TXN_PAGE',
441
-            ),
442
-            array(
443
-                'id'   => 'thank_you_page_id',
444
-                'name' => __('Thank You', 'event_espresso'),
445
-                'post' => null,
446
-                'code' => 'ESPRESSO_THANK_YOU',
447
-            ),
448
-            array(
449
-                'id'   => 'cancel_page_id',
450
-                'name' => __('Registration Cancelled', 'event_espresso'),
451
-                'post' => null,
452
-                'code' => 'ESPRESSO_CANCELLED',
453
-            ),
454
-        );
455
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
456
-        foreach ($critical_pages as $critical_page) {
457
-            // is critical page ID set in config ?
458
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
459
-                // attempt to find post by ID
460
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
461
-            }
462
-            // no dice?
463
-            if ($critical_page['post'] === null) {
464
-                // attempt to find post by title
465
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
466
-                // still nothing?
467
-                if ($critical_page['post'] === null) {
468
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
469
-                    // REALLY? Still nothing ??!?!?
470
-                    if ($critical_page['post'] === null) {
471
-                        $msg = __(
472
-                            'The Event Espresso critical page configuration settings could not be updated.',
473
-                            'event_espresso'
474
-                        );
475
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
476
-                        break;
477
-                    }
478
-                }
479
-            }
480
-            // check that Post ID matches critical page ID in config
481
-            if (
482
-                isset($critical_page['post']->ID)
483
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
484
-            ) {
485
-                //update Config with post ID
486
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
487
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
488
-                    $msg = __(
489
-                        'The Event Espresso critical page configuration settings could not be updated.',
490
-                        'event_espresso'
491
-                    );
492
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
493
-                }
494
-            }
495
-            $critical_page_problem =
496
-                ! isset($critical_page['post']->post_status)
497
-                || $critical_page['post']->post_status !== 'publish'
498
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
499
-                    ? true
500
-                    : $critical_page_problem;
501
-        }
502
-        if ($critical_page_problem) {
503
-            $msg = sprintf(
504
-                __(
505
-                    'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
506
-                    'event_espresso'
507
-                ),
508
-                '<a href="'
509
-                . admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
510
-                . '">'
511
-                . __('Event Espresso Critical Pages Settings', 'event_espresso')
512
-                . '</a>'
513
-            );
514
-            EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
515
-        }
516
-        if (EE_Error::has_notices()) {
517
-            EE_Error::get_notices(false, true, true);
518
-        }
519
-    }
520
-
521
-
522
-
523
-    /**
524
-     * Returns the first post which uses the specified shortcode
525
-     *
526
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
527
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
528
-     *                             "[ESPRESSO_THANK_YOU"
529
-     *                             (we don't search for the closing shortcode bracket because they might have added
530
-     *                             parameter to the shortcode
531
-     * @return WP_Post or NULl
532
-     */
533
-    public static function get_page_by_ee_shortcode($ee_shortcode)
534
-    {
535
-        global $wpdb;
536
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
537
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
538
-        if ($post_id) {
539
-            return get_post($post_id);
540
-        } else {
541
-            return null;
542
-        }
543
-    }
544
-
545
-
546
-
547
-    /**
548
-     *    This function generates a post for critical espresso pages
549
-     *
550
-     * @access public
551
-     * @static
552
-     * @param array $critical_page
553
-     * @return array
554
-     */
555
-    public static function create_critical_page($critical_page)
556
-    {
557
-
558
-        $post_args = array(
559
-            'post_title'     => $critical_page['name'],
560
-            'post_status'    => 'publish',
561
-            'post_type'      => 'page',
562
-            'comment_status' => 'closed',
563
-            'post_content'   => '[' . $critical_page['code'] . ']',
564
-        );
565
-
566
-        $post_id = wp_insert_post($post_args);
567
-        if (! $post_id) {
568
-            $msg = sprintf(
569
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
570
-                $critical_page['name']
571
-            );
572
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
573
-            return $critical_page;
574
-        }
575
-        // get newly created post's details
576
-        if (! $critical_page['post'] = get_post($post_id)) {
577
-            $msg = sprintf(
578
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
579
-                $critical_page['name']
580
-            );
581
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
582
-        }
583
-
584
-        return $critical_page;
585
-
586
-    }
587
-
588
-
589
-
590
-
591
-    /**
592
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
593
-     * The role being used to check is filterable.
594
-     *
595
-     * @since  4.6.0
596
-     * @global WPDB $wpdb
597
-     * @return mixed null|int WP_user ID or NULL
598
-     */
599
-    public static function get_default_creator_id()
600
-    {
601
-        global $wpdb;
602
-        if ( ! empty(self::$_default_creator_id)) {
603
-            return self::$_default_creator_id;
604
-        }/**/
605
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
606
-        //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.
607
-        $pre_filtered_id = apply_filters(
608
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
609
-            false,
610
-            $role_to_check
611
-        );
612
-        if ($pre_filtered_id !== false) {
613
-            return (int)$pre_filtered_id;
614
-        }
615
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
616
-        $query = $wpdb->prepare(
617
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
618
-            '%' . $role_to_check . '%'
619
-        );
620
-        $user_id = $wpdb->get_var($query);
621
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
622
-        if ($user_id && (int)$user_id) {
623
-            self::$_default_creator_id = (int)$user_id;
624
-            return self::$_default_creator_id;
625
-        } else {
626
-            return null;
627
-        }
628
-    }
629
-
630
-
631
-
632
-    /**
633
-     * used by EE and EE addons during plugin activation to create tables.
634
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
635
-     * but includes extra logic regarding activations.
636
-     *
637
-     * @access public
638
-     * @static
639
-     * @param string  $table_name              without the $wpdb->prefix
640
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
641
-     *                                         table query)
642
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
643
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
644
-     *                                         and new once this function is done (ie, you really do want to CREATE a
645
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
646
-     *                                         you just want to verify the table exists and matches this definition
647
-     *                                         (and if it HAS data in it you want to leave it be)
648
-     * @return void
649
-     * @throws EE_Error if there are database errors
650
-     */
651
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
652
-    {
653
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
654
-            return;
655
-        }
656
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
657
-        if ( ! function_exists('dbDelta')) {
658
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
659
-        }
660
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
661
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
662
-        // do we need to first delete an existing version of this table ?
663
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
664
-            // ok, delete the table... but ONLY if it's empty
665
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
666
-            // table is NOT empty, are you SURE you want to delete this table ???
667
-            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
668
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
669
-            } else if ( ! $deleted_safely) {
670
-                // so we should be more cautious rather than just dropping tables so easily
671
-                error_log(
672
-                    sprintf(
673
-                        __(
674
-                            '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.',
675
-                            'event_espresso'
676
-                        ),
677
-                        $wp_table_name,
678
-                        '<br/>',
679
-                        'espresso_db_update'
680
-                    )
681
-                );
682
-            }
683
-        }
684
-        $engine = str_replace('ENGINE=', '', $engine);
685
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
686
-    }
687
-
688
-
689
-
690
-    /**
691
-     *    add_column_if_it_doesn't_exist
692
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
693
-     *
694
-     * @access     public
695
-     * @static
696
-     * @deprecated instead use TableManager::addColumn()
697
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
698
-     * @param string $column_name
699
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
700
-     *                            'VARCHAR(10)'
701
-     * @return bool|int
702
-     */
703
-    public static function add_column_if_it_doesnt_exist(
704
-        $table_name,
705
-        $column_name,
706
-        $column_info = 'INT UNSIGNED NOT NULL'
707
-    ) {
708
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
709
-    }
710
-
711
-
712
-    /**
713
-     * get_fields_on_table
714
-     * Gets all the fields on the database table.
715
-     *
716
-     * @access     public
717
-     * @deprecated instead use TableManager::getTableColumns()
718
-     * @static
719
-     * @param string $table_name , without prefixed $wpdb->prefix
720
-     * @return array of database column names
721
-     */
722
-    public static function get_fields_on_table($table_name = null)
723
-    {
724
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
725
-    }
726
-
727
-
728
-    /**
729
-     * db_table_is_empty
730
-     *
731
-     * @access     public\
732
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
733
-     * @static
734
-     * @param string $table_name
735
-     * @return bool
736
-     */
737
-    public static function db_table_is_empty($table_name)
738
-    {
739
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
740
-    }
741
-
742
-
743
-    /**
744
-     * delete_db_table_if_empty
745
-     *
746
-     * @access public
747
-     * @static
748
-     * @param string $table_name
749
-     * @return bool | int
750
-     */
751
-    public static function delete_db_table_if_empty($table_name)
752
-    {
753
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
754
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
755
-        }
756
-        return false;
757
-    }
758
-
759
-
760
-    /**
761
-     * delete_unused_db_table
762
-     *
763
-     * @access     public
764
-     * @static
765
-     * @deprecated instead use TableManager::dropTable()
766
-     * @param string $table_name
767
-     * @return bool | int
768
-     */
769
-    public static function delete_unused_db_table($table_name)
770
-    {
771
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
772
-    }
773
-
774
-
775
-    /**
776
-     * drop_index
777
-     *
778
-     * @access     public
779
-     * @static
780
-     * @deprecated instead use TableManager::dropIndex()
781
-     * @param string $table_name
782
-     * @param string $index_name
783
-     * @return bool | int
784
-     */
785
-    public static function drop_index($table_name, $index_name)
786
-    {
787
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
788
-    }
789
-
790
-
791
-
792
-    /**
793
-     * create_database_tables
794
-     *
795
-     * @access public
796
-     * @static
797
-     * @throws EE_Error
798
-     * @return boolean success (whether database is setup properly or not)
799
-     */
800
-    public static function create_database_tables()
801
-    {
802
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
803
-        //find the migration script that sets the database to be compatible with the code
804
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
805
-        if ($dms_name) {
806
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
807
-            $current_data_migration_script->set_migrating(false);
808
-            $current_data_migration_script->schema_changes_before_migration();
809
-            $current_data_migration_script->schema_changes_after_migration();
810
-            if ($current_data_migration_script->get_errors()) {
811
-                if (WP_DEBUG) {
812
-                    foreach ($current_data_migration_script->get_errors() as $error) {
813
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
814
-                    }
815
-                } else {
816
-                    EE_Error::add_error(
817
-                        __(
818
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
270
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
271
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
272
+			if (is_array($hooks_to_fire_at_time)) {
273
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
274
+					if (isset($ee_cron_tasks_to_remove[$hook_name])
275
+						&& is_array($ee_cron_tasks_to_remove[$hook_name])
276
+					) {
277
+						unset($crons[$timestamp][$hook_name]);
278
+					}
279
+				}
280
+				//also take care of any empty cron timestamps.
281
+				if (empty($hooks_to_fire_at_time)) {
282
+					unset($crons[$timestamp]);
283
+				}
284
+			}
285
+		}
286
+		_set_cron_array($crons);
287
+	}
288
+
289
+
290
+	/**
291
+	 *    CPT_initialization
292
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
293
+	 *
294
+	 * @access public
295
+	 * @static
296
+	 * @return void
297
+	 */
298
+	public static function CPT_initialization()
299
+	{
300
+		// register Custom Post Types
301
+		EE_Registry::instance()->load_core('Register_CPTs');
302
+		flush_rewrite_rules();
303
+	}
304
+
305
+
306
+
307
+	/**
308
+	 *    reset_and_update_config
309
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
310
+	 * If there is old calendar config data saved, then it will get converted on activation.
311
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
312
+	 *
313
+	 * @access public
314
+	 * @static
315
+	 * @return void
316
+	 */
317
+	public static function reset_and_update_config()
318
+	{
319
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
320
+		add_filter(
321
+			'FHEE__EE_Config___load_core_config__config_settings',
322
+			array('EEH_Activation', 'migrate_old_config_data'),
323
+			10,
324
+			3
325
+		);
326
+		//EE_Config::reset();
327
+		if (! EE_Config::logging_enabled()) {
328
+			delete_option(EE_Config::LOG_NAME);
329
+		}
330
+	}
331
+
332
+
333
+	/**
334
+	 *    load_calendar_config
335
+	 *
336
+	 * @access    public
337
+	 * @return    void
338
+	 */
339
+	public static function load_calendar_config()
340
+	{
341
+		// grab array of all plugin folders and loop thru it
342
+		$plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
343
+		if (empty($plugins)) {
344
+			return;
345
+		}
346
+		foreach ($plugins as $plugin_path) {
347
+			// grab plugin folder name from path
348
+			$plugin = basename($plugin_path);
349
+			// drill down to Espresso plugins
350
+			// then to calendar related plugins
351
+			if (
352
+				strpos($plugin, 'espresso') !== false
353
+				|| strpos($plugin, 'Espresso') !== false
354
+				|| strpos($plugin, 'ee4') !== false
355
+				|| strpos($plugin, 'EE4') !== false
356
+				|| strpos($plugin, 'calendar') !== false
357
+			) {
358
+				// this is what we are looking for
359
+				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
360
+				// does it exist in this folder ?
361
+				if (is_readable($calendar_config)) {
362
+					// YEAH! let's load it
363
+					require_once($calendar_config);
364
+				}
365
+			}
366
+		}
367
+	}
368
+
369
+
370
+
371
+	/**
372
+	 *    _migrate_old_config_data
373
+	 *
374
+	 * @access    public
375
+	 * @param array|stdClass $settings
376
+	 * @param string         $config
377
+	 * @param \EE_Config     $EE_Config
378
+	 * @return \stdClass
379
+	 */
380
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
381
+	{
382
+		$convert_from_array = array('addons');
383
+		// in case old settings were saved as an array
384
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
385
+			// convert existing settings to an object
386
+			$config_array = $settings;
387
+			$settings = new stdClass();
388
+			foreach ($config_array as $key => $value) {
389
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
390
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
391
+				} else {
392
+					$settings->{$key} = $value;
393
+				}
394
+			}
395
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
396
+		}
397
+		return $settings;
398
+	}
399
+
400
+
401
+	/**
402
+	 * deactivate_event_espresso
403
+	 *
404
+	 * @access public
405
+	 * @static
406
+	 * @return void
407
+	 */
408
+	public static function deactivate_event_espresso()
409
+	{
410
+		// check permissions
411
+		if (current_user_can('activate_plugins')) {
412
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
413
+		}
414
+	}
415
+
416
+
417
+
418
+
419
+	/**
420
+	 * verify_default_pages_exist
421
+	 *
422
+	 * @access public
423
+	 * @static
424
+	 * @return void
425
+	 */
426
+	public static function verify_default_pages_exist()
427
+	{
428
+		$critical_page_problem = false;
429
+		$critical_pages = array(
430
+			array(
431
+				'id'   => 'reg_page_id',
432
+				'name' => __('Registration Checkout', 'event_espresso'),
433
+				'post' => null,
434
+				'code' => 'ESPRESSO_CHECKOUT',
435
+			),
436
+			array(
437
+				'id'   => 'txn_page_id',
438
+				'name' => __('Transactions', 'event_espresso'),
439
+				'post' => null,
440
+				'code' => 'ESPRESSO_TXN_PAGE',
441
+			),
442
+			array(
443
+				'id'   => 'thank_you_page_id',
444
+				'name' => __('Thank You', 'event_espresso'),
445
+				'post' => null,
446
+				'code' => 'ESPRESSO_THANK_YOU',
447
+			),
448
+			array(
449
+				'id'   => 'cancel_page_id',
450
+				'name' => __('Registration Cancelled', 'event_espresso'),
451
+				'post' => null,
452
+				'code' => 'ESPRESSO_CANCELLED',
453
+			),
454
+		);
455
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
456
+		foreach ($critical_pages as $critical_page) {
457
+			// is critical page ID set in config ?
458
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
459
+				// attempt to find post by ID
460
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
461
+			}
462
+			// no dice?
463
+			if ($critical_page['post'] === null) {
464
+				// attempt to find post by title
465
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
466
+				// still nothing?
467
+				if ($critical_page['post'] === null) {
468
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
469
+					// REALLY? Still nothing ??!?!?
470
+					if ($critical_page['post'] === null) {
471
+						$msg = __(
472
+							'The Event Espresso critical page configuration settings could not be updated.',
473
+							'event_espresso'
474
+						);
475
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
476
+						break;
477
+					}
478
+				}
479
+			}
480
+			// check that Post ID matches critical page ID in config
481
+			if (
482
+				isset($critical_page['post']->ID)
483
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
484
+			) {
485
+				//update Config with post ID
486
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
487
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
488
+					$msg = __(
489
+						'The Event Espresso critical page configuration settings could not be updated.',
490
+						'event_espresso'
491
+					);
492
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
493
+				}
494
+			}
495
+			$critical_page_problem =
496
+				! isset($critical_page['post']->post_status)
497
+				|| $critical_page['post']->post_status !== 'publish'
498
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
499
+					? true
500
+					: $critical_page_problem;
501
+		}
502
+		if ($critical_page_problem) {
503
+			$msg = sprintf(
504
+				__(
505
+					'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
506
+					'event_espresso'
507
+				),
508
+				'<a href="'
509
+				. admin_url('admin.php?page=espresso_general_settings&action=critical_pages')
510
+				. '">'
511
+				. __('Event Espresso Critical Pages Settings', 'event_espresso')
512
+				. '</a>'
513
+			);
514
+			EE_Error::add_persistent_admin_notice('critical_page_problem', $msg);
515
+		}
516
+		if (EE_Error::has_notices()) {
517
+			EE_Error::get_notices(false, true, true);
518
+		}
519
+	}
520
+
521
+
522
+
523
+	/**
524
+	 * Returns the first post which uses the specified shortcode
525
+	 *
526
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
527
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
528
+	 *                             "[ESPRESSO_THANK_YOU"
529
+	 *                             (we don't search for the closing shortcode bracket because they might have added
530
+	 *                             parameter to the shortcode
531
+	 * @return WP_Post or NULl
532
+	 */
533
+	public static function get_page_by_ee_shortcode($ee_shortcode)
534
+	{
535
+		global $wpdb;
536
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
537
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
538
+		if ($post_id) {
539
+			return get_post($post_id);
540
+		} else {
541
+			return null;
542
+		}
543
+	}
544
+
545
+
546
+
547
+	/**
548
+	 *    This function generates a post for critical espresso pages
549
+	 *
550
+	 * @access public
551
+	 * @static
552
+	 * @param array $critical_page
553
+	 * @return array
554
+	 */
555
+	public static function create_critical_page($critical_page)
556
+	{
557
+
558
+		$post_args = array(
559
+			'post_title'     => $critical_page['name'],
560
+			'post_status'    => 'publish',
561
+			'post_type'      => 'page',
562
+			'comment_status' => 'closed',
563
+			'post_content'   => '[' . $critical_page['code'] . ']',
564
+		);
565
+
566
+		$post_id = wp_insert_post($post_args);
567
+		if (! $post_id) {
568
+			$msg = sprintf(
569
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
570
+				$critical_page['name']
571
+			);
572
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
573
+			return $critical_page;
574
+		}
575
+		// get newly created post's details
576
+		if (! $critical_page['post'] = get_post($post_id)) {
577
+			$msg = sprintf(
578
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
579
+				$critical_page['name']
580
+			);
581
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
582
+		}
583
+
584
+		return $critical_page;
585
+
586
+	}
587
+
588
+
589
+
590
+
591
+	/**
592
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
593
+	 * The role being used to check is filterable.
594
+	 *
595
+	 * @since  4.6.0
596
+	 * @global WPDB $wpdb
597
+	 * @return mixed null|int WP_user ID or NULL
598
+	 */
599
+	public static function get_default_creator_id()
600
+	{
601
+		global $wpdb;
602
+		if ( ! empty(self::$_default_creator_id)) {
603
+			return self::$_default_creator_id;
604
+		}/**/
605
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
606
+		//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.
607
+		$pre_filtered_id = apply_filters(
608
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
609
+			false,
610
+			$role_to_check
611
+		);
612
+		if ($pre_filtered_id !== false) {
613
+			return (int)$pre_filtered_id;
614
+		}
615
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
616
+		$query = $wpdb->prepare(
617
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
618
+			'%' . $role_to_check . '%'
619
+		);
620
+		$user_id = $wpdb->get_var($query);
621
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
622
+		if ($user_id && (int)$user_id) {
623
+			self::$_default_creator_id = (int)$user_id;
624
+			return self::$_default_creator_id;
625
+		} else {
626
+			return null;
627
+		}
628
+	}
629
+
630
+
631
+
632
+	/**
633
+	 * used by EE and EE addons during plugin activation to create tables.
634
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
635
+	 * but includes extra logic regarding activations.
636
+	 *
637
+	 * @access public
638
+	 * @static
639
+	 * @param string  $table_name              without the $wpdb->prefix
640
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
641
+	 *                                         table query)
642
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
643
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
644
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
645
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
646
+	 *                                         you just want to verify the table exists and matches this definition
647
+	 *                                         (and if it HAS data in it you want to leave it be)
648
+	 * @return void
649
+	 * @throws EE_Error if there are database errors
650
+	 */
651
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
652
+	{
653
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
654
+			return;
655
+		}
656
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
657
+		if ( ! function_exists('dbDelta')) {
658
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
659
+		}
660
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
661
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
662
+		// do we need to first delete an existing version of this table ?
663
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
664
+			// ok, delete the table... but ONLY if it's empty
665
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
666
+			// table is NOT empty, are you SURE you want to delete this table ???
667
+			if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
668
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
669
+			} else if ( ! $deleted_safely) {
670
+				// so we should be more cautious rather than just dropping tables so easily
671
+				error_log(
672
+					sprintf(
673
+						__(
674
+							'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.',
675
+							'event_espresso'
676
+						),
677
+						$wp_table_name,
678
+						'<br/>',
679
+						'espresso_db_update'
680
+					)
681
+				);
682
+			}
683
+		}
684
+		$engine = str_replace('ENGINE=', '', $engine);
685
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
686
+	}
687
+
688
+
689
+
690
+	/**
691
+	 *    add_column_if_it_doesn't_exist
692
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
693
+	 *
694
+	 * @access     public
695
+	 * @static
696
+	 * @deprecated instead use TableManager::addColumn()
697
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
698
+	 * @param string $column_name
699
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
700
+	 *                            'VARCHAR(10)'
701
+	 * @return bool|int
702
+	 */
703
+	public static function add_column_if_it_doesnt_exist(
704
+		$table_name,
705
+		$column_name,
706
+		$column_info = 'INT UNSIGNED NOT NULL'
707
+	) {
708
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
709
+	}
710
+
711
+
712
+	/**
713
+	 * get_fields_on_table
714
+	 * Gets all the fields on the database table.
715
+	 *
716
+	 * @access     public
717
+	 * @deprecated instead use TableManager::getTableColumns()
718
+	 * @static
719
+	 * @param string $table_name , without prefixed $wpdb->prefix
720
+	 * @return array of database column names
721
+	 */
722
+	public static function get_fields_on_table($table_name = null)
723
+	{
724
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
725
+	}
726
+
727
+
728
+	/**
729
+	 * db_table_is_empty
730
+	 *
731
+	 * @access     public\
732
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
733
+	 * @static
734
+	 * @param string $table_name
735
+	 * @return bool
736
+	 */
737
+	public static function db_table_is_empty($table_name)
738
+	{
739
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
740
+	}
741
+
742
+
743
+	/**
744
+	 * delete_db_table_if_empty
745
+	 *
746
+	 * @access public
747
+	 * @static
748
+	 * @param string $table_name
749
+	 * @return bool | int
750
+	 */
751
+	public static function delete_db_table_if_empty($table_name)
752
+	{
753
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
754
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
755
+		}
756
+		return false;
757
+	}
758
+
759
+
760
+	/**
761
+	 * delete_unused_db_table
762
+	 *
763
+	 * @access     public
764
+	 * @static
765
+	 * @deprecated instead use TableManager::dropTable()
766
+	 * @param string $table_name
767
+	 * @return bool | int
768
+	 */
769
+	public static function delete_unused_db_table($table_name)
770
+	{
771
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
772
+	}
773
+
774
+
775
+	/**
776
+	 * drop_index
777
+	 *
778
+	 * @access     public
779
+	 * @static
780
+	 * @deprecated instead use TableManager::dropIndex()
781
+	 * @param string $table_name
782
+	 * @param string $index_name
783
+	 * @return bool | int
784
+	 */
785
+	public static function drop_index($table_name, $index_name)
786
+	{
787
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
788
+	}
789
+
790
+
791
+
792
+	/**
793
+	 * create_database_tables
794
+	 *
795
+	 * @access public
796
+	 * @static
797
+	 * @throws EE_Error
798
+	 * @return boolean success (whether database is setup properly or not)
799
+	 */
800
+	public static function create_database_tables()
801
+	{
802
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
803
+		//find the migration script that sets the database to be compatible with the code
804
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
805
+		if ($dms_name) {
806
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
807
+			$current_data_migration_script->set_migrating(false);
808
+			$current_data_migration_script->schema_changes_before_migration();
809
+			$current_data_migration_script->schema_changes_after_migration();
810
+			if ($current_data_migration_script->get_errors()) {
811
+				if (WP_DEBUG) {
812
+					foreach ($current_data_migration_script->get_errors() as $error) {
813
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
814
+					}
815
+				} else {
816
+					EE_Error::add_error(
817
+						__(
818
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
819 819
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
820
-                            'event_espresso'
821
-                        )
822
-                    );
823
-                }
824
-                return false;
825
-            }
826
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
827
-        } else {
828
-            EE_Error::add_error(
829
-                __(
830
-                    'Could not determine most up-to-date data migration script from which to pull database schema
820
+							'event_espresso'
821
+						)
822
+					);
823
+				}
824
+				return false;
825
+			}
826
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
827
+		} else {
828
+			EE_Error::add_error(
829
+				__(
830
+					'Could not determine most up-to-date data migration script from which to pull database schema
831 831
                      structure. So database is probably not setup properly',
832
-                    'event_espresso'
833
-                ),
834
-                __FILE__,
835
-                __FUNCTION__,
836
-                __LINE__
837
-            );
838
-            return false;
839
-        }
840
-        return true;
841
-    }
842
-
843
-
844
-
845
-    /**
846
-     * initialize_system_questions
847
-     *
848
-     * @access public
849
-     * @static
850
-     * @return void
851
-     */
852
-    public static function initialize_system_questions()
853
-    {
854
-        // QUESTION GROUPS
855
-        global $wpdb;
856
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
857
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
858
-        // what we have
859
-        $question_groups = $wpdb->get_col($SQL);
860
-        // check the response
861
-        $question_groups = is_array($question_groups) ? $question_groups : array();
862
-        // what we should have
863
-        $QSG_systems = array(1, 2);
864
-        // loop thru what we should have and compare to what we have
865
-        foreach ($QSG_systems as $QSG_system) {
866
-            // reset values array
867
-            $QSG_values = array();
868
-            // 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)
869
-            if (! in_array("$QSG_system", $question_groups)) {
870
-                // add it
871
-                switch ($QSG_system) {
872
-                    case 1:
873
-                        $QSG_values = array(
874
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
875
-                            'QSG_identifier'      => 'personal-information-' . time(),
876
-                            'QSG_desc'            => '',
877
-                            'QSG_order'           => 1,
878
-                            'QSG_show_group_name' => 1,
879
-                            'QSG_show_group_desc' => 1,
880
-                            'QSG_system'          => EEM_Question_Group::system_personal,
881
-                            'QSG_deleted'         => 0,
882
-                        );
883
-                        break;
884
-                    case 2:
885
-                        $QSG_values = array(
886
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
887
-                            'QSG_identifier'      => 'address-information-' . time(),
888
-                            'QSG_desc'            => '',
889
-                            'QSG_order'           => 2,
890
-                            'QSG_show_group_name' => 1,
891
-                            'QSG_show_group_desc' => 1,
892
-                            'QSG_system'          => EEM_Question_Group::system_address,
893
-                            'QSG_deleted'         => 0,
894
-                        );
895
-                        break;
896
-                }
897
-                // make sure we have some values before inserting them
898
-                if (! empty($QSG_values)) {
899
-                    // insert system question
900
-                    $wpdb->insert(
901
-                        $table_name,
902
-                        $QSG_values,
903
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
904
-                    );
905
-                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
906
-                }
907
-            }
908
-        }
909
-        // QUESTIONS
910
-        global $wpdb;
911
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
912
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
913
-        // what we have
914
-        $questions = $wpdb->get_col($SQL);
915
-        // what we should have
916
-        $QST_systems = array(
917
-            'fname',
918
-            'lname',
919
-            'email',
920
-            'address',
921
-            'address2',
922
-            'city',
923
-            'country',
924
-            'state',
925
-            'zip',
926
-            'phone',
927
-        );
928
-        $order_for_group_1 = 1;
929
-        $order_for_group_2 = 1;
930
-        // loop thru what we should have and compare to what we have
931
-        foreach ($QST_systems as $QST_system) {
932
-            // reset values array
933
-            $QST_values = array();
934
-            // if we don't have what we should have
935
-            if (! in_array($QST_system, $questions)) {
936
-                // add it
937
-                switch ($QST_system) {
938
-                    case 'fname':
939
-                        $QST_values = array(
940
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
941
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
942
-                            'QST_system'        => 'fname',
943
-                            'QST_type'          => 'TEXT',
944
-                            'QST_required'      => 1,
945
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
946
-                            'QST_order'         => 1,
947
-                            'QST_admin_only'    => 0,
948
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
949
-                            'QST_wp_user'       => self::get_default_creator_id(),
950
-                            'QST_deleted'       => 0,
951
-                        );
952
-                        break;
953
-                    case 'lname':
954
-                        $QST_values = array(
955
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
956
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
957
-                            'QST_system'        => 'lname',
958
-                            'QST_type'          => 'TEXT',
959
-                            'QST_required'      => 1,
960
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
961
-                            'QST_order'         => 2,
962
-                            'QST_admin_only'    => 0,
963
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
964
-                            'QST_wp_user'       => self::get_default_creator_id(),
965
-                            'QST_deleted'       => 0,
966
-                        );
967
-                        break;
968
-                    case 'email':
969
-                        $QST_values = array(
970
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
971
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
972
-                            'QST_system'        => 'email',
973
-                            'QST_type'          => 'EMAIL',
974
-                            'QST_required'      => 1,
975
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
976
-                            'QST_order'         => 3,
977
-                            'QST_admin_only'    => 0,
978
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
979
-                            'QST_wp_user'       => self::get_default_creator_id(),
980
-                            'QST_deleted'       => 0,
981
-                        );
982
-                        break;
983
-                    case 'address':
984
-                        $QST_values = array(
985
-                            'QST_display_text'  => __('Address', 'event_espresso'),
986
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
987
-                            'QST_system'        => 'address',
988
-                            'QST_type'          => 'TEXT',
989
-                            'QST_required'      => 0,
990
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
991
-                            'QST_order'         => 4,
992
-                            'QST_admin_only'    => 0,
993
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
994
-                            'QST_wp_user'       => self::get_default_creator_id(),
995
-                            'QST_deleted'       => 0,
996
-                        );
997
-                        break;
998
-                    case 'address2':
999
-                        $QST_values = array(
1000
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
1001
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1002
-                            'QST_system'        => 'address2',
1003
-                            'QST_type'          => 'TEXT',
1004
-                            'QST_required'      => 0,
1005
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1006
-                            'QST_order'         => 5,
1007
-                            'QST_admin_only'    => 0,
1008
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1009
-                            'QST_wp_user'       => self::get_default_creator_id(),
1010
-                            'QST_deleted'       => 0,
1011
-                        );
1012
-                        break;
1013
-                    case 'city':
1014
-                        $QST_values = array(
1015
-                            'QST_display_text'  => __('City', 'event_espresso'),
1016
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1017
-                            'QST_system'        => 'city',
1018
-                            'QST_type'          => 'TEXT',
1019
-                            'QST_required'      => 0,
1020
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1021
-                            'QST_order'         => 6,
1022
-                            'QST_admin_only'    => 0,
1023
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1024
-                            'QST_wp_user'       => self::get_default_creator_id(),
1025
-                            'QST_deleted'       => 0,
1026
-                        );
1027
-                        break;
1028
-                    case 'country':
1029
-                        $QST_values = array(
1030
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1031
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1032
-                            'QST_system'        => 'country',
1033
-                            'QST_type'          => 'COUNTRY',
1034
-                            'QST_required'      => 0,
1035
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1036
-                            'QST_order'         => 7,
1037
-                            'QST_admin_only'    => 0,
1038
-                            'QST_wp_user'       => self::get_default_creator_id(),
1039
-                            'QST_deleted'       => 0,
1040
-                        );
1041
-                        break;
1042
-                    case 'state':
1043
-                        $QST_values = array(
1044
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1045
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1046
-                            'QST_system'        => 'state',
1047
-                            'QST_type'          => 'STATE',
1048
-                            'QST_required'      => 0,
1049
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1050
-                            'QST_order'         => 8,
1051
-                            'QST_admin_only'    => 0,
1052
-                            'QST_wp_user'       => self::get_default_creator_id(),
1053
-                            'QST_deleted'       => 0,
1054
-                        );
1055
-                        break;
1056
-                    case 'zip':
1057
-                        $QST_values = array(
1058
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1059
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1060
-                            'QST_system'        => 'zip',
1061
-                            'QST_type'          => 'TEXT',
1062
-                            'QST_required'      => 0,
1063
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1064
-                            'QST_order'         => 9,
1065
-                            'QST_admin_only'    => 0,
1066
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1067
-                            'QST_wp_user'       => self::get_default_creator_id(),
1068
-                            'QST_deleted'       => 0,
1069
-                        );
1070
-                        break;
1071
-                    case 'phone':
1072
-                        $QST_values = array(
1073
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1074
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1075
-                            'QST_system'        => 'phone',
1076
-                            'QST_type'          => 'TEXT',
1077
-                            'QST_required'      => 0,
1078
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1079
-                            'QST_order'         => 10,
1080
-                            'QST_admin_only'    => 0,
1081
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1082
-                            'QST_wp_user'       => self::get_default_creator_id(),
1083
-                            'QST_deleted'       => 0,
1084
-                        );
1085
-                        break;
1086
-                }
1087
-                if (! empty($QST_values)) {
1088
-                    // insert system question
1089
-                    $wpdb->insert(
1090
-                        $table_name,
1091
-                        $QST_values,
1092
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1093
-                    );
1094
-                    $QST_ID = $wpdb->insert_id;
1095
-                    // QUESTION GROUP QUESTIONS
1096
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1097
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1098
-                    } else {
1099
-                        $system_question_we_want = EEM_Question_Group::system_address;
1100
-                    }
1101
-                    if (isset($QSG_IDs[$system_question_we_want])) {
1102
-                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1103
-                    } else {
1104
-                        $id_col = EEM_Question_Group::instance()
1105
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1106
-                        if (is_array($id_col)) {
1107
-                            $QSG_ID = reset($id_col);
1108
-                        } else {
1109
-                            //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
1110
-                            EE_Log::instance()->log(
1111
-                                __FILE__,
1112
-                                __FUNCTION__,
1113
-                                sprintf(
1114
-                                    __(
1115
-                                        'Could not associate question %1$s to a question group because no system question
832
+					'event_espresso'
833
+				),
834
+				__FILE__,
835
+				__FUNCTION__,
836
+				__LINE__
837
+			);
838
+			return false;
839
+		}
840
+		return true;
841
+	}
842
+
843
+
844
+
845
+	/**
846
+	 * initialize_system_questions
847
+	 *
848
+	 * @access public
849
+	 * @static
850
+	 * @return void
851
+	 */
852
+	public static function initialize_system_questions()
853
+	{
854
+		// QUESTION GROUPS
855
+		global $wpdb;
856
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
857
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
858
+		// what we have
859
+		$question_groups = $wpdb->get_col($SQL);
860
+		// check the response
861
+		$question_groups = is_array($question_groups) ? $question_groups : array();
862
+		// what we should have
863
+		$QSG_systems = array(1, 2);
864
+		// loop thru what we should have and compare to what we have
865
+		foreach ($QSG_systems as $QSG_system) {
866
+			// reset values array
867
+			$QSG_values = array();
868
+			// 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)
869
+			if (! in_array("$QSG_system", $question_groups)) {
870
+				// add it
871
+				switch ($QSG_system) {
872
+					case 1:
873
+						$QSG_values = array(
874
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
875
+							'QSG_identifier'      => 'personal-information-' . time(),
876
+							'QSG_desc'            => '',
877
+							'QSG_order'           => 1,
878
+							'QSG_show_group_name' => 1,
879
+							'QSG_show_group_desc' => 1,
880
+							'QSG_system'          => EEM_Question_Group::system_personal,
881
+							'QSG_deleted'         => 0,
882
+						);
883
+						break;
884
+					case 2:
885
+						$QSG_values = array(
886
+							'QSG_name'            => __('Address Information', 'event_espresso'),
887
+							'QSG_identifier'      => 'address-information-' . time(),
888
+							'QSG_desc'            => '',
889
+							'QSG_order'           => 2,
890
+							'QSG_show_group_name' => 1,
891
+							'QSG_show_group_desc' => 1,
892
+							'QSG_system'          => EEM_Question_Group::system_address,
893
+							'QSG_deleted'         => 0,
894
+						);
895
+						break;
896
+				}
897
+				// make sure we have some values before inserting them
898
+				if (! empty($QSG_values)) {
899
+					// insert system question
900
+					$wpdb->insert(
901
+						$table_name,
902
+						$QSG_values,
903
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
904
+					);
905
+					$QSG_IDs[$QSG_system] = $wpdb->insert_id;
906
+				}
907
+			}
908
+		}
909
+		// QUESTIONS
910
+		global $wpdb;
911
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
912
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
913
+		// what we have
914
+		$questions = $wpdb->get_col($SQL);
915
+		// what we should have
916
+		$QST_systems = array(
917
+			'fname',
918
+			'lname',
919
+			'email',
920
+			'address',
921
+			'address2',
922
+			'city',
923
+			'country',
924
+			'state',
925
+			'zip',
926
+			'phone',
927
+		);
928
+		$order_for_group_1 = 1;
929
+		$order_for_group_2 = 1;
930
+		// loop thru what we should have and compare to what we have
931
+		foreach ($QST_systems as $QST_system) {
932
+			// reset values array
933
+			$QST_values = array();
934
+			// if we don't have what we should have
935
+			if (! in_array($QST_system, $questions)) {
936
+				// add it
937
+				switch ($QST_system) {
938
+					case 'fname':
939
+						$QST_values = array(
940
+							'QST_display_text'  => __('First Name', 'event_espresso'),
941
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
942
+							'QST_system'        => 'fname',
943
+							'QST_type'          => 'TEXT',
944
+							'QST_required'      => 1,
945
+							'QST_required_text' => __('This field is required', 'event_espresso'),
946
+							'QST_order'         => 1,
947
+							'QST_admin_only'    => 0,
948
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
949
+							'QST_wp_user'       => self::get_default_creator_id(),
950
+							'QST_deleted'       => 0,
951
+						);
952
+						break;
953
+					case 'lname':
954
+						$QST_values = array(
955
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
956
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
957
+							'QST_system'        => 'lname',
958
+							'QST_type'          => 'TEXT',
959
+							'QST_required'      => 1,
960
+							'QST_required_text' => __('This field is required', 'event_espresso'),
961
+							'QST_order'         => 2,
962
+							'QST_admin_only'    => 0,
963
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
964
+							'QST_wp_user'       => self::get_default_creator_id(),
965
+							'QST_deleted'       => 0,
966
+						);
967
+						break;
968
+					case 'email':
969
+						$QST_values = array(
970
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
971
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
972
+							'QST_system'        => 'email',
973
+							'QST_type'          => 'EMAIL',
974
+							'QST_required'      => 1,
975
+							'QST_required_text' => __('This field is required', 'event_espresso'),
976
+							'QST_order'         => 3,
977
+							'QST_admin_only'    => 0,
978
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
979
+							'QST_wp_user'       => self::get_default_creator_id(),
980
+							'QST_deleted'       => 0,
981
+						);
982
+						break;
983
+					case 'address':
984
+						$QST_values = array(
985
+							'QST_display_text'  => __('Address', 'event_espresso'),
986
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
987
+							'QST_system'        => 'address',
988
+							'QST_type'          => 'TEXT',
989
+							'QST_required'      => 0,
990
+							'QST_required_text' => __('This field is required', 'event_espresso'),
991
+							'QST_order'         => 4,
992
+							'QST_admin_only'    => 0,
993
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
994
+							'QST_wp_user'       => self::get_default_creator_id(),
995
+							'QST_deleted'       => 0,
996
+						);
997
+						break;
998
+					case 'address2':
999
+						$QST_values = array(
1000
+							'QST_display_text'  => __('Address2', 'event_espresso'),
1001
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
1002
+							'QST_system'        => 'address2',
1003
+							'QST_type'          => 'TEXT',
1004
+							'QST_required'      => 0,
1005
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1006
+							'QST_order'         => 5,
1007
+							'QST_admin_only'    => 0,
1008
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1009
+							'QST_wp_user'       => self::get_default_creator_id(),
1010
+							'QST_deleted'       => 0,
1011
+						);
1012
+						break;
1013
+					case 'city':
1014
+						$QST_values = array(
1015
+							'QST_display_text'  => __('City', 'event_espresso'),
1016
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1017
+							'QST_system'        => 'city',
1018
+							'QST_type'          => 'TEXT',
1019
+							'QST_required'      => 0,
1020
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1021
+							'QST_order'         => 6,
1022
+							'QST_admin_only'    => 0,
1023
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1024
+							'QST_wp_user'       => self::get_default_creator_id(),
1025
+							'QST_deleted'       => 0,
1026
+						);
1027
+						break;
1028
+					case 'country':
1029
+						$QST_values = array(
1030
+							'QST_display_text'  => __('Country', 'event_espresso'),
1031
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1032
+							'QST_system'        => 'country',
1033
+							'QST_type'          => 'COUNTRY',
1034
+							'QST_required'      => 0,
1035
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1036
+							'QST_order'         => 7,
1037
+							'QST_admin_only'    => 0,
1038
+							'QST_wp_user'       => self::get_default_creator_id(),
1039
+							'QST_deleted'       => 0,
1040
+						);
1041
+						break;
1042
+					case 'state':
1043
+						$QST_values = array(
1044
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1045
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1046
+							'QST_system'        => 'state',
1047
+							'QST_type'          => 'STATE',
1048
+							'QST_required'      => 0,
1049
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1050
+							'QST_order'         => 8,
1051
+							'QST_admin_only'    => 0,
1052
+							'QST_wp_user'       => self::get_default_creator_id(),
1053
+							'QST_deleted'       => 0,
1054
+						);
1055
+						break;
1056
+					case 'zip':
1057
+						$QST_values = array(
1058
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1059
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1060
+							'QST_system'        => 'zip',
1061
+							'QST_type'          => 'TEXT',
1062
+							'QST_required'      => 0,
1063
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1064
+							'QST_order'         => 9,
1065
+							'QST_admin_only'    => 0,
1066
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1067
+							'QST_wp_user'       => self::get_default_creator_id(),
1068
+							'QST_deleted'       => 0,
1069
+						);
1070
+						break;
1071
+					case 'phone':
1072
+						$QST_values = array(
1073
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1074
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1075
+							'QST_system'        => 'phone',
1076
+							'QST_type'          => 'TEXT',
1077
+							'QST_required'      => 0,
1078
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1079
+							'QST_order'         => 10,
1080
+							'QST_admin_only'    => 0,
1081
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1082
+							'QST_wp_user'       => self::get_default_creator_id(),
1083
+							'QST_deleted'       => 0,
1084
+						);
1085
+						break;
1086
+				}
1087
+				if (! empty($QST_values)) {
1088
+					// insert system question
1089
+					$wpdb->insert(
1090
+						$table_name,
1091
+						$QST_values,
1092
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1093
+					);
1094
+					$QST_ID = $wpdb->insert_id;
1095
+					// QUESTION GROUP QUESTIONS
1096
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1097
+						$system_question_we_want = EEM_Question_Group::system_personal;
1098
+					} else {
1099
+						$system_question_we_want = EEM_Question_Group::system_address;
1100
+					}
1101
+					if (isset($QSG_IDs[$system_question_we_want])) {
1102
+						$QSG_ID = $QSG_IDs[$system_question_we_want];
1103
+					} else {
1104
+						$id_col = EEM_Question_Group::instance()
1105
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1106
+						if (is_array($id_col)) {
1107
+							$QSG_ID = reset($id_col);
1108
+						} else {
1109
+							//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
1110
+							EE_Log::instance()->log(
1111
+								__FILE__,
1112
+								__FUNCTION__,
1113
+								sprintf(
1114
+									__(
1115
+										'Could not associate question %1$s to a question group because no system question
1116 1116
                                          group existed',
1117
-                                        'event_espresso'
1118
-                                    ),
1119
-                                    $QST_ID),
1120
-                                'error');
1121
-                            continue;
1122
-                        }
1123
-                    }
1124
-                    // add system questions to groups
1125
-                    $wpdb->insert(
1126
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1127
-                        array(
1128
-                            'QSG_ID'    => $QSG_ID,
1129
-                            'QST_ID'    => $QST_ID,
1130
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1131
-                        ),
1132
-                        array('%d', '%d', '%d')
1133
-                    );
1134
-                }
1135
-            }
1136
-        }
1137
-    }
1138
-
1139
-
1140
-    /**
1141
-     * Makes sure the default payment method (Invoice) is active.
1142
-     * This used to be done automatically as part of constructing the old gateways config
1143
-     *
1144
-     * @throws \EE_Error
1145
-     */
1146
-    public static function insert_default_payment_methods()
1147
-    {
1148
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1149
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1150
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1151
-        } else {
1152
-            EEM_Payment_Method::instance()->verify_button_urls();
1153
-        }
1154
-    }
1155
-
1156
-    /**
1157
-     * insert_default_status_codes
1158
-     *
1159
-     * @access public
1160
-     * @static
1161
-     * @return void
1162
-     */
1163
-    public static function insert_default_status_codes()
1164
-    {
1165
-
1166
-        global $wpdb;
1167
-
1168
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1169
-
1170
-            $table_name = EEM_Status::instance()->table();
1171
-
1172
-            $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' );";
1173
-            $wpdb->query($SQL);
1174
-
1175
-            $SQL = "INSERT INTO $table_name
1117
+										'event_espresso'
1118
+									),
1119
+									$QST_ID),
1120
+								'error');
1121
+							continue;
1122
+						}
1123
+					}
1124
+					// add system questions to groups
1125
+					$wpdb->insert(
1126
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1127
+						array(
1128
+							'QSG_ID'    => $QSG_ID,
1129
+							'QST_ID'    => $QST_ID,
1130
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1131
+						),
1132
+						array('%d', '%d', '%d')
1133
+					);
1134
+				}
1135
+			}
1136
+		}
1137
+	}
1138
+
1139
+
1140
+	/**
1141
+	 * Makes sure the default payment method (Invoice) is active.
1142
+	 * This used to be done automatically as part of constructing the old gateways config
1143
+	 *
1144
+	 * @throws \EE_Error
1145
+	 */
1146
+	public static function insert_default_payment_methods()
1147
+	{
1148
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1149
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1150
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1151
+		} else {
1152
+			EEM_Payment_Method::instance()->verify_button_urls();
1153
+		}
1154
+	}
1155
+
1156
+	/**
1157
+	 * insert_default_status_codes
1158
+	 *
1159
+	 * @access public
1160
+	 * @static
1161
+	 * @return void
1162
+	 */
1163
+	public static function insert_default_status_codes()
1164
+	{
1165
+
1166
+		global $wpdb;
1167
+
1168
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1169
+
1170
+			$table_name = EEM_Status::instance()->table();
1171
+
1172
+			$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' );";
1173
+			$wpdb->query($SQL);
1174
+
1175
+			$SQL = "INSERT INTO $table_name
1176 1176
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1177 1177
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1178 1178
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1212,521 +1212,521 @@  discard block
 block discarded – undo
1212 1212
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1213 1213
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1214 1214
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1215
-            $wpdb->query($SQL);
1216
-
1217
-        }
1218
-
1219
-    }
1220
-
1221
-
1222
-    /**
1223
-     * create_upload_directories
1224
-     * Creates folders in the uploads directory to facilitate addons and templates
1225
-     *
1226
-     * @access public
1227
-     * @static
1228
-     * @return boolean success of verifying upload directories exist
1229
-     */
1230
-    public static function create_upload_directories()
1231
-    {
1232
-        // Create the required folders
1233
-        $folders = array(
1234
-            EVENT_ESPRESSO_TEMPLATE_DIR,
1235
-            EVENT_ESPRESSO_GATEWAY_DIR,
1236
-            EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1237
-            EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1238
-            EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1239
-        );
1240
-        foreach ($folders as $folder) {
1241
-            try {
1242
-                EEH_File::ensure_folder_exists_and_is_writable($folder);
1243
-                @ chmod($folder, 0755);
1244
-            } catch (EE_Error $e) {
1245
-                EE_Error::add_error(
1246
-                    sprintf(
1247
-                        __('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1248
-                        $folder,
1249
-                        '<br />' . $e->getMessage()
1250
-                    ),
1251
-                    __FILE__, __FUNCTION__, __LINE__
1252
-                );
1253
-                //indicate we'll need to fix this later
1254
-                update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1255
-                return false;
1256
-            }
1257
-        }
1258
-        //just add the .htaccess file to the logs directory to begin with. Even if logging
1259
-        //is disabled, there might be activation errors recorded in there
1260
-        EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1261
-        //remember EE's folders are all good
1262
-        delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1263
-        return true;
1264
-    }
1265
-
1266
-    /**
1267
-     * Whether the upload directories need to be fixed or not.
1268
-     * If EE is installed but filesystem access isn't initially available,
1269
-     * we need to get the user's filesystem credentials and THEN create them,
1270
-     * so there might be period of time when EE is installed but its
1271
-     * upload directories aren't available. This indicates such a state
1272
-     *
1273
-     * @return boolean
1274
-     */
1275
-    public static function upload_directories_incomplete()
1276
-    {
1277
-        return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1278
-    }
1279
-
1280
-
1281
-    /**
1282
-     * generate_default_message_templates
1283
-     *
1284
-     * @static
1285
-     * @throws EE_Error
1286
-     * @return bool     true means new templates were created.
1287
-     *                  false means no templates were created.
1288
-     *                  This is NOT an error flag. To check for errors you will want
1289
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1290
-     */
1291
-    public static function generate_default_message_templates()
1292
-    {
1293
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1294
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1295
-        /*
1215
+			$wpdb->query($SQL);
1216
+
1217
+		}
1218
+
1219
+	}
1220
+
1221
+
1222
+	/**
1223
+	 * create_upload_directories
1224
+	 * Creates folders in the uploads directory to facilitate addons and templates
1225
+	 *
1226
+	 * @access public
1227
+	 * @static
1228
+	 * @return boolean success of verifying upload directories exist
1229
+	 */
1230
+	public static function create_upload_directories()
1231
+	{
1232
+		// Create the required folders
1233
+		$folders = array(
1234
+			EVENT_ESPRESSO_TEMPLATE_DIR,
1235
+			EVENT_ESPRESSO_GATEWAY_DIR,
1236
+			EVENT_ESPRESSO_UPLOAD_DIR . 'logs/',
1237
+			EVENT_ESPRESSO_UPLOAD_DIR . 'css/',
1238
+			EVENT_ESPRESSO_UPLOAD_DIR . 'tickets/',
1239
+		);
1240
+		foreach ($folders as $folder) {
1241
+			try {
1242
+				EEH_File::ensure_folder_exists_and_is_writable($folder);
1243
+				@ chmod($folder, 0755);
1244
+			} catch (EE_Error $e) {
1245
+				EE_Error::add_error(
1246
+					sprintf(
1247
+						__('Could not create the folder at "%1$s" because: %2$s', 'event_espresso'),
1248
+						$folder,
1249
+						'<br />' . $e->getMessage()
1250
+					),
1251
+					__FILE__, __FUNCTION__, __LINE__
1252
+				);
1253
+				//indicate we'll need to fix this later
1254
+				update_option(EEH_Activation::upload_directories_incomplete_option_name, true);
1255
+				return false;
1256
+			}
1257
+		}
1258
+		//just add the .htaccess file to the logs directory to begin with. Even if logging
1259
+		//is disabled, there might be activation errors recorded in there
1260
+		EEH_File::add_htaccess_deny_from_all(EVENT_ESPRESSO_UPLOAD_DIR . 'logs/');
1261
+		//remember EE's folders are all good
1262
+		delete_option(EEH_Activation::upload_directories_incomplete_option_name);
1263
+		return true;
1264
+	}
1265
+
1266
+	/**
1267
+	 * Whether the upload directories need to be fixed or not.
1268
+	 * If EE is installed but filesystem access isn't initially available,
1269
+	 * we need to get the user's filesystem credentials and THEN create them,
1270
+	 * so there might be period of time when EE is installed but its
1271
+	 * upload directories aren't available. This indicates such a state
1272
+	 *
1273
+	 * @return boolean
1274
+	 */
1275
+	public static function upload_directories_incomplete()
1276
+	{
1277
+		return get_option(EEH_Activation::upload_directories_incomplete_option_name, false);
1278
+	}
1279
+
1280
+
1281
+	/**
1282
+	 * generate_default_message_templates
1283
+	 *
1284
+	 * @static
1285
+	 * @throws EE_Error
1286
+	 * @return bool     true means new templates were created.
1287
+	 *                  false means no templates were created.
1288
+	 *                  This is NOT an error flag. To check for errors you will want
1289
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1290
+	 */
1291
+	public static function generate_default_message_templates()
1292
+	{
1293
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1294
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1295
+		/*
1296 1296
          * This first method is taking care of ensuring any default messengers
1297 1297
          * that should be made active and have templates generated are done.
1298 1298
          */
1299
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1300
-            $message_resource_manager
1301
-        );
1302
-        /**
1303
-         * This method is verifying there are no NEW default message types
1304
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1305
-         */
1306
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1307
-            $message_resource_manager
1308
-        );
1309
-        //after all is done, let's persist these changes to the db.
1310
-        $message_resource_manager->update_has_activated_messengers_option();
1311
-        $message_resource_manager->update_active_messengers_option();
1312
-        // will return true if either of these are true.  Otherwise will return false.
1313
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1314
-    }
1315
-
1316
-
1317
-
1318
-    /**
1319
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1320
-     * @return array|bool
1321
-     * @throws \EE_Error
1322
-     */
1323
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1324
-        EE_Message_Resource_Manager $message_resource_manager
1325
-    ) {
1326
-        /** @type EE_messenger[] $active_messengers */
1327
-        $active_messengers = $message_resource_manager->active_messengers();
1328
-        $installed_message_types = $message_resource_manager->installed_message_types();
1329
-        $templates_created = false;
1330
-        foreach ($active_messengers as $active_messenger) {
1331
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1332
-            $default_message_type_names_to_activate = array();
1333
-            // looping through each default message type reported by the messenger
1334
-            // and setup the actual message types to activate.
1335
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1336
-                // if already active or has already been activated before we skip
1337
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1338
-                // we also skip if the message type is not installed.
1339
-                if (
1340
-                    $message_resource_manager->has_message_type_been_activated_for_messenger(
1341
-                        $default_message_type_name_for_messenger,
1342
-                        $active_messenger->name
1343
-                    )
1344
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1345
-                        $active_messenger->name,
1346
-                        $default_message_type_name_for_messenger
1347
-                    )
1348
-                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1349
-                ) {
1350
-                    continue;
1351
-                }
1352
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1353
-            }
1354
-            //let's activate!
1355
-            $message_resource_manager->ensure_message_types_are_active(
1356
-                $default_message_type_names_to_activate,
1357
-                $active_messenger->name,
1358
-                false
1359
-            );
1360
-            //activate the templates for these message types
1361
-            if ( ! empty($default_message_type_names_to_activate)) {
1362
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1363
-                    $active_messenger->name,
1364
-                    $default_message_type_names_for_messenger,
1365
-                    '',
1366
-                    true
1367
-                );
1368
-            }
1369
-        }
1370
-        return $templates_created;
1371
-    }
1372
-
1373
-
1374
-
1375
-    /**
1376
-     * This will activate and generate default messengers and default message types for those messengers.
1377
-     *
1378
-     * @param EE_message_Resource_Manager $message_resource_manager
1379
-     * @return array|bool  True means there were default messengers and message type templates generated.
1380
-     *                     False means that there were no templates generated
1381
-     *                     (which could simply mean there are no default message types for a messenger).
1382
-     * @throws EE_Error
1383
-     */
1384
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1385
-        EE_Message_Resource_Manager $message_resource_manager
1386
-    ) {
1387
-        /** @type EE_messenger[] $messengers_to_generate */
1388
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1389
-        $installed_message_types = $message_resource_manager->installed_message_types();
1390
-        $templates_generated = false;
1391
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1392
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1393
-            //verify the default message types match an installed message type.
1394
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1395
-                if (
1396
-                    ! isset($installed_message_types[$name])
1397
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1398
-                        $name,
1399
-                        $messenger_to_generate->name
1400
-                    )
1401
-                ) {
1402
-                    unset($default_message_type_names_for_messenger[$key]);
1403
-                }
1404
-            }
1405
-            // in previous iterations, the active_messengers option in the db
1406
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1407
-            // This comment is left here just in case we discover that we _do_ need to update before
1408
-            // passing off to create templates (after the refactor is done).
1409
-            // @todo remove this comment when determined not necessary.
1410
-            $message_resource_manager->activate_messenger(
1411
-                $messenger_to_generate->name,
1412
-                $default_message_type_names_for_messenger,
1413
-                false
1414
-            );
1415
-            //create any templates needing created (or will reactivate templates already generated as necessary).
1416
-            if ( ! empty($default_message_type_names_for_messenger)) {
1417
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1418
-                    $messenger_to_generate->name,
1419
-                    $default_message_type_names_for_messenger,
1420
-                    '',
1421
-                    true
1422
-                );
1423
-            }
1424
-        }
1425
-        return $templates_generated;
1426
-    }
1427
-
1428
-
1429
-    /**
1430
-     * This returns the default messengers to generate templates for on activation of EE.
1431
-     * It considers:
1432
-     * - whether a messenger is already active in the db.
1433
-     * - whether a messenger has been made active at any time in the past.
1434
-     *
1435
-     * @static
1436
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1437
-     * @return EE_messenger[]
1438
-     */
1439
-    protected static function _get_default_messengers_to_generate_on_activation(
1440
-        EE_Message_Resource_Manager $message_resource_manager
1441
-    ) {
1442
-        $active_messengers    = $message_resource_manager->active_messengers();
1443
-        $installed_messengers = $message_resource_manager->installed_messengers();
1444
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1445
-
1446
-        $messengers_to_generate = array();
1447
-        foreach ($installed_messengers as $installed_messenger) {
1448
-            //if installed messenger is a messenger that should be activated on install
1449
-            //and is not already active
1450
-            //and has never been activated
1451
-            if (
1452
-                ! $installed_messenger->activate_on_install
1453
-                || isset($active_messengers[$installed_messenger->name])
1454
-                || isset($has_activated[$installed_messenger->name])
1455
-            ) {
1456
-                continue;
1457
-            }
1458
-            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1459
-        }
1460
-        return $messengers_to_generate;
1461
-    }
1462
-
1463
-
1464
-    /**
1465
-     * This simply validates active message types to ensure they actually match installed
1466
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1467
-     * rows are set inactive.
1468
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1469
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1470
-     * are still handled in here.
1471
-     *
1472
-     * @since 4.3.1
1473
-     * @return void
1474
-     */
1475
-    public static function validate_messages_system()
1476
-    {
1477
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1478
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1479
-        $message_resource_manager->validate_active_message_types_are_installed();
1480
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1481
-    }
1482
-
1483
-
1484
-    /**
1485
-     * create_no_ticket_prices_array
1486
-     *
1487
-     * @access public
1488
-     * @static
1489
-     * @return void
1490
-     */
1491
-    public static function create_no_ticket_prices_array()
1492
-    {
1493
-        // this creates an array for tracking events that have no active ticket prices created
1494
-        // this allows us to warn admins of the situation so that it can be corrected
1495
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1496
-        if (! $espresso_no_ticket_prices) {
1497
-            add_option('ee_no_ticket_prices', array(), '', false);
1498
-        }
1499
-    }
1500
-
1501
-
1502
-    /**
1503
-     * plugin_deactivation
1504
-     *
1505
-     * @access public
1506
-     * @static
1507
-     * @return void
1508
-     */
1509
-    public static function plugin_deactivation()
1510
-    {
1511
-    }
1512
-
1513
-
1514
-    /**
1515
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1516
-     * (like post meta or term relations)
1517
-     *
1518
-     * @global wpdb $wpdb
1519
-     * @throws \EE_Error
1520
-     */
1521
-    public static function delete_all_espresso_cpt_data()
1522
-    {
1523
-        global $wpdb;
1524
-        //get all the CPT post_types
1525
-        $ee_post_types = array();
1526
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1527
-            if (method_exists($model_name, 'instance')) {
1528
-                $model_obj = call_user_func(array($model_name, 'instance'));
1529
-                if ($model_obj instanceof EEM_CPT_Base) {
1530
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1531
-                }
1532
-            }
1533
-        }
1534
-        //get all our CPTs
1535
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1536
-        $cpt_ids = $wpdb->get_col($query);
1537
-        //delete each post meta and term relations too
1538
-        foreach ($cpt_ids as $post_id) {
1539
-            wp_delete_post($post_id, true);
1540
-        }
1541
-    }
1542
-
1543
-    /**
1544
-     * Deletes all EE custom tables
1545
-     *
1546
-     * @return array
1547
-     */
1548
-    public static function drop_espresso_tables()
1549
-    {
1550
-        $tables = array();
1551
-        // load registry
1552
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1553
-            if (method_exists($model_name, 'instance')) {
1554
-                $model_obj = call_user_func(array($model_name, 'instance'));
1555
-                if ($model_obj instanceof EEM_Base) {
1556
-                    foreach ($model_obj->get_tables() as $table) {
1557
-                        if (strpos($table->get_table_name(), 'esp_')
1558
-                            &&
1559
-                            (
1560
-                                is_main_site()//main site? nuke them all
1561
-                                || ! $table->is_global()//not main site,but not global either. nuke it
1562
-                            )
1563
-                        ) {
1564
-                            $tables[] = $table->get_table_name();
1565
-                        }
1566
-                    }
1567
-                }
1568
-            }
1569
-        }
1570
-
1571
-        //there are some tables whose models were removed.
1572
-        //they should be removed when removing all EE core's data
1573
-        $tables_without_models = array(
1574
-            'esp_promotion',
1575
-            'esp_promotion_applied',
1576
-            'esp_promotion_object',
1577
-            'esp_promotion_rule',
1578
-            'esp_rule',
1579
-        );
1580
-        foreach ($tables_without_models as $table) {
1581
-            $tables[] = $table;
1582
-        }
1583
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1584
-    }
1585
-
1586
-
1587
-
1588
-    /**
1589
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1590
-     * each table name provided has a wpdb prefix attached, and that it exists.
1591
-     * Returns the list actually deleted
1592
-     *
1593
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1594
-     * @global WPDB $wpdb
1595
-     * @param array $table_names
1596
-     * @return array of table names which we deleted
1597
-     */
1598
-    public static function drop_tables($table_names)
1599
-    {
1600
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1601
-    }
1602
-
1603
-
1604
-
1605
-    /**
1606
-     * plugin_uninstall
1607
-     *
1608
-     * @access public
1609
-     * @static
1610
-     * @param bool $remove_all
1611
-     * @return void
1612
-     */
1613
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1614
-    {
1615
-        global $wpdb;
1616
-        self::drop_espresso_tables();
1617
-        $wp_options_to_delete = array(
1618
-            'ee_no_ticket_prices'                => true,
1619
-            'ee_active_messengers'               => true,
1620
-            'ee_has_activated_messenger'         => true,
1621
-            'ee_flush_rewrite_rules'             => true,
1622
-            'ee_config'                          => false,
1623
-            'ee_data_migration_current_db_state' => true,
1624
-            'ee_data_migration_mapping_'         => false,
1625
-            'ee_data_migration_script_'          => false,
1626
-            'ee_data_migrations'                 => true,
1627
-            'ee_dms_map'                         => false,
1628
-            'ee_notices'                         => true,
1629
-            'lang_file_check_'                   => false,
1630
-            'ee_maintenance_mode'                => true,
1631
-            'ee_ueip_optin'                      => true,
1632
-            'ee_ueip_has_notified'               => true,
1633
-            'ee_plugin_activation_errors'        => true,
1634
-            'ee_id_mapping_from'                 => false,
1635
-            'espresso_persistent_admin_notices'  => true,
1636
-            'ee_encryption_key'                  => true,
1637
-            'pue_force_upgrade_'                 => false,
1638
-            'pue_json_error_'                    => false,
1639
-            'pue_install_key_'                   => false,
1640
-            'pue_verification_error_'            => false,
1641
-            'pu_dismissed_upgrade_'              => false,
1642
-            'external_updates-'                  => false,
1643
-            'ee_extra_data'                      => true,
1644
-            'ee_ssn_'                            => false,
1645
-            'ee_rss_'                            => false,
1646
-            'ee_rte_n_tx_'                       => false,
1647
-            'ee_pers_admin_notices'              => true,
1648
-            'ee_job_parameters_'                 => false,
1649
-            'ee_upload_directories_incomplete'   => true,
1650
-            'ee_verified_db_collations'          => true,
1651
-        );
1652
-        if (is_main_site()) {
1653
-            $wp_options_to_delete['ee_network_config'] = true;
1654
-        }
1655
-        $undeleted_options = array();
1656
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1657
-            if ($no_wildcard) {
1658
-                if ( ! delete_option($option_name)) {
1659
-                    $undeleted_options[] = $option_name;
1660
-                }
1661
-            } else {
1662
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1663
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1664
-                    if ( ! delete_option($option_name_from_wildcard)) {
1665
-                        $undeleted_options[] = $option_name_from_wildcard;
1666
-                    }
1667
-                }
1668
-            }
1669
-        }
1670
-        //also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1671
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1672
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1673
-            $db_update_sans_ee4 = array();
1674
-            foreach ($espresso_db_update as $version => $times_activated) {
1675
-                if ((string)$version[0] === '3') {//if its NON EE4
1676
-                    $db_update_sans_ee4[$version] = $times_activated;
1677
-                }
1678
-            }
1679
-            update_option('espresso_db_update', $db_update_sans_ee4);
1680
-        }
1681
-        $errors = '';
1682
-        if ( ! empty($undeleted_options)) {
1683
-            $errors .= sprintf(
1684
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1685
-                '<br/>',
1686
-                implode(',<br/>', $undeleted_options)
1687
-            );
1688
-        }
1689
-        if ( ! empty($errors)) {
1690
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1691
-        }
1692
-    }
1693
-
1694
-    /**
1695
-     * Gets the mysql error code from the last used query by wpdb
1696
-     *
1697
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1698
-     */
1699
-    public static function last_wpdb_error_code()
1700
-    {
1701
-        global $wpdb;
1702
-        if ($wpdb->use_mysqli) {
1703
-            return mysqli_errno($wpdb->dbh);
1704
-        } else {
1705
-            return mysql_errno($wpdb->dbh);
1706
-        }
1707
-    }
1708
-
1709
-    /**
1710
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1711
-     *
1712
-     * @global wpdb  $wpdb
1713
-     * @deprecated instead use TableAnalysis::tableExists()
1714
-     * @param string $table_name with or without $wpdb->prefix
1715
-     * @return boolean
1716
-     */
1717
-    public static function table_exists($table_name)
1718
-    {
1719
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1720
-    }
1721
-
1722
-    /**
1723
-     * Resets the cache on EEH_Activation
1724
-     */
1725
-    public static function reset()
1726
-    {
1727
-        self::$_default_creator_id                             = null;
1728
-        self::$_initialized_db_content_already_in_this_request = false;
1729
-    }
1299
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1300
+			$message_resource_manager
1301
+		);
1302
+		/**
1303
+		 * This method is verifying there are no NEW default message types
1304
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1305
+		 */
1306
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1307
+			$message_resource_manager
1308
+		);
1309
+		//after all is done, let's persist these changes to the db.
1310
+		$message_resource_manager->update_has_activated_messengers_option();
1311
+		$message_resource_manager->update_active_messengers_option();
1312
+		// will return true if either of these are true.  Otherwise will return false.
1313
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1314
+	}
1315
+
1316
+
1317
+
1318
+	/**
1319
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1320
+	 * @return array|bool
1321
+	 * @throws \EE_Error
1322
+	 */
1323
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1324
+		EE_Message_Resource_Manager $message_resource_manager
1325
+	) {
1326
+		/** @type EE_messenger[] $active_messengers */
1327
+		$active_messengers = $message_resource_manager->active_messengers();
1328
+		$installed_message_types = $message_resource_manager->installed_message_types();
1329
+		$templates_created = false;
1330
+		foreach ($active_messengers as $active_messenger) {
1331
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1332
+			$default_message_type_names_to_activate = array();
1333
+			// looping through each default message type reported by the messenger
1334
+			// and setup the actual message types to activate.
1335
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1336
+				// if already active or has already been activated before we skip
1337
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1338
+				// we also skip if the message type is not installed.
1339
+				if (
1340
+					$message_resource_manager->has_message_type_been_activated_for_messenger(
1341
+						$default_message_type_name_for_messenger,
1342
+						$active_messenger->name
1343
+					)
1344
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1345
+						$active_messenger->name,
1346
+						$default_message_type_name_for_messenger
1347
+					)
1348
+					|| ! isset($installed_message_types[$default_message_type_name_for_messenger])
1349
+				) {
1350
+					continue;
1351
+				}
1352
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1353
+			}
1354
+			//let's activate!
1355
+			$message_resource_manager->ensure_message_types_are_active(
1356
+				$default_message_type_names_to_activate,
1357
+				$active_messenger->name,
1358
+				false
1359
+			);
1360
+			//activate the templates for these message types
1361
+			if ( ! empty($default_message_type_names_to_activate)) {
1362
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1363
+					$active_messenger->name,
1364
+					$default_message_type_names_for_messenger,
1365
+					'',
1366
+					true
1367
+				);
1368
+			}
1369
+		}
1370
+		return $templates_created;
1371
+	}
1372
+
1373
+
1374
+
1375
+	/**
1376
+	 * This will activate and generate default messengers and default message types for those messengers.
1377
+	 *
1378
+	 * @param EE_message_Resource_Manager $message_resource_manager
1379
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1380
+	 *                     False means that there were no templates generated
1381
+	 *                     (which could simply mean there are no default message types for a messenger).
1382
+	 * @throws EE_Error
1383
+	 */
1384
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1385
+		EE_Message_Resource_Manager $message_resource_manager
1386
+	) {
1387
+		/** @type EE_messenger[] $messengers_to_generate */
1388
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1389
+		$installed_message_types = $message_resource_manager->installed_message_types();
1390
+		$templates_generated = false;
1391
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1392
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1393
+			//verify the default message types match an installed message type.
1394
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1395
+				if (
1396
+					! isset($installed_message_types[$name])
1397
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1398
+						$name,
1399
+						$messenger_to_generate->name
1400
+					)
1401
+				) {
1402
+					unset($default_message_type_names_for_messenger[$key]);
1403
+				}
1404
+			}
1405
+			// in previous iterations, the active_messengers option in the db
1406
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1407
+			// This comment is left here just in case we discover that we _do_ need to update before
1408
+			// passing off to create templates (after the refactor is done).
1409
+			// @todo remove this comment when determined not necessary.
1410
+			$message_resource_manager->activate_messenger(
1411
+				$messenger_to_generate->name,
1412
+				$default_message_type_names_for_messenger,
1413
+				false
1414
+			);
1415
+			//create any templates needing created (or will reactivate templates already generated as necessary).
1416
+			if ( ! empty($default_message_type_names_for_messenger)) {
1417
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1418
+					$messenger_to_generate->name,
1419
+					$default_message_type_names_for_messenger,
1420
+					'',
1421
+					true
1422
+				);
1423
+			}
1424
+		}
1425
+		return $templates_generated;
1426
+	}
1427
+
1428
+
1429
+	/**
1430
+	 * This returns the default messengers to generate templates for on activation of EE.
1431
+	 * It considers:
1432
+	 * - whether a messenger is already active in the db.
1433
+	 * - whether a messenger has been made active at any time in the past.
1434
+	 *
1435
+	 * @static
1436
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1437
+	 * @return EE_messenger[]
1438
+	 */
1439
+	protected static function _get_default_messengers_to_generate_on_activation(
1440
+		EE_Message_Resource_Manager $message_resource_manager
1441
+	) {
1442
+		$active_messengers    = $message_resource_manager->active_messengers();
1443
+		$installed_messengers = $message_resource_manager->installed_messengers();
1444
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1445
+
1446
+		$messengers_to_generate = array();
1447
+		foreach ($installed_messengers as $installed_messenger) {
1448
+			//if installed messenger is a messenger that should be activated on install
1449
+			//and is not already active
1450
+			//and has never been activated
1451
+			if (
1452
+				! $installed_messenger->activate_on_install
1453
+				|| isset($active_messengers[$installed_messenger->name])
1454
+				|| isset($has_activated[$installed_messenger->name])
1455
+			) {
1456
+				continue;
1457
+			}
1458
+			$messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1459
+		}
1460
+		return $messengers_to_generate;
1461
+	}
1462
+
1463
+
1464
+	/**
1465
+	 * This simply validates active message types to ensure they actually match installed
1466
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1467
+	 * rows are set inactive.
1468
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1469
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1470
+	 * are still handled in here.
1471
+	 *
1472
+	 * @since 4.3.1
1473
+	 * @return void
1474
+	 */
1475
+	public static function validate_messages_system()
1476
+	{
1477
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1478
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1479
+		$message_resource_manager->validate_active_message_types_are_installed();
1480
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1481
+	}
1482
+
1483
+
1484
+	/**
1485
+	 * create_no_ticket_prices_array
1486
+	 *
1487
+	 * @access public
1488
+	 * @static
1489
+	 * @return void
1490
+	 */
1491
+	public static function create_no_ticket_prices_array()
1492
+	{
1493
+		// this creates an array for tracking events that have no active ticket prices created
1494
+		// this allows us to warn admins of the situation so that it can be corrected
1495
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1496
+		if (! $espresso_no_ticket_prices) {
1497
+			add_option('ee_no_ticket_prices', array(), '', false);
1498
+		}
1499
+	}
1500
+
1501
+
1502
+	/**
1503
+	 * plugin_deactivation
1504
+	 *
1505
+	 * @access public
1506
+	 * @static
1507
+	 * @return void
1508
+	 */
1509
+	public static function plugin_deactivation()
1510
+	{
1511
+	}
1512
+
1513
+
1514
+	/**
1515
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1516
+	 * (like post meta or term relations)
1517
+	 *
1518
+	 * @global wpdb $wpdb
1519
+	 * @throws \EE_Error
1520
+	 */
1521
+	public static function delete_all_espresso_cpt_data()
1522
+	{
1523
+		global $wpdb;
1524
+		//get all the CPT post_types
1525
+		$ee_post_types = array();
1526
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1527
+			if (method_exists($model_name, 'instance')) {
1528
+				$model_obj = call_user_func(array($model_name, 'instance'));
1529
+				if ($model_obj instanceof EEM_CPT_Base) {
1530
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1531
+				}
1532
+			}
1533
+		}
1534
+		//get all our CPTs
1535
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1536
+		$cpt_ids = $wpdb->get_col($query);
1537
+		//delete each post meta and term relations too
1538
+		foreach ($cpt_ids as $post_id) {
1539
+			wp_delete_post($post_id, true);
1540
+		}
1541
+	}
1542
+
1543
+	/**
1544
+	 * Deletes all EE custom tables
1545
+	 *
1546
+	 * @return array
1547
+	 */
1548
+	public static function drop_espresso_tables()
1549
+	{
1550
+		$tables = array();
1551
+		// load registry
1552
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1553
+			if (method_exists($model_name, 'instance')) {
1554
+				$model_obj = call_user_func(array($model_name, 'instance'));
1555
+				if ($model_obj instanceof EEM_Base) {
1556
+					foreach ($model_obj->get_tables() as $table) {
1557
+						if (strpos($table->get_table_name(), 'esp_')
1558
+							&&
1559
+							(
1560
+								is_main_site()//main site? nuke them all
1561
+								|| ! $table->is_global()//not main site,but not global either. nuke it
1562
+							)
1563
+						) {
1564
+							$tables[] = $table->get_table_name();
1565
+						}
1566
+					}
1567
+				}
1568
+			}
1569
+		}
1570
+
1571
+		//there are some tables whose models were removed.
1572
+		//they should be removed when removing all EE core's data
1573
+		$tables_without_models = array(
1574
+			'esp_promotion',
1575
+			'esp_promotion_applied',
1576
+			'esp_promotion_object',
1577
+			'esp_promotion_rule',
1578
+			'esp_rule',
1579
+		);
1580
+		foreach ($tables_without_models as $table) {
1581
+			$tables[] = $table;
1582
+		}
1583
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1584
+	}
1585
+
1586
+
1587
+
1588
+	/**
1589
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1590
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1591
+	 * Returns the list actually deleted
1592
+	 *
1593
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1594
+	 * @global WPDB $wpdb
1595
+	 * @param array $table_names
1596
+	 * @return array of table names which we deleted
1597
+	 */
1598
+	public static function drop_tables($table_names)
1599
+	{
1600
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1601
+	}
1602
+
1603
+
1604
+
1605
+	/**
1606
+	 * plugin_uninstall
1607
+	 *
1608
+	 * @access public
1609
+	 * @static
1610
+	 * @param bool $remove_all
1611
+	 * @return void
1612
+	 */
1613
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1614
+	{
1615
+		global $wpdb;
1616
+		self::drop_espresso_tables();
1617
+		$wp_options_to_delete = array(
1618
+			'ee_no_ticket_prices'                => true,
1619
+			'ee_active_messengers'               => true,
1620
+			'ee_has_activated_messenger'         => true,
1621
+			'ee_flush_rewrite_rules'             => true,
1622
+			'ee_config'                          => false,
1623
+			'ee_data_migration_current_db_state' => true,
1624
+			'ee_data_migration_mapping_'         => false,
1625
+			'ee_data_migration_script_'          => false,
1626
+			'ee_data_migrations'                 => true,
1627
+			'ee_dms_map'                         => false,
1628
+			'ee_notices'                         => true,
1629
+			'lang_file_check_'                   => false,
1630
+			'ee_maintenance_mode'                => true,
1631
+			'ee_ueip_optin'                      => true,
1632
+			'ee_ueip_has_notified'               => true,
1633
+			'ee_plugin_activation_errors'        => true,
1634
+			'ee_id_mapping_from'                 => false,
1635
+			'espresso_persistent_admin_notices'  => true,
1636
+			'ee_encryption_key'                  => true,
1637
+			'pue_force_upgrade_'                 => false,
1638
+			'pue_json_error_'                    => false,
1639
+			'pue_install_key_'                   => false,
1640
+			'pue_verification_error_'            => false,
1641
+			'pu_dismissed_upgrade_'              => false,
1642
+			'external_updates-'                  => false,
1643
+			'ee_extra_data'                      => true,
1644
+			'ee_ssn_'                            => false,
1645
+			'ee_rss_'                            => false,
1646
+			'ee_rte_n_tx_'                       => false,
1647
+			'ee_pers_admin_notices'              => true,
1648
+			'ee_job_parameters_'                 => false,
1649
+			'ee_upload_directories_incomplete'   => true,
1650
+			'ee_verified_db_collations'          => true,
1651
+		);
1652
+		if (is_main_site()) {
1653
+			$wp_options_to_delete['ee_network_config'] = true;
1654
+		}
1655
+		$undeleted_options = array();
1656
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1657
+			if ($no_wildcard) {
1658
+				if ( ! delete_option($option_name)) {
1659
+					$undeleted_options[] = $option_name;
1660
+				}
1661
+			} else {
1662
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1663
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1664
+					if ( ! delete_option($option_name_from_wildcard)) {
1665
+						$undeleted_options[] = $option_name_from_wildcard;
1666
+					}
1667
+				}
1668
+			}
1669
+		}
1670
+		//also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1671
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1672
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1673
+			$db_update_sans_ee4 = array();
1674
+			foreach ($espresso_db_update as $version => $times_activated) {
1675
+				if ((string)$version[0] === '3') {//if its NON EE4
1676
+					$db_update_sans_ee4[$version] = $times_activated;
1677
+				}
1678
+			}
1679
+			update_option('espresso_db_update', $db_update_sans_ee4);
1680
+		}
1681
+		$errors = '';
1682
+		if ( ! empty($undeleted_options)) {
1683
+			$errors .= sprintf(
1684
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1685
+				'<br/>',
1686
+				implode(',<br/>', $undeleted_options)
1687
+			);
1688
+		}
1689
+		if ( ! empty($errors)) {
1690
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1691
+		}
1692
+	}
1693
+
1694
+	/**
1695
+	 * Gets the mysql error code from the last used query by wpdb
1696
+	 *
1697
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1698
+	 */
1699
+	public static function last_wpdb_error_code()
1700
+	{
1701
+		global $wpdb;
1702
+		if ($wpdb->use_mysqli) {
1703
+			return mysqli_errno($wpdb->dbh);
1704
+		} else {
1705
+			return mysql_errno($wpdb->dbh);
1706
+		}
1707
+	}
1708
+
1709
+	/**
1710
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1711
+	 *
1712
+	 * @global wpdb  $wpdb
1713
+	 * @deprecated instead use TableAnalysis::tableExists()
1714
+	 * @param string $table_name with or without $wpdb->prefix
1715
+	 * @return boolean
1716
+	 */
1717
+	public static function table_exists($table_name)
1718
+	{
1719
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1720
+	}
1721
+
1722
+	/**
1723
+	 * Resets the cache on EEH_Activation
1724
+	 */
1725
+	public static function reset()
1726
+	{
1727
+		self::$_default_creator_id                             = null;
1728
+		self::$_initialized_db_content_already_in_this_request = false;
1729
+	}
1730 1730
 }
1731 1731
 // End of file EEH_Activation.helper.php
1732 1732
 // Location: /helpers/EEH_Activation.core.php
Please login to merge, or discard this patch.
core/EE_System.core.php 2 patches
Indentation   +1435 added lines, -1435 removed lines patch added patch discarded remove patch
@@ -2,7 +2,7 @@  discard block
 block discarded – undo
2 2
 use EventEspresso\core\services\shortcodes\ShortcodesManager;
3 3
 
4 4
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
5
-    exit('No direct script access allowed');
5
+	exit('No direct script access allowed');
6 6
 }
7 7
 
8 8
 
@@ -19,1440 +19,1440 @@  discard block
 block discarded – undo
19 19
 {
20 20
 
21 21
 
22
-    /**
23
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
24
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
25
-     */
26
-    const req_type_normal = 0;
27
-
28
-    /**
29
-     * Indicates this is a brand new installation of EE so we should install
30
-     * tables and default data etc
31
-     */
32
-    const req_type_new_activation = 1;
33
-
34
-    /**
35
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
36
-     * and we just exited maintenance mode). We MUST check the database is setup properly
37
-     * and that default data is setup too
38
-     */
39
-    const req_type_reactivation = 2;
40
-
41
-    /**
42
-     * indicates that EE has been upgraded since its previous request.
43
-     * We may have data migration scripts to call and will want to trigger maintenance mode
44
-     */
45
-    const req_type_upgrade = 3;
46
-
47
-    /**
48
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
49
-     */
50
-    const req_type_downgrade = 4;
51
-
52
-    /**
53
-     * @deprecated since version 4.6.0.dev.006
54
-     * Now whenever a new_activation is detected the request type is still just
55
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
56
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
57
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
58
-     * (Specifically, when the migration manager indicates migrations are finished
59
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
60
-     */
61
-    const req_type_activation_but_not_installed = 5;
62
-
63
-    /**
64
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
65
-     */
66
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
67
-
68
-
69
-    /**
70
-     *    instance of the EE_System object
71
-     *
72
-     * @var    $_instance
73
-     * @access    private
74
-     */
75
-    private static $_instance = null;
76
-
77
-    /**
78
-     * @type  EE_Registry $Registry
79
-     * @access    protected
80
-     */
81
-    protected $registry;
82
-
83
-    /**
84
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
85
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
86
-     *
87
-     * @var int
88
-     */
89
-    private $_req_type;
90
-
91
-    /**
92
-     * Whether or not there was a non-micro version change in EE core version during this request
93
-     *
94
-     * @var boolean
95
-     */
96
-    private $_major_version_change = false;
97
-
98
-
99
-
100
-    /**
101
-     * @singleton method used to instantiate class object
102
-     * @access    public
103
-     * @param  \EE_Registry $Registry
104
-     * @return \EE_System
105
-     */
106
-    public static function instance(EE_Registry $Registry = null)
107
-    {
108
-        // check if class object is instantiated
109
-        if ( ! self::$_instance instanceof EE_System) {
110
-            self::$_instance = new self($Registry);
111
-        }
112
-        return self::$_instance;
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     * resets the instance and returns it
119
-     *
120
-     * @return EE_System
121
-     */
122
-    public static function reset()
123
-    {
124
-        self::$_instance->_req_type = null;
125
-        //make sure none of the old hooks are left hanging around
126
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
127
-        //we need to reset the migration manager in order for it to detect DMSs properly
128
-        EE_Data_Migration_Manager::reset();
129
-        self::instance()->detect_activations_or_upgrades();
130
-        self::instance()->perform_activations_upgrades_and_migrations();
131
-        return self::instance();
132
-    }
133
-
134
-
135
-
136
-    /**
137
-     *    sets hooks for running rest of system
138
-     *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
139
-     *    starting EE Addons from any other point may lead to problems
140
-     *
141
-     * @access private
142
-     * @param  \EE_Registry $Registry
143
-     */
144
-    private function __construct(EE_Registry $Registry)
145
-    {
146
-        $this->registry = $Registry;
147
-        do_action('AHEE__EE_System__construct__begin', $this);
148
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
149
-        add_action('AHEE__EE_Bootstrap__load_espresso_addons', array($this, 'load_espresso_addons'));
150
-        // when an ee addon is activated, we want to call the core hook(s) again
151
-        // because the newly-activated addon didn't get a chance to run at all
152
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
153
-        // detect whether install or upgrade
154
-        add_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades', array($this, 'detect_activations_or_upgrades'),
155
-            3);
156
-        // load EE_Config, EE_Textdomain, etc
157
-        add_action('AHEE__EE_Bootstrap__load_core_configuration', array($this, 'load_core_configuration'), 5);
158
-        // load EE_Config, EE_Textdomain, etc
159
-        add_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
160
-            array($this, 'register_shortcodes_modules_and_widgets'), 7);
161
-        // you wanna get going? I wanna get going... let's get going!
162
-        add_action('AHEE__EE_Bootstrap__brew_espresso', array($this, 'brew_espresso'), 9);
163
-        //other housekeeping
164
-        //exclude EE critical pages from wp_list_pages
165
-        add_filter('wp_list_pages_excludes', array($this, 'remove_pages_from_wp_list_pages'), 10);
166
-        // ALL EE Addons should use the following hook point to attach their initial setup too
167
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
168
-        do_action('AHEE__EE_System__construct__complete', $this);
169
-    }
170
-
171
-
172
-
173
-    /**
174
-     * load_espresso_addons
175
-     * allow addons to load first so that they can set hooks for running DMS's, etc
176
-     * this is hooked into both:
177
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
178
-     *        which runs during the WP 'plugins_loaded' action at priority 5
179
-     *    and the WP 'activate_plugin' hookpoint
180
-     *
181
-     * @access public
182
-     * @return void
183
-     */
184
-    public function load_espresso_addons()
185
-    {
186
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
187
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
188
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
189
-        //load and setup EE_Capabilities
190
-        $this->registry->load_core('Capabilities');
191
-        do_action('AHEE__EE_System__load_espresso_addons');
192
-        //if the WP API basic auth plugin isn't already loaded, load it now.
193
-        //We want it for mobile apps. Just include the entire plugin
194
-        //also, don't load the basic auth when a plugin is getting activated, because
195
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
196
-        //and causes a fatal error
197
-        if ( ! function_exists('json_basic_auth_handler')
198
-             && ! function_exists('json_basic_auth_error')
199
-             && ! (
200
-                isset($_GET['action'])
201
-                && in_array($_GET['action'], array('activate', 'activate-selected'))
202
-            )
203
-             && ! (
204
-                isset($_GET['activate'])
205
-                && $_GET['activate'] === 'true'
206
-            )
207
-        ) {
208
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
209
-        }
210
-        $this->_maybe_brew_regular();
211
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
212
-
213
-        //caps need to be initialized on every request so that capability maps are set.
214
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
215
-        $this->registry->CAP->init_caps();
216
-    }
217
-
218
-
219
-
220
-    /**
221
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
222
-     * that need to be setup before our EE_System launches.
223
-     *
224
-     * @return void
225
-     */
226
-    private function _maybe_brew_regular()
227
-    {
228
-        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
229
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
230
-        }
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * detect_activations_or_upgrades
237
-     * Checks for activation or upgrade of core first;
238
-     * then also checks if any registered addons have been activated or upgraded
239
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
240
-     * which runs during the WP 'plugins_loaded' action at priority 3
241
-     *
242
-     * @access public
243
-     * @return void
244
-     */
245
-    public function detect_activations_or_upgrades()
246
-    {
247
-        //first off: let's make sure to handle core
248
-        $this->detect_if_activation_or_upgrade();
249
-        foreach ($this->registry->addons as $addon) {
250
-            //detect teh request type for that addon
251
-            $addon->detect_activation_or_upgrade();
252
-        }
253
-    }
254
-
255
-
256
-
257
-    /**
258
-     * detect_if_activation_or_upgrade
259
-     * Takes care of detecting whether this is a brand new install or code upgrade,
260
-     * and either setting up the DB or setting up maintenance mode etc.
261
-     *
262
-     * @access public
263
-     * @return void
264
-     */
265
-    public function detect_if_activation_or_upgrade()
266
-    {
267
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
268
-        // load M-Mode class
269
-        $this->registry->load_core('Maintenance_Mode');
270
-        // check if db has been updated, or if its a brand-new installation
271
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
272
-        $request_type = $this->detect_req_type($espresso_db_update);
273
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
274
-        switch ($request_type) {
275
-            case EE_System::req_type_new_activation:
276
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
277
-                $this->_handle_core_version_change($espresso_db_update);
278
-                break;
279
-            case EE_System::req_type_reactivation:
280
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
281
-                $this->_handle_core_version_change($espresso_db_update);
282
-                break;
283
-            case EE_System::req_type_upgrade:
284
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
285
-                //migrations may be required now that we've upgraded
286
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
287
-                $this->_handle_core_version_change($espresso_db_update);
288
-                //				echo "done upgrade";die;
289
-                break;
290
-            case EE_System::req_type_downgrade:
291
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
292
-                //its possible migrations are no longer required
293
-                EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
294
-                $this->_handle_core_version_change($espresso_db_update);
295
-                break;
296
-            case EE_System::req_type_normal:
297
-            default:
298
-                //				$this->_maybe_redirect_to_ee_about();
299
-                break;
300
-        }
301
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
302
-    }
303
-
304
-
305
-
306
-    /**
307
-     * Updates the list of installed versions and sets hooks for
308
-     * initializing the database later during the request
309
-     *
310
-     * @param array $espresso_db_update
311
-     */
312
-    protected function _handle_core_version_change($espresso_db_update)
313
-    {
314
-        $this->update_list_of_installed_versions($espresso_db_update);
315
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
316
-        add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
317
-            array($this, 'initialize_db_if_no_migrations_required'));
318
-    }
319
-
320
-
321
-
322
-    /**
323
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
324
-     * information about what versions of EE have been installed and activated,
325
-     * NOT necessarily the state of the database
326
-     *
327
-     * @param null $espresso_db_update
328
-     * @internal param array $espresso_db_update_value the value of the WordPress option. If not supplied, fetches it
329
-     *           from the options table
330
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
331
-     */
332
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
333
-    {
334
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
335
-        if ( ! $espresso_db_update) {
336
-            $espresso_db_update = get_option('espresso_db_update');
337
-        }
338
-        // check that option is an array
339
-        if ( ! is_array($espresso_db_update)) {
340
-            // if option is FALSE, then it never existed
341
-            if ($espresso_db_update === false) {
342
-                // make $espresso_db_update an array and save option with autoload OFF
343
-                $espresso_db_update = array();
344
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
345
-            } else {
346
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
347
-                $espresso_db_update = array($espresso_db_update => array());
348
-                update_option('espresso_db_update', $espresso_db_update);
349
-            }
350
-        } else {
351
-            $corrected_db_update = array();
352
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
353
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
354
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
355
-                    //the key is an int, and the value IS NOT an array
356
-                    //so it must be numerically-indexed, where values are versions installed...
357
-                    //fix it!
358
-                    $version_string = $should_be_array;
359
-                    $corrected_db_update[$version_string] = array('unknown-date');
360
-                } else {
361
-                    //ok it checks out
362
-                    $corrected_db_update[$should_be_version_string] = $should_be_array;
363
-                }
364
-            }
365
-            $espresso_db_update = $corrected_db_update;
366
-            update_option('espresso_db_update', $espresso_db_update);
367
-        }
368
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
369
-        return $espresso_db_update;
370
-    }
371
-
372
-
373
-
374
-    /**
375
-     * Does the traditional work of setting up the plugin's database and adding default data.
376
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
377
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
378
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
379
-     * so that it will be done when migrations are finished
380
-     *
381
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
382
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
383
-     *                                       This is a resource-intensive job
384
-     *                                       so we prefer to only do it when necessary
385
-     * @return void
386
-     */
387
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
388
-    {
389
-        $request_type = $this->detect_req_type();
390
-        //only initialize system if we're not in maintenance mode.
391
-        if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
392
-            update_option('ee_flush_rewrite_rules', true);
393
-            if ($verify_schema) {
394
-                EEH_Activation::initialize_db_and_folders();
395
-            }
396
-            EEH_Activation::initialize_db_content();
397
-            EEH_Activation::system_initialization();
398
-            if ($initialize_addons_too) {
399
-                $this->initialize_addons();
400
-            }
401
-        } else {
402
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
403
-        }
404
-        if ($request_type === EE_System::req_type_new_activation
405
-            || $request_type === EE_System::req_type_reactivation
406
-            || (
407
-                $request_type === EE_System::req_type_upgrade
408
-                && $this->is_major_version_change()
409
-            )
410
-        ) {
411
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
412
-        }
413
-    }
414
-
415
-
416
-
417
-    /**
418
-     * Initializes the db for all registered addons
419
-     */
420
-    public function initialize_addons()
421
-    {
422
-        //foreach registered addon, make sure its db is up-to-date too
423
-        foreach ($this->registry->addons as $addon) {
424
-            $addon->initialize_db_if_no_migrations_required();
425
-        }
426
-    }
427
-
428
-
429
-
430
-    /**
431
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
432
-     *
433
-     * @param    array  $version_history
434
-     * @param    string $current_version_to_add version to be added to the version history
435
-     * @return    boolean success as to whether or not this option was changed
436
-     */
437
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
438
-    {
439
-        if ( ! $version_history) {
440
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
441
-        }
442
-        if ($current_version_to_add == null) {
443
-            $current_version_to_add = espresso_version();
444
-        }
445
-        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
446
-        // re-save
447
-        return update_option('espresso_db_update', $version_history);
448
-    }
449
-
450
-
451
-
452
-    /**
453
-     * Detects if the current version indicated in the has existed in the list of
454
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
455
-     *
456
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
457
-     *                                  If not supplied, fetches it from the options table.
458
-     *                                  Also, caches its result so later parts of the code can also know whether
459
-     *                                  there's been an update or not. This way we can add the current version to
460
-     *                                  espresso_db_update, but still know if this is a new install or not
461
-     * @return int one of the constants on EE_System::req_type_
462
-     */
463
-    public function detect_req_type($espresso_db_update = null)
464
-    {
465
-        if ($this->_req_type === null) {
466
-            $espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
467
-                : $this->fix_espresso_db_upgrade_option();
468
-            $this->_req_type = $this->detect_req_type_given_activation_history($espresso_db_update,
469
-                'ee_espresso_activation', espresso_version());
470
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
471
-        }
472
-        return $this->_req_type;
473
-    }
474
-
475
-
476
-
477
-    /**
478
-     * Returns whether or not there was a non-micro version change (ie, change in either
479
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
480
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
481
-     *
482
-     * @param $activation_history
483
-     * @return bool
484
-     */
485
-    protected function _detect_major_version_change($activation_history)
486
-    {
487
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
488
-        $previous_version_parts = explode('.', $previous_version);
489
-        $current_version_parts = explode('.', espresso_version());
490
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
491
-               && ($previous_version_parts[0] !== $current_version_parts[0]
492
-                   || $previous_version_parts[1] !== $current_version_parts[1]
493
-               );
494
-    }
495
-
496
-
497
-
498
-    /**
499
-     * Returns true if either the major or minor version of EE changed during this request.
500
-     * 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
501
-     *
502
-     * @return bool
503
-     */
504
-    public function is_major_version_change()
505
-    {
506
-        return $this->_major_version_change;
507
-    }
508
-
509
-
510
-
511
-    /**
512
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
513
-     * histories (for core that' 'espresso_db_update' wp option); the name of the wordpress option which is temporarily
514
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
515
-     * just activated to (for core that will always be espresso_version())
516
-     *
517
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
518
-     *                                                 ee plugin. for core that's 'espresso_db_update'
519
-     * @param string $activation_indicator_option_name the name of the wordpress option that is temporarily set to
520
-     *                                                 indicate that this plugin was just activated
521
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
522
-     *                                                 espresso_version())
523
-     * @return int one of the constants on EE_System::req_type_*
524
-     */
525
-    public static function detect_req_type_given_activation_history(
526
-        $activation_history_for_addon,
527
-        $activation_indicator_option_name,
528
-        $version_to_upgrade_to
529
-    ) {
530
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
531
-        if ($activation_history_for_addon) {
532
-            //it exists, so this isn't a completely new install
533
-            //check if this version already in that list of previously installed versions
534
-            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
535
-                //it a version we haven't seen before
536
-                if ($version_is_higher === 1) {
537
-                    $req_type = EE_System::req_type_upgrade;
538
-                } else {
539
-                    $req_type = EE_System::req_type_downgrade;
540
-                }
541
-                delete_option($activation_indicator_option_name);
542
-            } else {
543
-                // its not an update. maybe a reactivation?
544
-                if (get_option($activation_indicator_option_name, false)) {
545
-                    if ($version_is_higher === -1) {
546
-                        $req_type = EE_System::req_type_downgrade;
547
-                    } elseif ($version_is_higher === 0) {
548
-                        //we've seen this version before, but it's an activation. must be a reactivation
549
-                        $req_type = EE_System::req_type_reactivation;
550
-                    } else {//$version_is_higher === 1
551
-                        $req_type = EE_System::req_type_upgrade;
552
-                    }
553
-                    delete_option($activation_indicator_option_name);
554
-                } else {
555
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
556
-                    if ($version_is_higher === -1) {
557
-                        $req_type = EE_System::req_type_downgrade;
558
-                    } elseif ($version_is_higher === 0) {
559
-                        //we've seen this version before and it's not an activation. its normal request
560
-                        $req_type = EE_System::req_type_normal;
561
-                    } else {//$version_is_higher === 1
562
-                        $req_type = EE_System::req_type_upgrade;
563
-                    }
564
-                }
565
-            }
566
-        } else {
567
-            //brand new install
568
-            $req_type = EE_System::req_type_new_activation;
569
-            delete_option($activation_indicator_option_name);
570
-        }
571
-        return $req_type;
572
-    }
573
-
574
-
575
-
576
-    /**
577
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
578
-     * the $activation_history_for_addon
579
-     *
580
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
581
-     *                                             sometimes containing 'unknown-date'
582
-     * @param string $version_to_upgrade_to        (current version)
583
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
584
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
585
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
586
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
587
-     */
588
-    protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
589
-    {
590
-        //find the most recently-activated version
591
-        $most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
592
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
593
-    }
594
-
595
-
596
-
597
-    /**
598
-     * Gets the most recently active version listed in the activation history,
599
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
600
-     *
601
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
602
-     *                                   sometimes containing 'unknown-date'
603
-     * @return string
604
-     */
605
-    protected static function _get_most_recently_active_version_from_activation_history($activation_history)
606
-    {
607
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
608
-        $most_recently_active_version = '0.0.0.dev.000';
609
-        if (is_array($activation_history)) {
610
-            foreach ($activation_history as $version => $times_activated) {
611
-                //check there is a record of when this version was activated. Otherwise,
612
-                //mark it as unknown
613
-                if ( ! $times_activated) {
614
-                    $times_activated = array('unknown-date');
615
-                }
616
-                if (is_string($times_activated)) {
617
-                    $times_activated = array($times_activated);
618
-                }
619
-                foreach ($times_activated as $an_activation) {
620
-                    if ($an_activation != 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
621
-                        $most_recently_active_version = $version;
622
-                        $most_recently_active_version_activation = $an_activation == 'unknown-date'
623
-                            ? '1970-01-01 00:00:00' : $an_activation;
624
-                    }
625
-                }
626
-            }
627
-        }
628
-        return $most_recently_active_version;
629
-    }
630
-
631
-
632
-
633
-    /**
634
-     * This redirects to the about EE page after activation
635
-     *
636
-     * @return void
637
-     */
638
-    public function redirect_to_about_ee()
639
-    {
640
-        $notices = EE_Error::get_notices(false);
641
-        //if current user is an admin and it's not an ajax or rest request
642
-        if (
643
-            ! (defined('DOING_AJAX') && DOING_AJAX)
644
-            && ! (defined('REST_REQUEST') && REST_REQUEST)
645
-            && ! isset($notices['errors'])
646
-            && apply_filters(
647
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
648
-                $this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
649
-            )
650
-        ) {
651
-            $query_params = array('page' => 'espresso_about');
652
-            if (EE_System::instance()->detect_req_type() == EE_System::req_type_new_activation) {
653
-                $query_params['new_activation'] = true;
654
-            }
655
-            if (EE_System::instance()->detect_req_type() == EE_System::req_type_reactivation) {
656
-                $query_params['reactivation'] = true;
657
-            }
658
-            $url = add_query_arg($query_params, admin_url('admin.php'));
659
-            wp_safe_redirect($url);
660
-            exit();
661
-        }
662
-    }
663
-
664
-
665
-
666
-    /**
667
-     * load_core_configuration
668
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
669
-     * which runs during the WP 'plugins_loaded' action at priority 5
670
-     *
671
-     * @return void
672
-     */
673
-    public function load_core_configuration()
674
-    {
675
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
676
-        $this->registry->load_core('EE_Load_Textdomain');
677
-        //load textdomain
678
-        EE_Load_Textdomain::load_textdomain();
679
-        // load and setup EE_Config and EE_Network_Config
680
-        $this->registry->load_core('Config');
681
-        $this->registry->load_core('Network_Config');
682
-        // setup autoloaders
683
-        // enable logging?
684
-        if ($this->registry->CFG->admin->use_full_logging) {
685
-            $this->registry->load_core('Log');
686
-        }
687
-        // check for activation errors
688
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
689
-        if ($activation_errors) {
690
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
691
-            update_option('ee_plugin_activation_errors', false);
692
-        }
693
-        // get model names
694
-        $this->_parse_model_names();
695
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
702
-     *
703
-     * @return void
704
-     */
705
-    private function _parse_model_names()
706
-    {
707
-        //get all the files in the EE_MODELS folder that end in .model.php
708
-        $models = glob(EE_MODELS . '*.model.php');
709
-        $model_names = array();
710
-        $non_abstract_db_models = array();
711
-        foreach ($models as $model) {
712
-            // get model classname
713
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
714
-            $short_name = str_replace('EEM_', '', $classname);
715
-            $reflectionClass = new ReflectionClass($classname);
716
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
717
-                $non_abstract_db_models[$short_name] = $classname;
718
-            }
719
-            $model_names[$short_name] = $classname;
720
-        }
721
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
722
-        $this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
723
-            $non_abstract_db_models);
724
-    }
725
-
726
-
727
-
728
-    /**
729
-     * register_shortcodes_modules_and_widgets
730
-     * generate lists of shortcodes and modules, then verify paths and classes
731
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
732
-     * which runs during the WP 'plugins_loaded' action at priority 7
733
-     *
734
-     * @access public
735
-     * @return void
736
-     */
737
-    public function register_shortcodes_modules_and_widgets()
738
-    {
739
-        try {
740
-            // load, register, and add shortcodes the new way
741
-            new ShortcodesManager(
742
-            // and the old way, but we'll put it under control of the new system
743
-                EE_Config::getLegacyShortcodesManager()
744
-            );
745
-        } catch (Exception $exception) {
746
-            new ExceptionStackTraceDisplay($exception);
747
-        }
748
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
749
-        // check for addons using old hookpoint
750
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
751
-            $this->_incompatible_addon_error();
752
-        }
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * _incompatible_addon_error
759
-     *
760
-     * @access public
761
-     * @return void
762
-     */
763
-    private function _incompatible_addon_error()
764
-    {
765
-        // get array of classes hooking into here
766
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
767
-        if ( ! empty($class_names)) {
768
-            $msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
769
-                'event_espresso');
770
-            $msg .= '<ul>';
771
-            foreach ($class_names as $class_name) {
772
-                $msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
773
-                        $class_name) . '</b></li>';
774
-            }
775
-            $msg .= '</ul>';
776
-            $msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
777
-                'event_espresso');
778
-            // save list of incompatible addons to wp-options for later use
779
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
780
-            if (is_admin()) {
781
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
782
-            }
783
-        }
784
-    }
785
-
786
-
787
-
788
-    /**
789
-     * brew_espresso
790
-     * begins the process of setting hooks for initializing EE in the correct order
791
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hookpoint
792
-     * which runs during the WP 'plugins_loaded' action at priority 9
793
-     *
794
-     * @return void
795
-     */
796
-    public function brew_espresso()
797
-    {
798
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
799
-        // load some final core systems
800
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
801
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
802
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
803
-        add_action('init', array($this, 'load_controllers'), 7);
804
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
805
-        add_action('init', array($this, 'initialize'), 10);
806
-        add_action('init', array($this, 'initialize_last'), 100);
807
-        add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 100);
808
-        add_action('admin_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 100);
809
-        add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
810
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
811
-            // pew pew pew
812
-            $this->registry->load_core('PUE');
813
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
814
-        }
815
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
816
-    }
817
-
818
-
819
-
820
-    /**
821
-     *    set_hooks_for_core
822
-     *
823
-     * @access public
824
-     * @return    void
825
-     */
826
-    public function set_hooks_for_core()
827
-    {
828
-        $this->_deactivate_incompatible_addons();
829
-        do_action('AHEE__EE_System__set_hooks_for_core');
830
-    }
831
-
832
-
833
-
834
-    /**
835
-     * Using the information gathered in EE_System::_incompatible_addon_error,
836
-     * deactivates any addons considered incompatible with the current version of EE
837
-     */
838
-    private function _deactivate_incompatible_addons()
839
-    {
840
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
841
-        if ( ! empty($incompatible_addons)) {
842
-            $active_plugins = get_option('active_plugins', array());
843
-            foreach ($active_plugins as $active_plugin) {
844
-                foreach ($incompatible_addons as $incompatible_addon) {
845
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
846
-                        unset($_GET['activate']);
847
-                        espresso_deactivate_plugin($active_plugin);
848
-                    }
849
-                }
850
-            }
851
-        }
852
-    }
853
-
854
-
855
-
856
-    /**
857
-     *    perform_activations_upgrades_and_migrations
858
-     *
859
-     * @access public
860
-     * @return    void
861
-     */
862
-    public function perform_activations_upgrades_and_migrations()
863
-    {
864
-        //first check if we had previously attempted to setup EE's directories but failed
865
-        if (EEH_Activation::upload_directories_incomplete()) {
866
-            EEH_Activation::create_upload_directories();
867
-        }
868
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
869
-    }
870
-
871
-
872
-
873
-    /**
874
-     *    load_CPTs_and_session
875
-     *
876
-     * @access public
877
-     * @return    void
878
-     */
879
-    public function load_CPTs_and_session()
880
-    {
881
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
882
-        // register Custom Post Types
883
-        $this->registry->load_core('Register_CPTs');
884
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
885
-    }
886
-
887
-
888
-
889
-    /**
890
-     * load_controllers
891
-     * this is the best place to load any additional controllers that needs access to EE core.
892
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
893
-     * time
894
-     *
895
-     * @access public
896
-     * @return void
897
-     */
898
-    public function load_controllers()
899
-    {
900
-        do_action('AHEE__EE_System__load_controllers__start');
901
-        // let's get it started
902
-        if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
903
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
904
-            $this->registry->load_core('Front_Controller');
905
-        } else if ( ! EE_FRONT_AJAX) {
906
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
907
-            EE_Registry::instance()->load_core('Admin');
908
-        }
909
-        do_action('AHEE__EE_System__load_controllers__complete');
910
-    }
911
-
912
-
913
-
914
-    /**
915
-     * core_loaded_and_ready
916
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
917
-     *
918
-     * @access public
919
-     * @return void
920
-     */
921
-    public function core_loaded_and_ready()
922
-    {
923
-        do_action('AHEE__EE_System__core_loaded_and_ready');
924
-        // load_espresso_template_tags
925
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
926
-            require_once(EE_PUBLIC . 'template_tags.php');
927
-        }
928
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
929
-        $this->registry->load_core('Session');
930
-    }
931
-
932
-
933
-
934
-    /**
935
-     * initialize
936
-     * this is the best place to begin initializing client code
937
-     *
938
-     * @access public
939
-     * @return void
940
-     */
941
-    public function initialize()
942
-    {
943
-        do_action('AHEE__EE_System__initialize');
944
-    }
945
-
946
-
947
-
948
-    /**
949
-     * initialize_last
950
-     * this is run really late during the WP init hookpoint, and ensures that mostly everything else that needs to
951
-     * initialize has done so
952
-     *
953
-     * @access public
954
-     * @return void
955
-     */
956
-    public function initialize_last()
957
-    {
958
-        do_action('AHEE__EE_System__initialize_last');
959
-    }
960
-
961
-
962
-
963
-    /**
964
-     * set_hooks_for_shortcodes_modules_and_addons
965
-     * this is the best place for other systems to set callbacks for hooking into other parts of EE
966
-     * this happens at the very beginning of the wp_loaded hookpoint
967
-     *
968
-     * @access public
969
-     * @return void
970
-     */
971
-    public function set_hooks_for_shortcodes_modules_and_addons()
972
-    {
973
-        //		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
974
-    }
975
-
976
-
977
-
978
-    /**
979
-     * do_not_cache
980
-     * sets no cache headers and defines no cache constants for WP plugins
981
-     *
982
-     * @access public
983
-     * @return void
984
-     */
985
-    public static function do_not_cache()
986
-    {
987
-        // set no cache constants
988
-        if ( ! defined('DONOTCACHEPAGE')) {
989
-            define('DONOTCACHEPAGE', true);
990
-        }
991
-        if ( ! defined('DONOTCACHCEOBJECT')) {
992
-            define('DONOTCACHCEOBJECT', true);
993
-        }
994
-        if ( ! defined('DONOTCACHEDB')) {
995
-            define('DONOTCACHEDB', true);
996
-        }
997
-        // add no cache headers
998
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
999
-        // plus a little extra for nginx and Google Chrome
1000
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1001
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1002
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1003
-    }
1004
-
1005
-
1006
-
1007
-    /**
1008
-     *    extra_nocache_headers
1009
-     *
1010
-     * @access    public
1011
-     * @param $headers
1012
-     * @return    array
1013
-     */
1014
-    public static function extra_nocache_headers($headers)
1015
-    {
1016
-        // for NGINX
1017
-        $headers['X-Accel-Expires'] = 0;
1018
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1019
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1020
-        return $headers;
1021
-    }
1022
-
1023
-
1024
-
1025
-    /**
1026
-     *    nocache_headers
1027
-     *
1028
-     * @access    public
1029
-     * @return    void
1030
-     */
1031
-    public static function nocache_headers()
1032
-    {
1033
-        nocache_headers();
1034
-    }
1035
-
1036
-
1037
-
1038
-    /**
1039
-     *    espresso_toolbar_items
1040
-     *
1041
-     * @access public
1042
-     * @param  WP_Admin_Bar $admin_bar
1043
-     * @return void
1044
-     */
1045
-    public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1046
-    {
1047
-        // if in full M-Mode, or its an AJAX request, or user is NOT an admin
1048
-        if (EE_Maintenance_Mode::instance()->level() == EE_Maintenance_Mode::level_2_complete_maintenance
1049
-            || defined('DOING_AJAX')
1050
-            || ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1051
-        ) {
1052
-            return;
1053
-        }
1054
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1055
-        $menu_class = 'espresso_menu_item_class';
1056
-        //we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1057
-        //because they're only defined in each of their respective constructors
1058
-        //and this might be a frontend request, in which case they aren't available
1059
-        $events_admin_url = admin_url("admin.php?page=espresso_events");
1060
-        $reg_admin_url = admin_url("admin.php?page=espresso_registrations");
1061
-        $extensions_admin_url = admin_url("admin.php?page=espresso_packages");
1062
-        //Top Level
1063
-        $admin_bar->add_menu(array(
1064
-            'id'    => 'espresso-toolbar',
1065
-            'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1066
-                       . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1067
-                       . '</span>',
1068
-            'href'  => $events_admin_url,
1069
-            'meta'  => array(
1070
-                'title' => __('Event Espresso', 'event_espresso'),
1071
-                'class' => $menu_class . 'first',
1072
-            ),
1073
-        ));
1074
-        //Events
1075
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1076
-            $admin_bar->add_menu(array(
1077
-                'id'     => 'espresso-toolbar-events',
1078
-                'parent' => 'espresso-toolbar',
1079
-                'title'  => __('Events', 'event_espresso'),
1080
-                'href'   => $events_admin_url,
1081
-                'meta'   => array(
1082
-                    'title'  => __('Events', 'event_espresso'),
1083
-                    'target' => '',
1084
-                    'class'  => $menu_class,
1085
-                ),
1086
-            ));
1087
-        }
1088
-        if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1089
-            //Events Add New
1090
-            $admin_bar->add_menu(array(
1091
-                'id'     => 'espresso-toolbar-events-new',
1092
-                'parent' => 'espresso-toolbar-events',
1093
-                'title'  => __('Add New', 'event_espresso'),
1094
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1095
-                'meta'   => array(
1096
-                    'title'  => __('Add New', 'event_espresso'),
1097
-                    'target' => '',
1098
-                    'class'  => $menu_class,
1099
-                ),
1100
-            ));
1101
-        }
1102
-        if (is_single() && (get_post_type() == 'espresso_events')) {
1103
-            //Current post
1104
-            global $post;
1105
-            if ($this->registry->CAP->current_user_can('ee_edit_event',
1106
-                'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1107
-            ) {
1108
-                //Events Edit Current Event
1109
-                $admin_bar->add_menu(array(
1110
-                    'id'     => 'espresso-toolbar-events-edit',
1111
-                    'parent' => 'espresso-toolbar-events',
1112
-                    'title'  => __('Edit Event', 'event_espresso'),
1113
-                    'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1114
-                        $events_admin_url),
1115
-                    'meta'   => array(
1116
-                        'title'  => __('Edit Event', 'event_espresso'),
1117
-                        'target' => '',
1118
-                        'class'  => $menu_class,
1119
-                    ),
1120
-                ));
1121
-            }
1122
-        }
1123
-        //Events View
1124
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1125
-            'ee_admin_bar_menu_espresso-toolbar-events-view')
1126
-        ) {
1127
-            $admin_bar->add_menu(array(
1128
-                'id'     => 'espresso-toolbar-events-view',
1129
-                'parent' => 'espresso-toolbar-events',
1130
-                'title'  => __('View', 'event_espresso'),
1131
-                'href'   => $events_admin_url,
1132
-                'meta'   => array(
1133
-                    'title'  => __('View', 'event_espresso'),
1134
-                    'target' => '',
1135
-                    'class'  => $menu_class,
1136
-                ),
1137
-            ));
1138
-        }
1139
-        if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1140
-            //Events View All
1141
-            $admin_bar->add_menu(array(
1142
-                'id'     => 'espresso-toolbar-events-all',
1143
-                'parent' => 'espresso-toolbar-events-view',
1144
-                'title'  => __('All', 'event_espresso'),
1145
-                'href'   => $events_admin_url,
1146
-                'meta'   => array(
1147
-                    'title'  => __('All', 'event_espresso'),
1148
-                    'target' => '',
1149
-                    'class'  => $menu_class,
1150
-                ),
1151
-            ));
1152
-        }
1153
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1154
-            'ee_admin_bar_menu_espresso-toolbar-events-today')
1155
-        ) {
1156
-            //Events View Today
1157
-            $admin_bar->add_menu(array(
1158
-                'id'     => 'espresso-toolbar-events-today',
1159
-                'parent' => 'espresso-toolbar-events-view',
1160
-                'title'  => __('Today', 'event_espresso'),
1161
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1162
-                    $events_admin_url),
1163
-                'meta'   => array(
1164
-                    'title'  => __('Today', 'event_espresso'),
1165
-                    'target' => '',
1166
-                    'class'  => $menu_class,
1167
-                ),
1168
-            ));
1169
-        }
1170
-        if ($this->registry->CAP->current_user_can('ee_read_events',
1171
-            'ee_admin_bar_menu_espresso-toolbar-events-month')
1172
-        ) {
1173
-            //Events View This Month
1174
-            $admin_bar->add_menu(array(
1175
-                'id'     => 'espresso-toolbar-events-month',
1176
-                'parent' => 'espresso-toolbar-events-view',
1177
-                'title'  => __('This Month', 'event_espresso'),
1178
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1179
-                    $events_admin_url),
1180
-                'meta'   => array(
1181
-                    'title'  => __('This Month', 'event_espresso'),
1182
-                    'target' => '',
1183
-                    'class'  => $menu_class,
1184
-                ),
1185
-            ));
1186
-        }
1187
-        //Registration Overview
1188
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1189
-            'ee_admin_bar_menu_espresso-toolbar-registrations')
1190
-        ) {
1191
-            $admin_bar->add_menu(array(
1192
-                'id'     => 'espresso-toolbar-registrations',
1193
-                'parent' => 'espresso-toolbar',
1194
-                'title'  => __('Registrations', 'event_espresso'),
1195
-                'href'   => $reg_admin_url,
1196
-                'meta'   => array(
1197
-                    'title'  => __('Registrations', 'event_espresso'),
1198
-                    'target' => '',
1199
-                    'class'  => $menu_class,
1200
-                ),
1201
-            ));
1202
-        }
1203
-        //Registration Overview Today
1204
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1205
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1206
-        ) {
1207
-            $admin_bar->add_menu(array(
1208
-                'id'     => 'espresso-toolbar-registrations-today',
1209
-                'parent' => 'espresso-toolbar-registrations',
1210
-                'title'  => __('Today', 'event_espresso'),
1211
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1212
-                    $reg_admin_url),
1213
-                'meta'   => array(
1214
-                    'title'  => __('Today', 'event_espresso'),
1215
-                    'target' => '',
1216
-                    'class'  => $menu_class,
1217
-                ),
1218
-            ));
1219
-        }
1220
-        //Registration Overview Today Completed
1221
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1222
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1223
-        ) {
1224
-            $admin_bar->add_menu(array(
1225
-                'id'     => 'espresso-toolbar-registrations-today-approved',
1226
-                'parent' => 'espresso-toolbar-registrations-today',
1227
-                'title'  => __('Approved', 'event_espresso'),
1228
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1229
-                    'action'      => 'default',
1230
-                    'status'      => 'today',
1231
-                    '_reg_status' => EEM_Registration::status_id_approved,
1232
-                ), $reg_admin_url),
1233
-                'meta'   => array(
1234
-                    'title'  => __('Approved', 'event_espresso'),
1235
-                    'target' => '',
1236
-                    'class'  => $menu_class,
1237
-                ),
1238
-            ));
1239
-        }
1240
-        //Registration Overview Today Pending\
1241
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1242
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1243
-        ) {
1244
-            $admin_bar->add_menu(array(
1245
-                'id'     => 'espresso-toolbar-registrations-today-pending',
1246
-                'parent' => 'espresso-toolbar-registrations-today',
1247
-                'title'  => __('Pending', 'event_espresso'),
1248
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1249
-                    'action'     => 'default',
1250
-                    'status'     => 'today',
1251
-                    'reg_status' => EEM_Registration::status_id_pending_payment,
1252
-                ), $reg_admin_url),
1253
-                'meta'   => array(
1254
-                    'title'  => __('Pending Payment', 'event_espresso'),
1255
-                    'target' => '',
1256
-                    'class'  => $menu_class,
1257
-                ),
1258
-            ));
1259
-        }
1260
-        //Registration Overview Today Incomplete
1261
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1262
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1263
-        ) {
1264
-            $admin_bar->add_menu(array(
1265
-                'id'     => 'espresso-toolbar-registrations-today-not-approved',
1266
-                'parent' => 'espresso-toolbar-registrations-today',
1267
-                'title'  => __('Not Approved', 'event_espresso'),
1268
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1269
-                    'action'      => 'default',
1270
-                    'status'      => 'today',
1271
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1272
-                ), $reg_admin_url),
1273
-                'meta'   => array(
1274
-                    'title'  => __('Not Approved', 'event_espresso'),
1275
-                    'target' => '',
1276
-                    'class'  => $menu_class,
1277
-                ),
1278
-            ));
1279
-        }
1280
-        //Registration Overview Today Incomplete
1281
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1282
-            'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1283
-        ) {
1284
-            $admin_bar->add_menu(array(
1285
-                'id'     => 'espresso-toolbar-registrations-today-cancelled',
1286
-                'parent' => 'espresso-toolbar-registrations-today',
1287
-                'title'  => __('Cancelled', 'event_espresso'),
1288
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1289
-                    'action'      => 'default',
1290
-                    'status'      => 'today',
1291
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1292
-                ), $reg_admin_url),
1293
-                'meta'   => array(
1294
-                    'title'  => __('Cancelled', 'event_espresso'),
1295
-                    'target' => '',
1296
-                    'class'  => $menu_class,
1297
-                ),
1298
-            ));
1299
-        }
1300
-        //Registration Overview This Month
1301
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1302
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1303
-        ) {
1304
-            $admin_bar->add_menu(array(
1305
-                'id'     => 'espresso-toolbar-registrations-month',
1306
-                'parent' => 'espresso-toolbar-registrations',
1307
-                'title'  => __('This Month', 'event_espresso'),
1308
-                'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1309
-                    $reg_admin_url),
1310
-                'meta'   => array(
1311
-                    'title'  => __('This Month', 'event_espresso'),
1312
-                    'target' => '',
1313
-                    'class'  => $menu_class,
1314
-                ),
1315
-            ));
1316
-        }
1317
-        //Registration Overview This Month Approved
1318
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1319
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1320
-        ) {
1321
-            $admin_bar->add_menu(array(
1322
-                'id'     => 'espresso-toolbar-registrations-month-approved',
1323
-                'parent' => 'espresso-toolbar-registrations-month',
1324
-                'title'  => __('Approved', 'event_espresso'),
1325
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1326
-                    'action'      => 'default',
1327
-                    'status'      => 'month',
1328
-                    '_reg_status' => EEM_Registration::status_id_approved,
1329
-                ), $reg_admin_url),
1330
-                'meta'   => array(
1331
-                    'title'  => __('Approved', 'event_espresso'),
1332
-                    'target' => '',
1333
-                    'class'  => $menu_class,
1334
-                ),
1335
-            ));
1336
-        }
1337
-        //Registration Overview This Month Pending
1338
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1339
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1340
-        ) {
1341
-            $admin_bar->add_menu(array(
1342
-                'id'     => 'espresso-toolbar-registrations-month-pending',
1343
-                'parent' => 'espresso-toolbar-registrations-month',
1344
-                'title'  => __('Pending', 'event_espresso'),
1345
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1346
-                    'action'      => 'default',
1347
-                    'status'      => 'month',
1348
-                    '_reg_status' => EEM_Registration::status_id_pending_payment,
1349
-                ), $reg_admin_url),
1350
-                'meta'   => array(
1351
-                    'title'  => __('Pending', 'event_espresso'),
1352
-                    'target' => '',
1353
-                    'class'  => $menu_class,
1354
-                ),
1355
-            ));
1356
-        }
1357
-        //Registration Overview This Month Not Approved
1358
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1359
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1360
-        ) {
1361
-            $admin_bar->add_menu(array(
1362
-                'id'     => 'espresso-toolbar-registrations-month-not-approved',
1363
-                'parent' => 'espresso-toolbar-registrations-month',
1364
-                'title'  => __('Not Approved', 'event_espresso'),
1365
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1366
-                    'action'      => 'default',
1367
-                    'status'      => 'month',
1368
-                    '_reg_status' => EEM_Registration::status_id_not_approved,
1369
-                ), $reg_admin_url),
1370
-                'meta'   => array(
1371
-                    'title'  => __('Not Approved', 'event_espresso'),
1372
-                    'target' => '',
1373
-                    'class'  => $menu_class,
1374
-                ),
1375
-            ));
1376
-        }
1377
-        //Registration Overview This Month Cancelled
1378
-        if ($this->registry->CAP->current_user_can('ee_read_registrations',
1379
-            'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1380
-        ) {
1381
-            $admin_bar->add_menu(array(
1382
-                'id'     => 'espresso-toolbar-registrations-month-cancelled',
1383
-                'parent' => 'espresso-toolbar-registrations-month',
1384
-                'title'  => __('Cancelled', 'event_espresso'),
1385
-                'href'   => EEH_URL::add_query_args_and_nonce(array(
1386
-                    'action'      => 'default',
1387
-                    'status'      => 'month',
1388
-                    '_reg_status' => EEM_Registration::status_id_cancelled,
1389
-                ), $reg_admin_url),
1390
-                'meta'   => array(
1391
-                    'title'  => __('Cancelled', 'event_espresso'),
1392
-                    'target' => '',
1393
-                    'class'  => $menu_class,
1394
-                ),
1395
-            ));
1396
-        }
1397
-        //Extensions & Services
1398
-        if ($this->registry->CAP->current_user_can('ee_read_ee',
1399
-            'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1400
-        ) {
1401
-            $admin_bar->add_menu(array(
1402
-                'id'     => 'espresso-toolbar-extensions-and-services',
1403
-                'parent' => 'espresso-toolbar',
1404
-                'title'  => __('Extensions & Services', 'event_espresso'),
1405
-                'href'   => $extensions_admin_url,
1406
-                'meta'   => array(
1407
-                    'title'  => __('Extensions & Services', 'event_espresso'),
1408
-                    'target' => '',
1409
-                    'class'  => $menu_class,
1410
-                ),
1411
-            ));
1412
-        }
1413
-    }
1414
-
1415
-
1416
-
1417
-    /**
1418
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1419
-     * never returned with the function.
1420
-     *
1421
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1422
-     * @return array
1423
-     */
1424
-    public function remove_pages_from_wp_list_pages($exclude_array)
1425
-    {
1426
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1427
-    }
1428
-
1429
-
1430
-
1431
-
1432
-
1433
-
1434
-    /***********************************************        WP_ENQUEUE_SCRIPTS HOOK         ***********************************************/
1435
-    /**
1436
-     *    wp_enqueue_scripts
1437
-     *
1438
-     * @access    public
1439
-     * @return    void
1440
-     */
1441
-    public function wp_enqueue_scripts()
1442
-    {
1443
-        // unlike other systems, EE_System_scripts loading is turned ON by default, but prior to the init hook, can be turned off via: add_filter( 'FHEE_load_EE_System_scripts', '__return_false' );
1444
-        if (apply_filters('FHEE_load_EE_System_scripts', true)) {
1445
-            // jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1446
-            if (apply_filters('FHEE_load_jquery_validate', false)) {
1447
-                // register jQuery Validate and additional methods
1448
-                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1449
-                    array('jquery'), '1.15.0', true);
1450
-                wp_register_script('jquery-validate-extra-methods',
1451
-                    EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1452
-                    array('jquery', 'jquery-validate'), '1.15.0', true);
1453
-            }
1454
-        }
1455
-    }
22
+	/**
23
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
24
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
25
+	 */
26
+	const req_type_normal = 0;
27
+
28
+	/**
29
+	 * Indicates this is a brand new installation of EE so we should install
30
+	 * tables and default data etc
31
+	 */
32
+	const req_type_new_activation = 1;
33
+
34
+	/**
35
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
36
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
37
+	 * and that default data is setup too
38
+	 */
39
+	const req_type_reactivation = 2;
40
+
41
+	/**
42
+	 * indicates that EE has been upgraded since its previous request.
43
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
44
+	 */
45
+	const req_type_upgrade = 3;
46
+
47
+	/**
48
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
49
+	 */
50
+	const req_type_downgrade = 4;
51
+
52
+	/**
53
+	 * @deprecated since version 4.6.0.dev.006
54
+	 * Now whenever a new_activation is detected the request type is still just
55
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
56
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
57
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
58
+	 * (Specifically, when the migration manager indicates migrations are finished
59
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
60
+	 */
61
+	const req_type_activation_but_not_installed = 5;
62
+
63
+	/**
64
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
65
+	 */
66
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
67
+
68
+
69
+	/**
70
+	 *    instance of the EE_System object
71
+	 *
72
+	 * @var    $_instance
73
+	 * @access    private
74
+	 */
75
+	private static $_instance = null;
76
+
77
+	/**
78
+	 * @type  EE_Registry $Registry
79
+	 * @access    protected
80
+	 */
81
+	protected $registry;
82
+
83
+	/**
84
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
85
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
86
+	 *
87
+	 * @var int
88
+	 */
89
+	private $_req_type;
90
+
91
+	/**
92
+	 * Whether or not there was a non-micro version change in EE core version during this request
93
+	 *
94
+	 * @var boolean
95
+	 */
96
+	private $_major_version_change = false;
97
+
98
+
99
+
100
+	/**
101
+	 * @singleton method used to instantiate class object
102
+	 * @access    public
103
+	 * @param  \EE_Registry $Registry
104
+	 * @return \EE_System
105
+	 */
106
+	public static function instance(EE_Registry $Registry = null)
107
+	{
108
+		// check if class object is instantiated
109
+		if ( ! self::$_instance instanceof EE_System) {
110
+			self::$_instance = new self($Registry);
111
+		}
112
+		return self::$_instance;
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 * resets the instance and returns it
119
+	 *
120
+	 * @return EE_System
121
+	 */
122
+	public static function reset()
123
+	{
124
+		self::$_instance->_req_type = null;
125
+		//make sure none of the old hooks are left hanging around
126
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
127
+		//we need to reset the migration manager in order for it to detect DMSs properly
128
+		EE_Data_Migration_Manager::reset();
129
+		self::instance()->detect_activations_or_upgrades();
130
+		self::instance()->perform_activations_upgrades_and_migrations();
131
+		return self::instance();
132
+	}
133
+
134
+
135
+
136
+	/**
137
+	 *    sets hooks for running rest of system
138
+	 *    provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
139
+	 *    starting EE Addons from any other point may lead to problems
140
+	 *
141
+	 * @access private
142
+	 * @param  \EE_Registry $Registry
143
+	 */
144
+	private function __construct(EE_Registry $Registry)
145
+	{
146
+		$this->registry = $Registry;
147
+		do_action('AHEE__EE_System__construct__begin', $this);
148
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
149
+		add_action('AHEE__EE_Bootstrap__load_espresso_addons', array($this, 'load_espresso_addons'));
150
+		// when an ee addon is activated, we want to call the core hook(s) again
151
+		// because the newly-activated addon didn't get a chance to run at all
152
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
153
+		// detect whether install or upgrade
154
+		add_action('AHEE__EE_Bootstrap__detect_activations_or_upgrades', array($this, 'detect_activations_or_upgrades'),
155
+			3);
156
+		// load EE_Config, EE_Textdomain, etc
157
+		add_action('AHEE__EE_Bootstrap__load_core_configuration', array($this, 'load_core_configuration'), 5);
158
+		// load EE_Config, EE_Textdomain, etc
159
+		add_action('AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
160
+			array($this, 'register_shortcodes_modules_and_widgets'), 7);
161
+		// you wanna get going? I wanna get going... let's get going!
162
+		add_action('AHEE__EE_Bootstrap__brew_espresso', array($this, 'brew_espresso'), 9);
163
+		//other housekeeping
164
+		//exclude EE critical pages from wp_list_pages
165
+		add_filter('wp_list_pages_excludes', array($this, 'remove_pages_from_wp_list_pages'), 10);
166
+		// ALL EE Addons should use the following hook point to attach their initial setup too
167
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
168
+		do_action('AHEE__EE_System__construct__complete', $this);
169
+	}
170
+
171
+
172
+
173
+	/**
174
+	 * load_espresso_addons
175
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
176
+	 * this is hooked into both:
177
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
178
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
179
+	 *    and the WP 'activate_plugin' hookpoint
180
+	 *
181
+	 * @access public
182
+	 * @return void
183
+	 */
184
+	public function load_espresso_addons()
185
+	{
186
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
187
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
188
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
189
+		//load and setup EE_Capabilities
190
+		$this->registry->load_core('Capabilities');
191
+		do_action('AHEE__EE_System__load_espresso_addons');
192
+		//if the WP API basic auth plugin isn't already loaded, load it now.
193
+		//We want it for mobile apps. Just include the entire plugin
194
+		//also, don't load the basic auth when a plugin is getting activated, because
195
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
196
+		//and causes a fatal error
197
+		if ( ! function_exists('json_basic_auth_handler')
198
+			 && ! function_exists('json_basic_auth_error')
199
+			 && ! (
200
+				isset($_GET['action'])
201
+				&& in_array($_GET['action'], array('activate', 'activate-selected'))
202
+			)
203
+			 && ! (
204
+				isset($_GET['activate'])
205
+				&& $_GET['activate'] === 'true'
206
+			)
207
+		) {
208
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
209
+		}
210
+		$this->_maybe_brew_regular();
211
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
212
+
213
+		//caps need to be initialized on every request so that capability maps are set.
214
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
215
+		$this->registry->CAP->init_caps();
216
+	}
217
+
218
+
219
+
220
+	/**
221
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
222
+	 * that need to be setup before our EE_System launches.
223
+	 *
224
+	 * @return void
225
+	 */
226
+	private function _maybe_brew_regular()
227
+	{
228
+		if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
229
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
230
+		}
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * detect_activations_or_upgrades
237
+	 * Checks for activation or upgrade of core first;
238
+	 * then also checks if any registered addons have been activated or upgraded
239
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
240
+	 * which runs during the WP 'plugins_loaded' action at priority 3
241
+	 *
242
+	 * @access public
243
+	 * @return void
244
+	 */
245
+	public function detect_activations_or_upgrades()
246
+	{
247
+		//first off: let's make sure to handle core
248
+		$this->detect_if_activation_or_upgrade();
249
+		foreach ($this->registry->addons as $addon) {
250
+			//detect teh request type for that addon
251
+			$addon->detect_activation_or_upgrade();
252
+		}
253
+	}
254
+
255
+
256
+
257
+	/**
258
+	 * detect_if_activation_or_upgrade
259
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
260
+	 * and either setting up the DB or setting up maintenance mode etc.
261
+	 *
262
+	 * @access public
263
+	 * @return void
264
+	 */
265
+	public function detect_if_activation_or_upgrade()
266
+	{
267
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
268
+		// load M-Mode class
269
+		$this->registry->load_core('Maintenance_Mode');
270
+		// check if db has been updated, or if its a brand-new installation
271
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
272
+		$request_type = $this->detect_req_type($espresso_db_update);
273
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
274
+		switch ($request_type) {
275
+			case EE_System::req_type_new_activation:
276
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
277
+				$this->_handle_core_version_change($espresso_db_update);
278
+				break;
279
+			case EE_System::req_type_reactivation:
280
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
281
+				$this->_handle_core_version_change($espresso_db_update);
282
+				break;
283
+			case EE_System::req_type_upgrade:
284
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
285
+				//migrations may be required now that we've upgraded
286
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
287
+				$this->_handle_core_version_change($espresso_db_update);
288
+				//				echo "done upgrade";die;
289
+				break;
290
+			case EE_System::req_type_downgrade:
291
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
292
+				//its possible migrations are no longer required
293
+				EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
294
+				$this->_handle_core_version_change($espresso_db_update);
295
+				break;
296
+			case EE_System::req_type_normal:
297
+			default:
298
+				//				$this->_maybe_redirect_to_ee_about();
299
+				break;
300
+		}
301
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
302
+	}
303
+
304
+
305
+
306
+	/**
307
+	 * Updates the list of installed versions and sets hooks for
308
+	 * initializing the database later during the request
309
+	 *
310
+	 * @param array $espresso_db_update
311
+	 */
312
+	protected function _handle_core_version_change($espresso_db_update)
313
+	{
314
+		$this->update_list_of_installed_versions($espresso_db_update);
315
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
316
+		add_action('AHEE__EE_System__perform_activations_upgrades_and_migrations',
317
+			array($this, 'initialize_db_if_no_migrations_required'));
318
+	}
319
+
320
+
321
+
322
+	/**
323
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
324
+	 * information about what versions of EE have been installed and activated,
325
+	 * NOT necessarily the state of the database
326
+	 *
327
+	 * @param null $espresso_db_update
328
+	 * @internal param array $espresso_db_update_value the value of the WordPress option. If not supplied, fetches it
329
+	 *           from the options table
330
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
331
+	 */
332
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
333
+	{
334
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
335
+		if ( ! $espresso_db_update) {
336
+			$espresso_db_update = get_option('espresso_db_update');
337
+		}
338
+		// check that option is an array
339
+		if ( ! is_array($espresso_db_update)) {
340
+			// if option is FALSE, then it never existed
341
+			if ($espresso_db_update === false) {
342
+				// make $espresso_db_update an array and save option with autoload OFF
343
+				$espresso_db_update = array();
344
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
345
+			} else {
346
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
347
+				$espresso_db_update = array($espresso_db_update => array());
348
+				update_option('espresso_db_update', $espresso_db_update);
349
+			}
350
+		} else {
351
+			$corrected_db_update = array();
352
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
353
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
354
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
355
+					//the key is an int, and the value IS NOT an array
356
+					//so it must be numerically-indexed, where values are versions installed...
357
+					//fix it!
358
+					$version_string = $should_be_array;
359
+					$corrected_db_update[$version_string] = array('unknown-date');
360
+				} else {
361
+					//ok it checks out
362
+					$corrected_db_update[$should_be_version_string] = $should_be_array;
363
+				}
364
+			}
365
+			$espresso_db_update = $corrected_db_update;
366
+			update_option('espresso_db_update', $espresso_db_update);
367
+		}
368
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
369
+		return $espresso_db_update;
370
+	}
371
+
372
+
373
+
374
+	/**
375
+	 * Does the traditional work of setting up the plugin's database and adding default data.
376
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
377
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
378
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
379
+	 * so that it will be done when migrations are finished
380
+	 *
381
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
382
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
383
+	 *                                       This is a resource-intensive job
384
+	 *                                       so we prefer to only do it when necessary
385
+	 * @return void
386
+	 */
387
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
388
+	{
389
+		$request_type = $this->detect_req_type();
390
+		//only initialize system if we're not in maintenance mode.
391
+		if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
392
+			update_option('ee_flush_rewrite_rules', true);
393
+			if ($verify_schema) {
394
+				EEH_Activation::initialize_db_and_folders();
395
+			}
396
+			EEH_Activation::initialize_db_content();
397
+			EEH_Activation::system_initialization();
398
+			if ($initialize_addons_too) {
399
+				$this->initialize_addons();
400
+			}
401
+		} else {
402
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
403
+		}
404
+		if ($request_type === EE_System::req_type_new_activation
405
+			|| $request_type === EE_System::req_type_reactivation
406
+			|| (
407
+				$request_type === EE_System::req_type_upgrade
408
+				&& $this->is_major_version_change()
409
+			)
410
+		) {
411
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
412
+		}
413
+	}
414
+
415
+
416
+
417
+	/**
418
+	 * Initializes the db for all registered addons
419
+	 */
420
+	public function initialize_addons()
421
+	{
422
+		//foreach registered addon, make sure its db is up-to-date too
423
+		foreach ($this->registry->addons as $addon) {
424
+			$addon->initialize_db_if_no_migrations_required();
425
+		}
426
+	}
427
+
428
+
429
+
430
+	/**
431
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
432
+	 *
433
+	 * @param    array  $version_history
434
+	 * @param    string $current_version_to_add version to be added to the version history
435
+	 * @return    boolean success as to whether or not this option was changed
436
+	 */
437
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
438
+	{
439
+		if ( ! $version_history) {
440
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
441
+		}
442
+		if ($current_version_to_add == null) {
443
+			$current_version_to_add = espresso_version();
444
+		}
445
+		$version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
446
+		// re-save
447
+		return update_option('espresso_db_update', $version_history);
448
+	}
449
+
450
+
451
+
452
+	/**
453
+	 * Detects if the current version indicated in the has existed in the list of
454
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
455
+	 *
456
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
457
+	 *                                  If not supplied, fetches it from the options table.
458
+	 *                                  Also, caches its result so later parts of the code can also know whether
459
+	 *                                  there's been an update or not. This way we can add the current version to
460
+	 *                                  espresso_db_update, but still know if this is a new install or not
461
+	 * @return int one of the constants on EE_System::req_type_
462
+	 */
463
+	public function detect_req_type($espresso_db_update = null)
464
+	{
465
+		if ($this->_req_type === null) {
466
+			$espresso_db_update = ! empty($espresso_db_update) ? $espresso_db_update
467
+				: $this->fix_espresso_db_upgrade_option();
468
+			$this->_req_type = $this->detect_req_type_given_activation_history($espresso_db_update,
469
+				'ee_espresso_activation', espresso_version());
470
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
471
+		}
472
+		return $this->_req_type;
473
+	}
474
+
475
+
476
+
477
+	/**
478
+	 * Returns whether or not there was a non-micro version change (ie, change in either
479
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
480
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
481
+	 *
482
+	 * @param $activation_history
483
+	 * @return bool
484
+	 */
485
+	protected function _detect_major_version_change($activation_history)
486
+	{
487
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
488
+		$previous_version_parts = explode('.', $previous_version);
489
+		$current_version_parts = explode('.', espresso_version());
490
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
491
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
492
+				   || $previous_version_parts[1] !== $current_version_parts[1]
493
+			   );
494
+	}
495
+
496
+
497
+
498
+	/**
499
+	 * Returns true if either the major or minor version of EE changed during this request.
500
+	 * 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
501
+	 *
502
+	 * @return bool
503
+	 */
504
+	public function is_major_version_change()
505
+	{
506
+		return $this->_major_version_change;
507
+	}
508
+
509
+
510
+
511
+	/**
512
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
513
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the wordpress option which is temporarily
514
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
515
+	 * just activated to (for core that will always be espresso_version())
516
+	 *
517
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
518
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
519
+	 * @param string $activation_indicator_option_name the name of the wordpress option that is temporarily set to
520
+	 *                                                 indicate that this plugin was just activated
521
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
522
+	 *                                                 espresso_version())
523
+	 * @return int one of the constants on EE_System::req_type_*
524
+	 */
525
+	public static function detect_req_type_given_activation_history(
526
+		$activation_history_for_addon,
527
+		$activation_indicator_option_name,
528
+		$version_to_upgrade_to
529
+	) {
530
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
531
+		if ($activation_history_for_addon) {
532
+			//it exists, so this isn't a completely new install
533
+			//check if this version already in that list of previously installed versions
534
+			if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
535
+				//it a version we haven't seen before
536
+				if ($version_is_higher === 1) {
537
+					$req_type = EE_System::req_type_upgrade;
538
+				} else {
539
+					$req_type = EE_System::req_type_downgrade;
540
+				}
541
+				delete_option($activation_indicator_option_name);
542
+			} else {
543
+				// its not an update. maybe a reactivation?
544
+				if (get_option($activation_indicator_option_name, false)) {
545
+					if ($version_is_higher === -1) {
546
+						$req_type = EE_System::req_type_downgrade;
547
+					} elseif ($version_is_higher === 0) {
548
+						//we've seen this version before, but it's an activation. must be a reactivation
549
+						$req_type = EE_System::req_type_reactivation;
550
+					} else {//$version_is_higher === 1
551
+						$req_type = EE_System::req_type_upgrade;
552
+					}
553
+					delete_option($activation_indicator_option_name);
554
+				} else {
555
+					//we've seen this version before and the activation indicate doesn't show it was just activated
556
+					if ($version_is_higher === -1) {
557
+						$req_type = EE_System::req_type_downgrade;
558
+					} elseif ($version_is_higher === 0) {
559
+						//we've seen this version before and it's not an activation. its normal request
560
+						$req_type = EE_System::req_type_normal;
561
+					} else {//$version_is_higher === 1
562
+						$req_type = EE_System::req_type_upgrade;
563
+					}
564
+				}
565
+			}
566
+		} else {
567
+			//brand new install
568
+			$req_type = EE_System::req_type_new_activation;
569
+			delete_option($activation_indicator_option_name);
570
+		}
571
+		return $req_type;
572
+	}
573
+
574
+
575
+
576
+	/**
577
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
578
+	 * the $activation_history_for_addon
579
+	 *
580
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
581
+	 *                                             sometimes containing 'unknown-date'
582
+	 * @param string $version_to_upgrade_to        (current version)
583
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
584
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
585
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
586
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
587
+	 */
588
+	protected static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
589
+	{
590
+		//find the most recently-activated version
591
+		$most_recently_active_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
592
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
593
+	}
594
+
595
+
596
+
597
+	/**
598
+	 * Gets the most recently active version listed in the activation history,
599
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
600
+	 *
601
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
602
+	 *                                   sometimes containing 'unknown-date'
603
+	 * @return string
604
+	 */
605
+	protected static function _get_most_recently_active_version_from_activation_history($activation_history)
606
+	{
607
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
608
+		$most_recently_active_version = '0.0.0.dev.000';
609
+		if (is_array($activation_history)) {
610
+			foreach ($activation_history as $version => $times_activated) {
611
+				//check there is a record of when this version was activated. Otherwise,
612
+				//mark it as unknown
613
+				if ( ! $times_activated) {
614
+					$times_activated = array('unknown-date');
615
+				}
616
+				if (is_string($times_activated)) {
617
+					$times_activated = array($times_activated);
618
+				}
619
+				foreach ($times_activated as $an_activation) {
620
+					if ($an_activation != 'unknown-date' && $an_activation > $most_recently_active_version_activation) {
621
+						$most_recently_active_version = $version;
622
+						$most_recently_active_version_activation = $an_activation == 'unknown-date'
623
+							? '1970-01-01 00:00:00' : $an_activation;
624
+					}
625
+				}
626
+			}
627
+		}
628
+		return $most_recently_active_version;
629
+	}
630
+
631
+
632
+
633
+	/**
634
+	 * This redirects to the about EE page after activation
635
+	 *
636
+	 * @return void
637
+	 */
638
+	public function redirect_to_about_ee()
639
+	{
640
+		$notices = EE_Error::get_notices(false);
641
+		//if current user is an admin and it's not an ajax or rest request
642
+		if (
643
+			! (defined('DOING_AJAX') && DOING_AJAX)
644
+			&& ! (defined('REST_REQUEST') && REST_REQUEST)
645
+			&& ! isset($notices['errors'])
646
+			&& apply_filters(
647
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
648
+				$this->registry->CAP->current_user_can('manage_options', 'espresso_about_default')
649
+			)
650
+		) {
651
+			$query_params = array('page' => 'espresso_about');
652
+			if (EE_System::instance()->detect_req_type() == EE_System::req_type_new_activation) {
653
+				$query_params['new_activation'] = true;
654
+			}
655
+			if (EE_System::instance()->detect_req_type() == EE_System::req_type_reactivation) {
656
+				$query_params['reactivation'] = true;
657
+			}
658
+			$url = add_query_arg($query_params, admin_url('admin.php'));
659
+			wp_safe_redirect($url);
660
+			exit();
661
+		}
662
+	}
663
+
664
+
665
+
666
+	/**
667
+	 * load_core_configuration
668
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
669
+	 * which runs during the WP 'plugins_loaded' action at priority 5
670
+	 *
671
+	 * @return void
672
+	 */
673
+	public function load_core_configuration()
674
+	{
675
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
676
+		$this->registry->load_core('EE_Load_Textdomain');
677
+		//load textdomain
678
+		EE_Load_Textdomain::load_textdomain();
679
+		// load and setup EE_Config and EE_Network_Config
680
+		$this->registry->load_core('Config');
681
+		$this->registry->load_core('Network_Config');
682
+		// setup autoloaders
683
+		// enable logging?
684
+		if ($this->registry->CFG->admin->use_full_logging) {
685
+			$this->registry->load_core('Log');
686
+		}
687
+		// check for activation errors
688
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
689
+		if ($activation_errors) {
690
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
691
+			update_option('ee_plugin_activation_errors', false);
692
+		}
693
+		// get model names
694
+		$this->_parse_model_names();
695
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
702
+	 *
703
+	 * @return void
704
+	 */
705
+	private function _parse_model_names()
706
+	{
707
+		//get all the files in the EE_MODELS folder that end in .model.php
708
+		$models = glob(EE_MODELS . '*.model.php');
709
+		$model_names = array();
710
+		$non_abstract_db_models = array();
711
+		foreach ($models as $model) {
712
+			// get model classname
713
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
714
+			$short_name = str_replace('EEM_', '', $classname);
715
+			$reflectionClass = new ReflectionClass($classname);
716
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
717
+				$non_abstract_db_models[$short_name] = $classname;
718
+			}
719
+			$model_names[$short_name] = $classname;
720
+		}
721
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
722
+		$this->registry->non_abstract_db_models = apply_filters('FHEE__EE_System__parse_implemented_model_names',
723
+			$non_abstract_db_models);
724
+	}
725
+
726
+
727
+
728
+	/**
729
+	 * register_shortcodes_modules_and_widgets
730
+	 * generate lists of shortcodes and modules, then verify paths and classes
731
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
732
+	 * which runs during the WP 'plugins_loaded' action at priority 7
733
+	 *
734
+	 * @access public
735
+	 * @return void
736
+	 */
737
+	public function register_shortcodes_modules_and_widgets()
738
+	{
739
+		try {
740
+			// load, register, and add shortcodes the new way
741
+			new ShortcodesManager(
742
+			// and the old way, but we'll put it under control of the new system
743
+				EE_Config::getLegacyShortcodesManager()
744
+			);
745
+		} catch (Exception $exception) {
746
+			new ExceptionStackTraceDisplay($exception);
747
+		}
748
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
749
+		// check for addons using old hookpoint
750
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
751
+			$this->_incompatible_addon_error();
752
+		}
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * _incompatible_addon_error
759
+	 *
760
+	 * @access public
761
+	 * @return void
762
+	 */
763
+	private function _incompatible_addon_error()
764
+	{
765
+		// get array of classes hooking into here
766
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook('AHEE__EE_System__register_shortcodes_modules_and_addons');
767
+		if ( ! empty($class_names)) {
768
+			$msg = __('The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
769
+				'event_espresso');
770
+			$msg .= '<ul>';
771
+			foreach ($class_names as $class_name) {
772
+				$msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
773
+						$class_name) . '</b></li>';
774
+			}
775
+			$msg .= '</ul>';
776
+			$msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
777
+				'event_espresso');
778
+			// save list of incompatible addons to wp-options for later use
779
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
780
+			if (is_admin()) {
781
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
782
+			}
783
+		}
784
+	}
785
+
786
+
787
+
788
+	/**
789
+	 * brew_espresso
790
+	 * begins the process of setting hooks for initializing EE in the correct order
791
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hookpoint
792
+	 * which runs during the WP 'plugins_loaded' action at priority 9
793
+	 *
794
+	 * @return void
795
+	 */
796
+	public function brew_espresso()
797
+	{
798
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
799
+		// load some final core systems
800
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
801
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
802
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
803
+		add_action('init', array($this, 'load_controllers'), 7);
804
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
805
+		add_action('init', array($this, 'initialize'), 10);
806
+		add_action('init', array($this, 'initialize_last'), 100);
807
+		add_action('wp_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 100);
808
+		add_action('admin_enqueue_scripts', array($this, 'wp_enqueue_scripts'), 100);
809
+		add_action('admin_bar_menu', array($this, 'espresso_toolbar_items'), 100);
810
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
811
+			// pew pew pew
812
+			$this->registry->load_core('PUE');
813
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
814
+		}
815
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
816
+	}
817
+
818
+
819
+
820
+	/**
821
+	 *    set_hooks_for_core
822
+	 *
823
+	 * @access public
824
+	 * @return    void
825
+	 */
826
+	public function set_hooks_for_core()
827
+	{
828
+		$this->_deactivate_incompatible_addons();
829
+		do_action('AHEE__EE_System__set_hooks_for_core');
830
+	}
831
+
832
+
833
+
834
+	/**
835
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
836
+	 * deactivates any addons considered incompatible with the current version of EE
837
+	 */
838
+	private function _deactivate_incompatible_addons()
839
+	{
840
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
841
+		if ( ! empty($incompatible_addons)) {
842
+			$active_plugins = get_option('active_plugins', array());
843
+			foreach ($active_plugins as $active_plugin) {
844
+				foreach ($incompatible_addons as $incompatible_addon) {
845
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
846
+						unset($_GET['activate']);
847
+						espresso_deactivate_plugin($active_plugin);
848
+					}
849
+				}
850
+			}
851
+		}
852
+	}
853
+
854
+
855
+
856
+	/**
857
+	 *    perform_activations_upgrades_and_migrations
858
+	 *
859
+	 * @access public
860
+	 * @return    void
861
+	 */
862
+	public function perform_activations_upgrades_and_migrations()
863
+	{
864
+		//first check if we had previously attempted to setup EE's directories but failed
865
+		if (EEH_Activation::upload_directories_incomplete()) {
866
+			EEH_Activation::create_upload_directories();
867
+		}
868
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
869
+	}
870
+
871
+
872
+
873
+	/**
874
+	 *    load_CPTs_and_session
875
+	 *
876
+	 * @access public
877
+	 * @return    void
878
+	 */
879
+	public function load_CPTs_and_session()
880
+	{
881
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
882
+		// register Custom Post Types
883
+		$this->registry->load_core('Register_CPTs');
884
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
885
+	}
886
+
887
+
888
+
889
+	/**
890
+	 * load_controllers
891
+	 * this is the best place to load any additional controllers that needs access to EE core.
892
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
893
+	 * time
894
+	 *
895
+	 * @access public
896
+	 * @return void
897
+	 */
898
+	public function load_controllers()
899
+	{
900
+		do_action('AHEE__EE_System__load_controllers__start');
901
+		// let's get it started
902
+		if ( ! is_admin() && ! EE_Maintenance_Mode::instance()->level()) {
903
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
904
+			$this->registry->load_core('Front_Controller');
905
+		} else if ( ! EE_FRONT_AJAX) {
906
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
907
+			EE_Registry::instance()->load_core('Admin');
908
+		}
909
+		do_action('AHEE__EE_System__load_controllers__complete');
910
+	}
911
+
912
+
913
+
914
+	/**
915
+	 * core_loaded_and_ready
916
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
917
+	 *
918
+	 * @access public
919
+	 * @return void
920
+	 */
921
+	public function core_loaded_and_ready()
922
+	{
923
+		do_action('AHEE__EE_System__core_loaded_and_ready');
924
+		// load_espresso_template_tags
925
+		if (is_readable(EE_PUBLIC . 'template_tags.php')) {
926
+			require_once(EE_PUBLIC . 'template_tags.php');
927
+		}
928
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
929
+		$this->registry->load_core('Session');
930
+	}
931
+
932
+
933
+
934
+	/**
935
+	 * initialize
936
+	 * this is the best place to begin initializing client code
937
+	 *
938
+	 * @access public
939
+	 * @return void
940
+	 */
941
+	public function initialize()
942
+	{
943
+		do_action('AHEE__EE_System__initialize');
944
+	}
945
+
946
+
947
+
948
+	/**
949
+	 * initialize_last
950
+	 * this is run really late during the WP init hookpoint, and ensures that mostly everything else that needs to
951
+	 * initialize has done so
952
+	 *
953
+	 * @access public
954
+	 * @return void
955
+	 */
956
+	public function initialize_last()
957
+	{
958
+		do_action('AHEE__EE_System__initialize_last');
959
+	}
960
+
961
+
962
+
963
+	/**
964
+	 * set_hooks_for_shortcodes_modules_and_addons
965
+	 * this is the best place for other systems to set callbacks for hooking into other parts of EE
966
+	 * this happens at the very beginning of the wp_loaded hookpoint
967
+	 *
968
+	 * @access public
969
+	 * @return void
970
+	 */
971
+	public function set_hooks_for_shortcodes_modules_and_addons()
972
+	{
973
+		//		do_action( 'AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons' );
974
+	}
975
+
976
+
977
+
978
+	/**
979
+	 * do_not_cache
980
+	 * sets no cache headers and defines no cache constants for WP plugins
981
+	 *
982
+	 * @access public
983
+	 * @return void
984
+	 */
985
+	public static function do_not_cache()
986
+	{
987
+		// set no cache constants
988
+		if ( ! defined('DONOTCACHEPAGE')) {
989
+			define('DONOTCACHEPAGE', true);
990
+		}
991
+		if ( ! defined('DONOTCACHCEOBJECT')) {
992
+			define('DONOTCACHCEOBJECT', true);
993
+		}
994
+		if ( ! defined('DONOTCACHEDB')) {
995
+			define('DONOTCACHEDB', true);
996
+		}
997
+		// add no cache headers
998
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
999
+		// plus a little extra for nginx and Google Chrome
1000
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1001
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1002
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1003
+	}
1004
+
1005
+
1006
+
1007
+	/**
1008
+	 *    extra_nocache_headers
1009
+	 *
1010
+	 * @access    public
1011
+	 * @param $headers
1012
+	 * @return    array
1013
+	 */
1014
+	public static function extra_nocache_headers($headers)
1015
+	{
1016
+		// for NGINX
1017
+		$headers['X-Accel-Expires'] = 0;
1018
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1019
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1020
+		return $headers;
1021
+	}
1022
+
1023
+
1024
+
1025
+	/**
1026
+	 *    nocache_headers
1027
+	 *
1028
+	 * @access    public
1029
+	 * @return    void
1030
+	 */
1031
+	public static function nocache_headers()
1032
+	{
1033
+		nocache_headers();
1034
+	}
1035
+
1036
+
1037
+
1038
+	/**
1039
+	 *    espresso_toolbar_items
1040
+	 *
1041
+	 * @access public
1042
+	 * @param  WP_Admin_Bar $admin_bar
1043
+	 * @return void
1044
+	 */
1045
+	public function espresso_toolbar_items(WP_Admin_Bar $admin_bar)
1046
+	{
1047
+		// if in full M-Mode, or its an AJAX request, or user is NOT an admin
1048
+		if (EE_Maintenance_Mode::instance()->level() == EE_Maintenance_Mode::level_2_complete_maintenance
1049
+			|| defined('DOING_AJAX')
1050
+			|| ! $this->registry->CAP->current_user_can('ee_read_ee', 'ee_admin_bar_menu_top_level')
1051
+		) {
1052
+			return;
1053
+		}
1054
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1055
+		$menu_class = 'espresso_menu_item_class';
1056
+		//we don't use the constants EVENTS_ADMIN_URL or REG_ADMIN_URL
1057
+		//because they're only defined in each of their respective constructors
1058
+		//and this might be a frontend request, in which case they aren't available
1059
+		$events_admin_url = admin_url("admin.php?page=espresso_events");
1060
+		$reg_admin_url = admin_url("admin.php?page=espresso_registrations");
1061
+		$extensions_admin_url = admin_url("admin.php?page=espresso_packages");
1062
+		//Top Level
1063
+		$admin_bar->add_menu(array(
1064
+			'id'    => 'espresso-toolbar',
1065
+			'title' => '<span class="ee-icon ee-icon-ee-cup-thick ee-icon-size-20"></span><span class="ab-label">'
1066
+					   . _x('Event Espresso', 'admin bar menu group label', 'event_espresso')
1067
+					   . '</span>',
1068
+			'href'  => $events_admin_url,
1069
+			'meta'  => array(
1070
+				'title' => __('Event Espresso', 'event_espresso'),
1071
+				'class' => $menu_class . 'first',
1072
+			),
1073
+		));
1074
+		//Events
1075
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events')) {
1076
+			$admin_bar->add_menu(array(
1077
+				'id'     => 'espresso-toolbar-events',
1078
+				'parent' => 'espresso-toolbar',
1079
+				'title'  => __('Events', 'event_espresso'),
1080
+				'href'   => $events_admin_url,
1081
+				'meta'   => array(
1082
+					'title'  => __('Events', 'event_espresso'),
1083
+					'target' => '',
1084
+					'class'  => $menu_class,
1085
+				),
1086
+			));
1087
+		}
1088
+		if ($this->registry->CAP->current_user_can('ee_edit_events', 'ee_admin_bar_menu_espresso-toolbar-events-new')) {
1089
+			//Events Add New
1090
+			$admin_bar->add_menu(array(
1091
+				'id'     => 'espresso-toolbar-events-new',
1092
+				'parent' => 'espresso-toolbar-events',
1093
+				'title'  => __('Add New', 'event_espresso'),
1094
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'create_new'), $events_admin_url),
1095
+				'meta'   => array(
1096
+					'title'  => __('Add New', 'event_espresso'),
1097
+					'target' => '',
1098
+					'class'  => $menu_class,
1099
+				),
1100
+			));
1101
+		}
1102
+		if (is_single() && (get_post_type() == 'espresso_events')) {
1103
+			//Current post
1104
+			global $post;
1105
+			if ($this->registry->CAP->current_user_can('ee_edit_event',
1106
+				'ee_admin_bar_menu_espresso-toolbar-events-edit', $post->ID)
1107
+			) {
1108
+				//Events Edit Current Event
1109
+				$admin_bar->add_menu(array(
1110
+					'id'     => 'espresso-toolbar-events-edit',
1111
+					'parent' => 'espresso-toolbar-events',
1112
+					'title'  => __('Edit Event', 'event_espresso'),
1113
+					'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'edit', 'post' => $post->ID),
1114
+						$events_admin_url),
1115
+					'meta'   => array(
1116
+						'title'  => __('Edit Event', 'event_espresso'),
1117
+						'target' => '',
1118
+						'class'  => $menu_class,
1119
+					),
1120
+				));
1121
+			}
1122
+		}
1123
+		//Events View
1124
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1125
+			'ee_admin_bar_menu_espresso-toolbar-events-view')
1126
+		) {
1127
+			$admin_bar->add_menu(array(
1128
+				'id'     => 'espresso-toolbar-events-view',
1129
+				'parent' => 'espresso-toolbar-events',
1130
+				'title'  => __('View', 'event_espresso'),
1131
+				'href'   => $events_admin_url,
1132
+				'meta'   => array(
1133
+					'title'  => __('View', 'event_espresso'),
1134
+					'target' => '',
1135
+					'class'  => $menu_class,
1136
+				),
1137
+			));
1138
+		}
1139
+		if ($this->registry->CAP->current_user_can('ee_read_events', 'ee_admin_bar_menu_espresso-toolbar-events-all')) {
1140
+			//Events View All
1141
+			$admin_bar->add_menu(array(
1142
+				'id'     => 'espresso-toolbar-events-all',
1143
+				'parent' => 'espresso-toolbar-events-view',
1144
+				'title'  => __('All', 'event_espresso'),
1145
+				'href'   => $events_admin_url,
1146
+				'meta'   => array(
1147
+					'title'  => __('All', 'event_espresso'),
1148
+					'target' => '',
1149
+					'class'  => $menu_class,
1150
+				),
1151
+			));
1152
+		}
1153
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1154
+			'ee_admin_bar_menu_espresso-toolbar-events-today')
1155
+		) {
1156
+			//Events View Today
1157
+			$admin_bar->add_menu(array(
1158
+				'id'     => 'espresso-toolbar-events-today',
1159
+				'parent' => 'espresso-toolbar-events-view',
1160
+				'title'  => __('Today', 'event_espresso'),
1161
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1162
+					$events_admin_url),
1163
+				'meta'   => array(
1164
+					'title'  => __('Today', 'event_espresso'),
1165
+					'target' => '',
1166
+					'class'  => $menu_class,
1167
+				),
1168
+			));
1169
+		}
1170
+		if ($this->registry->CAP->current_user_can('ee_read_events',
1171
+			'ee_admin_bar_menu_espresso-toolbar-events-month')
1172
+		) {
1173
+			//Events View This Month
1174
+			$admin_bar->add_menu(array(
1175
+				'id'     => 'espresso-toolbar-events-month',
1176
+				'parent' => 'espresso-toolbar-events-view',
1177
+				'title'  => __('This Month', 'event_espresso'),
1178
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1179
+					$events_admin_url),
1180
+				'meta'   => array(
1181
+					'title'  => __('This Month', 'event_espresso'),
1182
+					'target' => '',
1183
+					'class'  => $menu_class,
1184
+				),
1185
+			));
1186
+		}
1187
+		//Registration Overview
1188
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1189
+			'ee_admin_bar_menu_espresso-toolbar-registrations')
1190
+		) {
1191
+			$admin_bar->add_menu(array(
1192
+				'id'     => 'espresso-toolbar-registrations',
1193
+				'parent' => 'espresso-toolbar',
1194
+				'title'  => __('Registrations', 'event_espresso'),
1195
+				'href'   => $reg_admin_url,
1196
+				'meta'   => array(
1197
+					'title'  => __('Registrations', 'event_espresso'),
1198
+					'target' => '',
1199
+					'class'  => $menu_class,
1200
+				),
1201
+			));
1202
+		}
1203
+		//Registration Overview Today
1204
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1205
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today')
1206
+		) {
1207
+			$admin_bar->add_menu(array(
1208
+				'id'     => 'espresso-toolbar-registrations-today',
1209
+				'parent' => 'espresso-toolbar-registrations',
1210
+				'title'  => __('Today', 'event_espresso'),
1211
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'today'),
1212
+					$reg_admin_url),
1213
+				'meta'   => array(
1214
+					'title'  => __('Today', 'event_espresso'),
1215
+					'target' => '',
1216
+					'class'  => $menu_class,
1217
+				),
1218
+			));
1219
+		}
1220
+		//Registration Overview Today Completed
1221
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1222
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-approved')
1223
+		) {
1224
+			$admin_bar->add_menu(array(
1225
+				'id'     => 'espresso-toolbar-registrations-today-approved',
1226
+				'parent' => 'espresso-toolbar-registrations-today',
1227
+				'title'  => __('Approved', 'event_espresso'),
1228
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1229
+					'action'      => 'default',
1230
+					'status'      => 'today',
1231
+					'_reg_status' => EEM_Registration::status_id_approved,
1232
+				), $reg_admin_url),
1233
+				'meta'   => array(
1234
+					'title'  => __('Approved', 'event_espresso'),
1235
+					'target' => '',
1236
+					'class'  => $menu_class,
1237
+				),
1238
+			));
1239
+		}
1240
+		//Registration Overview Today Pending\
1241
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1242
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-pending')
1243
+		) {
1244
+			$admin_bar->add_menu(array(
1245
+				'id'     => 'espresso-toolbar-registrations-today-pending',
1246
+				'parent' => 'espresso-toolbar-registrations-today',
1247
+				'title'  => __('Pending', 'event_espresso'),
1248
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1249
+					'action'     => 'default',
1250
+					'status'     => 'today',
1251
+					'reg_status' => EEM_Registration::status_id_pending_payment,
1252
+				), $reg_admin_url),
1253
+				'meta'   => array(
1254
+					'title'  => __('Pending Payment', 'event_espresso'),
1255
+					'target' => '',
1256
+					'class'  => $menu_class,
1257
+				),
1258
+			));
1259
+		}
1260
+		//Registration Overview Today Incomplete
1261
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1262
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-not-approved')
1263
+		) {
1264
+			$admin_bar->add_menu(array(
1265
+				'id'     => 'espresso-toolbar-registrations-today-not-approved',
1266
+				'parent' => 'espresso-toolbar-registrations-today',
1267
+				'title'  => __('Not Approved', 'event_espresso'),
1268
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1269
+					'action'      => 'default',
1270
+					'status'      => 'today',
1271
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1272
+				), $reg_admin_url),
1273
+				'meta'   => array(
1274
+					'title'  => __('Not Approved', 'event_espresso'),
1275
+					'target' => '',
1276
+					'class'  => $menu_class,
1277
+				),
1278
+			));
1279
+		}
1280
+		//Registration Overview Today Incomplete
1281
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1282
+			'ee_admin_bar_menu_espresso-toolbar-registrations-today-cancelled')
1283
+		) {
1284
+			$admin_bar->add_menu(array(
1285
+				'id'     => 'espresso-toolbar-registrations-today-cancelled',
1286
+				'parent' => 'espresso-toolbar-registrations-today',
1287
+				'title'  => __('Cancelled', 'event_espresso'),
1288
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1289
+					'action'      => 'default',
1290
+					'status'      => 'today',
1291
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1292
+				), $reg_admin_url),
1293
+				'meta'   => array(
1294
+					'title'  => __('Cancelled', 'event_espresso'),
1295
+					'target' => '',
1296
+					'class'  => $menu_class,
1297
+				),
1298
+			));
1299
+		}
1300
+		//Registration Overview This Month
1301
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1302
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month')
1303
+		) {
1304
+			$admin_bar->add_menu(array(
1305
+				'id'     => 'espresso-toolbar-registrations-month',
1306
+				'parent' => 'espresso-toolbar-registrations',
1307
+				'title'  => __('This Month', 'event_espresso'),
1308
+				'href'   => EEH_URL::add_query_args_and_nonce(array('action' => 'default', 'status' => 'month'),
1309
+					$reg_admin_url),
1310
+				'meta'   => array(
1311
+					'title'  => __('This Month', 'event_espresso'),
1312
+					'target' => '',
1313
+					'class'  => $menu_class,
1314
+				),
1315
+			));
1316
+		}
1317
+		//Registration Overview This Month Approved
1318
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1319
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-approved')
1320
+		) {
1321
+			$admin_bar->add_menu(array(
1322
+				'id'     => 'espresso-toolbar-registrations-month-approved',
1323
+				'parent' => 'espresso-toolbar-registrations-month',
1324
+				'title'  => __('Approved', 'event_espresso'),
1325
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1326
+					'action'      => 'default',
1327
+					'status'      => 'month',
1328
+					'_reg_status' => EEM_Registration::status_id_approved,
1329
+				), $reg_admin_url),
1330
+				'meta'   => array(
1331
+					'title'  => __('Approved', 'event_espresso'),
1332
+					'target' => '',
1333
+					'class'  => $menu_class,
1334
+				),
1335
+			));
1336
+		}
1337
+		//Registration Overview This Month Pending
1338
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1339
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-pending')
1340
+		) {
1341
+			$admin_bar->add_menu(array(
1342
+				'id'     => 'espresso-toolbar-registrations-month-pending',
1343
+				'parent' => 'espresso-toolbar-registrations-month',
1344
+				'title'  => __('Pending', 'event_espresso'),
1345
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1346
+					'action'      => 'default',
1347
+					'status'      => 'month',
1348
+					'_reg_status' => EEM_Registration::status_id_pending_payment,
1349
+				), $reg_admin_url),
1350
+				'meta'   => array(
1351
+					'title'  => __('Pending', 'event_espresso'),
1352
+					'target' => '',
1353
+					'class'  => $menu_class,
1354
+				),
1355
+			));
1356
+		}
1357
+		//Registration Overview This Month Not Approved
1358
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1359
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-not-approved')
1360
+		) {
1361
+			$admin_bar->add_menu(array(
1362
+				'id'     => 'espresso-toolbar-registrations-month-not-approved',
1363
+				'parent' => 'espresso-toolbar-registrations-month',
1364
+				'title'  => __('Not Approved', 'event_espresso'),
1365
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1366
+					'action'      => 'default',
1367
+					'status'      => 'month',
1368
+					'_reg_status' => EEM_Registration::status_id_not_approved,
1369
+				), $reg_admin_url),
1370
+				'meta'   => array(
1371
+					'title'  => __('Not Approved', 'event_espresso'),
1372
+					'target' => '',
1373
+					'class'  => $menu_class,
1374
+				),
1375
+			));
1376
+		}
1377
+		//Registration Overview This Month Cancelled
1378
+		if ($this->registry->CAP->current_user_can('ee_read_registrations',
1379
+			'ee_admin_bar_menu_espresso-toolbar-registrations-month-cancelled')
1380
+		) {
1381
+			$admin_bar->add_menu(array(
1382
+				'id'     => 'espresso-toolbar-registrations-month-cancelled',
1383
+				'parent' => 'espresso-toolbar-registrations-month',
1384
+				'title'  => __('Cancelled', 'event_espresso'),
1385
+				'href'   => EEH_URL::add_query_args_and_nonce(array(
1386
+					'action'      => 'default',
1387
+					'status'      => 'month',
1388
+					'_reg_status' => EEM_Registration::status_id_cancelled,
1389
+				), $reg_admin_url),
1390
+				'meta'   => array(
1391
+					'title'  => __('Cancelled', 'event_espresso'),
1392
+					'target' => '',
1393
+					'class'  => $menu_class,
1394
+				),
1395
+			));
1396
+		}
1397
+		//Extensions & Services
1398
+		if ($this->registry->CAP->current_user_can('ee_read_ee',
1399
+			'ee_admin_bar_menu_espresso-toolbar-extensions-and-services')
1400
+		) {
1401
+			$admin_bar->add_menu(array(
1402
+				'id'     => 'espresso-toolbar-extensions-and-services',
1403
+				'parent' => 'espresso-toolbar',
1404
+				'title'  => __('Extensions & Services', 'event_espresso'),
1405
+				'href'   => $extensions_admin_url,
1406
+				'meta'   => array(
1407
+					'title'  => __('Extensions & Services', 'event_espresso'),
1408
+					'target' => '',
1409
+					'class'  => $menu_class,
1410
+				),
1411
+			));
1412
+		}
1413
+	}
1414
+
1415
+
1416
+
1417
+	/**
1418
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1419
+	 * never returned with the function.
1420
+	 *
1421
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1422
+	 * @return array
1423
+	 */
1424
+	public function remove_pages_from_wp_list_pages($exclude_array)
1425
+	{
1426
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1427
+	}
1428
+
1429
+
1430
+
1431
+
1432
+
1433
+
1434
+	/***********************************************        WP_ENQUEUE_SCRIPTS HOOK         ***********************************************/
1435
+	/**
1436
+	 *    wp_enqueue_scripts
1437
+	 *
1438
+	 * @access    public
1439
+	 * @return    void
1440
+	 */
1441
+	public function wp_enqueue_scripts()
1442
+	{
1443
+		// unlike other systems, EE_System_scripts loading is turned ON by default, but prior to the init hook, can be turned off via: add_filter( 'FHEE_load_EE_System_scripts', '__return_false' );
1444
+		if (apply_filters('FHEE_load_EE_System_scripts', true)) {
1445
+			// jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1446
+			if (apply_filters('FHEE_load_jquery_validate', false)) {
1447
+				// register jQuery Validate and additional methods
1448
+				wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1449
+					array('jquery'), '1.15.0', true);
1450
+				wp_register_script('jquery-validate-extra-methods',
1451
+					EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1452
+					array('jquery', 'jquery-validate'), '1.15.0', true);
1453
+			}
1454
+		}
1455
+	}
1456 1456
 
1457 1457
 
1458 1458
 
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
     {
186 186
         // set autoloaders for all of the classes implementing EEI_Plugin_API
187 187
         // which provide helpers for EE plugin authors to more easily register certain components with EE.
188
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
188
+        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'plugin_api');
189 189
         //load and setup EE_Capabilities
190 190
         $this->registry->load_core('Capabilities');
191 191
         do_action('AHEE__EE_System__load_espresso_addons');
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
                 && $_GET['activate'] === 'true'
206 206
             )
207 207
         ) {
208
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
208
+            include_once EE_THIRD_PARTY.'wp-api-basic-auth'.DS.'basic-auth.php';
209 209
         }
210 210
         $this->_maybe_brew_regular();
211 211
         do_action('AHEE__EE_System__load_espresso_addons__complete');
@@ -225,8 +225,8 @@  discard block
 block discarded – undo
225 225
      */
226 226
     private function _maybe_brew_regular()
227 227
     {
228
-        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
229
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
228
+        if (( ! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH.'brewing_regular.php')) {
229
+            require_once EE_CAFF_PATH.'brewing_regular.php';
230 230
         }
231 231
     }
232 232
 
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
     private function _parse_model_names()
706 706
     {
707 707
         //get all the files in the EE_MODELS folder that end in .model.php
708
-        $models = glob(EE_MODELS . '*.model.php');
708
+        $models = glob(EE_MODELS.'*.model.php');
709 709
         $model_names = array();
710 710
         $non_abstract_db_models = array();
711 711
         foreach ($models as $model) {
@@ -769,8 +769,8 @@  discard block
 block discarded – undo
769 769
                 'event_espresso');
770 770
             $msg .= '<ul>';
771 771
             foreach ($class_names as $class_name) {
772
-                $msg .= '<li><b>Event Espresso - ' . str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
773
-                        $class_name) . '</b></li>';
772
+                $msg .= '<li><b>Event Espresso - '.str_replace(array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
773
+                        $class_name).'</b></li>';
774 774
             }
775 775
             $msg .= '</ul>';
776 776
             $msg .= __('Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
@@ -922,8 +922,8 @@  discard block
 block discarded – undo
922 922
     {
923 923
         do_action('AHEE__EE_System__core_loaded_and_ready');
924 924
         // load_espresso_template_tags
925
-        if (is_readable(EE_PUBLIC . 'template_tags.php')) {
926
-            require_once(EE_PUBLIC . 'template_tags.php');
925
+        if (is_readable(EE_PUBLIC.'template_tags.php')) {
926
+            require_once(EE_PUBLIC.'template_tags.php');
927 927
         }
928 928
         do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
929 929
         $this->registry->load_core('Session');
@@ -1068,7 +1068,7 @@  discard block
 block discarded – undo
1068 1068
             'href'  => $events_admin_url,
1069 1069
             'meta'  => array(
1070 1070
                 'title' => __('Event Espresso', 'event_espresso'),
1071
-                'class' => $menu_class . 'first',
1071
+                'class' => $menu_class.'first',
1072 1072
             ),
1073 1073
         ));
1074 1074
         //Events
@@ -1445,10 +1445,10 @@  discard block
 block discarded – undo
1445 1445
             // jquery_validate loading is turned OFF by default, but prior to the wp_enqueue_scripts hook, can be turned back on again via:  add_filter( 'FHEE_load_jquery_validate', '__return_true' );
1446 1446
             if (apply_filters('FHEE_load_jquery_validate', false)) {
1447 1447
                 // register jQuery Validate and additional methods
1448
-                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.min.js',
1448
+                wp_register_script('jquery-validate', EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.min.js',
1449 1449
                     array('jquery'), '1.15.0', true);
1450 1450
                 wp_register_script('jquery-validate-extra-methods',
1451
-                    EE_GLOBAL_ASSETS_URL . 'scripts/jquery.validate.additional-methods.min.js',
1451
+                    EE_GLOBAL_ASSETS_URL.'scripts/jquery.validate.additional-methods.min.js',
1452 1452
                     array('jquery', 'jquery-validate'), '1.15.0', true);
1453 1453
             }
1454 1454
         }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.39.rc.045');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.39.rc.045');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.
modules/core_rest_api/EED_Core_Rest_Api.module.php 2 patches
Indentation   +1234 added lines, -1234 removed lines patch added patch discarded remove patch
@@ -20,1241 +20,1241 @@
 block discarded – undo
20 20
 class EED_Core_Rest_Api extends \EED_Module
21 21
 {
22 22
 
23
-    const ee_api_namespace           = 'ee/v';
23
+	const ee_api_namespace           = 'ee/v';
24 24
 
25
-    const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
26
-
27
-    const saved_routes_option_names  = 'ee_core_routes';
28
-
29
-    /**
30
-     * string used in _links response bodies to make them globally unique.
31
-     *
32
-     * @see http://v2.wp-api.org/extending/linking/
33
-     */
34
-    const ee_api_link_namespace = 'https://api.eventespresso.com/';
35
-
36
-    /**
37
-     * @var CalculatedModelFields
38
-     */
39
-    protected static $_field_calculator = null;
40
-
41
-
42
-
43
-    /**
44
-     * @return EED_Core_Rest_Api
45
-     */
46
-    public static function instance()
47
-    {
48
-        self::$_field_calculator = new CalculatedModelFields();
49
-        return parent::get_instance(__CLASS__);
50
-    }
51
-
52
-
53
-
54
-    /**
55
-     *    set_hooks - for hooking into EE Core, other modules, etc
56
-     *
57
-     * @access    public
58
-     * @return    void
59
-     */
60
-    public static function set_hooks()
61
-    {
62
-        self::set_hooks_both();
63
-    }
64
-
65
-
66
-
67
-    /**
68
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
-     *
70
-     * @access    public
71
-     * @return    void
72
-     */
73
-    public static function set_hooks_admin()
74
-    {
75
-        self::set_hooks_both();
76
-    }
77
-
78
-
79
-
80
-    public static function set_hooks_both()
81
-    {
82
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
83
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
84
-        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
85
-        add_filter('rest_index',
86
-            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
87
-        EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     * sets up hooks which only need to be included as part of REST API requests;
94
-     * other requests like to the frontend or admin etc don't need them
95
-     */
96
-    public static function set_hooks_rest_api()
97
-    {
98
-        //set hooks which account for changes made to the API
99
-        EED_Core_Rest_Api::_set_hooks_for_changes();
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     * public wrapper of _set_hooks_for_changes.
106
-     * Loads all the hooks which make requests to old versions of the API
107
-     * appear the same as they always did
108
-     */
109
-    public static function set_hooks_for_changes()
110
-    {
111
-        self::_set_hooks_for_changes();
112
-    }
113
-
114
-
115
-
116
-    /**
117
-     * Loads all the hooks which make requests to old versions of the API
118
-     * appear the same as they always did
119
-     */
120
-    protected static function _set_hooks_for_changes()
121
-    {
122
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
123
-        foreach ($folder_contents as $classname_in_namespace => $filepath) {
124
-            //ignore the base parent class
125
-            //and legacy named classes
126
-            if ($classname_in_namespace === 'ChangesInBase'
127
-                || strpos($classname_in_namespace, 'Changes_In_') === 0
128
-            ) {
129
-                continue;
130
-            }
131
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
132
-            if (class_exists($full_classname)) {
133
-                $instance_of_class = new $full_classname;
134
-                if ($instance_of_class instanceof ChangesInBase) {
135
-                    $instance_of_class->setHooks();
136
-                }
137
-            }
138
-        }
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * Filters the WP routes to add our EE-related ones. This takes a bit of time
145
-     * so we actually prefer to only do it when an EE plugin is activated or upgraded
146
-     */
147
-    public static function register_routes()
148
-    {
149
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
150
-            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
151
-                /**
152
-                 * @var array $data_for_multiple_endpoints numerically indexed array
153
-                 *                                         but can also contain route options like {
154
-                 * @type array    $schema                      {
155
-                 * @type callable $schema_callback
156
-                 * @type array    $callback_args               arguments that will be passed to the callback, after the
157
-                 * WP_REST_Request of course
158
-                 * }
159
-                 * }
160
-                 */
161
-                //when registering routes, register all the endpoints' data at the same time
162
-                $multiple_endpoint_args = array();
163
-                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
164
-                    /**
165
-                     * @var array     $data_for_single_endpoint {
166
-                     * @type callable $callback
167
-                     * @type string methods
168
-                     * @type array args
169
-                     * @type array _links
170
-                     * @type array    $callback_args            arguments that will be passed to the callback, after the
171
-                     * WP_REST_Request of course
172
-                     * }
173
-                     */
174
-                    //skip route options
175
-                    if (! is_numeric($endpoint_key)) {
176
-                        continue;
177
-                    }
178
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
179
-                        throw new EE_Error(
180
-                            esc_html__(
181
-                                // @codingStandardsIgnoreStart
182
-                                'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
183
-                                // @codingStandardsIgnoreEnd
184
-                                'event_espresso')
185
-                        );
186
-                    }
187
-                    $callback = $data_for_single_endpoint['callback'];
188
-                    $single_endpoint_args = array(
189
-                        'methods' => $data_for_single_endpoint['methods'],
190
-                        'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
191
-                            : array(),
192
-                    );
193
-                    if (isset($data_for_single_endpoint['_links'])) {
194
-                        $single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
195
-                    }
196
-                    if (isset($data_for_single_endpoint['callback_args'])) {
197
-                        $callback_args = $data_for_single_endpoint['callback_args'];
198
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
199
-                            $callback,
200
-                            $callback_args
201
-                        ) {
202
-                            array_unshift($callback_args, $request);
203
-                            return call_user_func_array(
204
-                                $callback,
205
-                                $callback_args
206
-                            );
207
-                        };
208
-                    } else {
209
-                        $single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
210
-                    }
211
-                    $multiple_endpoint_args[] = $single_endpoint_args;
212
-                }
213
-                if (isset($data_for_multiple_endpoints['schema'])) {
214
-                    $schema_route_data = $data_for_multiple_endpoints['schema'];
215
-                    $schema_callback = $schema_route_data['schema_callback'];
216
-                    $callback_args = $schema_route_data['callback_args'];
217
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
218
-                        return call_user_func_array(
219
-                            $schema_callback,
220
-                            $callback_args
221
-                        );
222
-                    };
223
-                }
224
-                register_rest_route(
225
-                    $namespace,
226
-                    $relative_route,
227
-                    $multiple_endpoint_args
228
-                );
229
-            }
230
-        }
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * Checks if there was a version change or something that merits invalidating the cached
237
-     * route data. If so, invalidates the cached route data so that it gets refreshed
238
-     * next time the WP API is used
239
-     */
240
-    public static function invalidate_cached_route_data_on_version_change()
241
-    {
242
-        if (EE_System::instance()->detect_req_type() != EE_System::req_type_normal) {
243
-            EED_Core_Rest_Api::invalidate_cached_route_data();
244
-        }
245
-        foreach (EE_Registry::instance()->addons as $addon) {
246
-            if ($addon instanceof EE_Addon && $addon->detect_req_type() != EE_System::req_type_normal) {
247
-                EED_Core_Rest_Api::invalidate_cached_route_data();
248
-            }
249
-        }
250
-    }
251
-
252
-
253
-
254
-    /**
255
-     * Removes the cached route data so it will get refreshed next time the WP API is used
256
-     */
257
-    public static function invalidate_cached_route_data()
258
-    {
259
-        //delete the saved EE REST API routes
260
-        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
261
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
262
-        }
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * Gets the EE route data
269
-     *
270
-     * @return array top-level key is the namespace, next-level key is the route and its value is array{
271
-     * @type string|array $callback
272
-     * @type string       $methods
273
-     * @type boolean      $hidden_endpoint
274
-     * }
275
-     */
276
-    public static function get_ee_route_data()
277
-    {
278
-        $ee_routes = array();
279
-        foreach (self::versions_served() as $version => $hidden_endpoints) {
280
-            $ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
281
-                $version,
282
-                $hidden_endpoints
283
-            );
284
-        }
285
-        return $ee_routes;
286
-    }
287
-
288
-
289
-
290
-    /**
291
-     * Gets the EE route data from the wp options if it exists already,
292
-     * otherwise re-generates it and saves it to the option
293
-     *
294
-     * @param string  $version
295
-     * @param boolean $hidden_endpoints
296
-     * @return array
297
-     */
298
-    protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
299
-    {
300
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
301
-        if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
302
-            $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
303
-        }
304
-        return $ee_routes;
305
-    }
306
-
307
-
308
-
309
-    /**
310
-     * Saves the EE REST API route data to a wp option and returns it
311
-     *
312
-     * @param string  $version
313
-     * @param boolean $hidden_endpoints
314
-     * @return mixed|null
315
-     */
316
-    protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
317
-    {
318
-        $instance = self::instance();
319
-        $routes = apply_filters(
320
-            'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
321
-            array_replace_recursive(
322
-                $instance->_get_config_route_data_for_version($version, $hidden_endpoints),
323
-                $instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
324
-                $instance->_get_model_route_data_for_version($version, $hidden_endpoints),
325
-                $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
326
-            )
327
-        );
328
-        $option_name = self::saved_routes_option_names . $version;
329
-        if (get_option($option_name)) {
330
-            update_option($option_name, $routes, true);
331
-        } else {
332
-            add_option($option_name, $routes, null, 'no');
333
-        }
334
-        return $routes;
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * Calculates all the EE routes and saves it to a WordPress option so we don't
341
-     * need to calculate it on every request
342
-     *
343
-     * @deprecated since version 4.9.1
344
-     * @return void
345
-     */
346
-    public static function save_ee_routes()
347
-    {
348
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
349
-            $instance = self::instance();
350
-            $routes = apply_filters(
351
-                'EED_Core_Rest_Api__save_ee_routes__routes',
352
-                array_replace_recursive(
353
-                    $instance->_register_config_routes(),
354
-                    $instance->_register_meta_routes(),
355
-                    $instance->_register_model_routes(),
356
-                    $instance->_register_rpc_routes()
357
-                )
358
-            );
359
-            update_option(self::saved_routes_option_names, $routes, true);
360
-        }
361
-    }
362
-
363
-
364
-
365
-    /**
366
-     * Gets all the route information relating to EE models
367
-     *
368
-     * @return array @see get_ee_route_data
369
-     * @deprecated since version 4.9.1
370
-     */
371
-    protected function _register_model_routes()
372
-    {
373
-        $model_routes = array();
374
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
375
-            $model_routes[EED_Core_Rest_Api::ee_api_namespace
376
-                          . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
377
-        }
378
-        return $model_routes;
379
-    }
380
-
381
-
382
-
383
-    /**
384
-     * Decides whether or not to add write endpoints for this model.
385
-     *
386
-     * Currently, this defaults to exclude all global tables and models
387
-     * which would allow inserting WP core data (we don't want to duplicate
388
-     * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
389
-     * @param EEM_Base $model
390
-     * @return bool
391
-     */
392
-    public static function should_have_write_endpoints(EEM_Base $model)
393
-    {
394
-        if ($model->is_wp_core_model()){
395
-            return false;
396
-        }
397
-        foreach($model->get_tables() as $table){
398
-            if( $table->is_global()){
399
-                return false;
400
-            }
401
-        }
402
-        return true;
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
409
-     * in this versioned namespace of EE4
410
-     * @param $version
411
-     * @return array keys are model names (eg 'Event') and values ar etheir classnames (eg 'EEM_Event')
412
-     */
413
-    public static function model_names_with_plural_routes($version){
414
-        $model_version_info = new ModelVersionInfo($version);
415
-        $models_to_register = $model_version_info->modelsForRequestedVersion();
416
-        //let's not bother having endpoints for extra metas
417
-        unset($models_to_register['Extra_Meta']);
418
-        unset($models_to_register['Extra_Join']);
419
-        unset($models_to_register['Post_Meta']);
420
-        return apply_filters(
421
-            'FHEE__EED_Core_REST_API___register_model_routes',
422
-            $models_to_register
423
-        );
424
-    }
425
-
426
-
427
-
428
-    /**
429
-     * Gets the route data for EE models in the specified version
430
-     *
431
-     * @param string  $version
432
-     * @param boolean $hidden_endpoint
433
-     * @return array
434
-     */
435
-    protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
436
-    {
437
-        $model_routes = array();
438
-        $model_version_info = new ModelVersionInfo($version);
439
-        foreach ($this->model_names_with_plural_routes($version) as $model_name => $model_classname) {
440
-            $model = \EE_Registry::instance()->load_model($model_name);
441
-            //if this isn't a valid model then let's skip iterate to the next item in the loop.
442
-            if (! $model instanceof EEM_Base) {
443
-                continue;
444
-            }
445
-            //yes we could just register one route for ALL models, but then they wouldn't show up in the index
446
-            $plural_model_route = EED_Core_Rest_Api::get_plural_route_to($model_name);
447
-            $singular_model_route = EED_Core_Rest_Api::get_singular_route_to($model_name, '(?P<id>[^\/]+)');
448
-            $model_routes[$plural_model_route] = array(
449
-                array(
450
-                    'callback'        => array(
451
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
452
-                        'handleRequestGetAll',
453
-                    ),
454
-                    'callback_args'   => array($version, $model_name),
455
-                    'methods'         => WP_REST_Server::READABLE,
456
-                    'hidden_endpoint' => $hidden_endpoint,
457
-                    'args'            => $this->_get_read_query_params($model, $version),
458
-                    '_links'          => array(
459
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
460
-                    ),
461
-                ),
462
-                'schema' => array(
463
-                    'schema_callback' => array(
464
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
465
-                        'handleSchemaRequest',
466
-                    ),
467
-                    'callback_args'   => array($version, $model_name),
468
-                ),
469
-            );
470
-            $model_routes[$singular_model_route] = array(
471
-                array(
472
-                    'callback'        => array(
473
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
474
-                        'handleRequestGetOne',
475
-                    ),
476
-                    'callback_args'   => array($version, $model_name),
477
-                    'methods'         => WP_REST_Server::READABLE,
478
-                    'hidden_endpoint' => $hidden_endpoint,
479
-                    'args'            => $this->_get_response_selection_query_params($model, $version),
480
-                ),
481
-            );
482
-            if( apply_filters(
483
-                'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
484
-                $this->should_have_write_endpoints($model),
485
-                $model
486
-            )){
487
-                $model_routes[$plural_model_route][] = array(
488
-                    'callback'        => array(
489
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Write',
490
-                        'handleRequestInsert',
491
-                    ),
492
-                    'callback_args'   => array($version, $model_name),
493
-                    'methods'         => WP_REST_Server::CREATABLE,
494
-                    'hidden_endpoint' => $hidden_endpoint,
495
-                    'args'            => $this->_get_write_params($model_name, $model_version_info, true),
496
-                );
497
-                $model_routes[$singular_model_route] = array_merge(
498
-                    $model_routes[$singular_model_route],
499
-                    array(
500
-                        array(
501
-                            'callback'        => array(
502
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
503
-                                'handleRequestUpdate',
504
-                            ),
505
-                            'callback_args'   => array($version, $model_name),
506
-                            'methods'         => WP_REST_Server::EDITABLE,
507
-                            'hidden_endpoint' => $hidden_endpoint,
508
-                            'args'            => $this->_get_write_params($model_name, $model_version_info, false),
509
-                        ),
510
-                        array(
511
-                            'callback'        => array(
512
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
513
-                                'handleRequestDelete',
514
-                            ),
515
-                            'callback_args'   => array($version, $model_name),
516
-                            'methods'         => WP_REST_Server::DELETABLE,
517
-                            'hidden_endpoint' => $hidden_endpoint,
518
-                            'args'            => $this->_get_delete_query_params($model, $version),
519
-                        )
520
-                    )
521
-                );
522
-            }
523
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
524
-
525
-                $related_route = EED_Core_Rest_Api::get_related_route_to(
526
-                    $model_name,
527
-                    '(?P<id>[^\/]+)',
528
-                    $relation_obj
529
-                );
530
-                $endpoints = array(
531
-                    array(
532
-                        'callback'        => array(
533
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Read',
534
-                            'handleRequestGetRelated',
535
-                        ),
536
-                        'callback_args'   => array($version, $model_name, $relation_name),
537
-                        'methods'         => WP_REST_Server::READABLE,
538
-                        'hidden_endpoint' => $hidden_endpoint,
539
-                        'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
540
-                    ),
541
-                );
542
-                $model_routes[$related_route] = $endpoints;
543
-            }
544
-        }
545
-        return $model_routes;
546
-    }
547
-
548
-
549
-
550
-    /**
551
-     * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
552
-     * excluding the preceding slash.
553
-     * Eg you pass get_plural_route_to('Event') = 'events'
554
-     * @param string $model_name eg Event or Venue
555
-     * @return string
556
-     */
557
-    public static function get_plural_route_to($model_name)
558
-    {
559
-        return EEH_Inflector::pluralize_and_lower($model_name);
560
-    }
561
-
562
-
563
-
564
-    /**
565
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
566
-     * excluding the preceding slash.
567
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
568
-     * @param string $model_name eg Event or Venue
569
-     * @param string $id
570
-     * @return string
571
-     */
572
-    public static function get_singular_route_to($model_name, $id)
573
-    {
574
-        return EEH_Inflector::pluralize_and_lower($model_name) . '/' . $id;
575
-    }
576
-
577
-
578
-    /**
579
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
580
-     * excluding the preceding slash.
581
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
582
-     *
583
-     * @param string                $model_name eg Event or Venue
584
-     * @param string                $id
585
-     * @param EE_Model_Relation_Base $relation_obj
586
-     * @return string
587
-     */
588
-    public static function get_related_route_to($model_name, $id, $relation_obj)
589
-    {
590
-        $related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
591
-            $relation_obj->get_other_model()->get_this_model_name(),
592
-            $relation_obj
593
-        );
594
-        return EED_Core_Rest_Api::get_singular_route_to($model_name, $id) . '/' . $related_model_name_endpoint_part;
595
-    }
596
-
597
-
598
-
599
-    /**
600
-     * Adds onto the $relative_route the EE4 REST API versioned namespace.
601
-     * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
602
-     * @param string $relative_route
603
-     * @param string $version
604
-     * @return string
605
-     */
606
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
607
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
608
-    }
609
-
610
-
611
-
612
-    /**
613
-     * Adds all the RPC-style routes (remote procedure call-like routes, ie
614
-     * routes that don't conform to the traditional REST CRUD-style).
615
-     *
616
-     * @deprecated since 4.9.1
617
-     */
618
-    protected function _register_rpc_routes()
619
-    {
620
-        $routes = array();
621
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
622
-            $routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
623
-                $version,
624
-                $hidden_endpoint
625
-            );
626
-        }
627
-        return $routes;
628
-    }
629
-
630
-
631
-
632
-    /**
633
-     * @param string  $version
634
-     * @param boolean $hidden_endpoint
635
-     * @return array
636
-     */
637
-    protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
638
-    {
639
-        $this_versions_routes = array();
640
-        //checkin endpoint
641
-        $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
642
-            array(
643
-                'callback'        => array(
644
-                    'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
645
-                    'handleRequestToggleCheckin',
646
-                ),
647
-                'methods'         => WP_REST_Server::CREATABLE,
648
-                'hidden_endpoint' => $hidden_endpoint,
649
-                'args'            => array(
650
-                    'force' => array(
651
-                        'required'    => false,
652
-                        'default'     => false,
653
-                        'description' => __(
654
-                            // @codingStandardsIgnoreStart
655
-                            'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
656
-                            // @codingStandardsIgnoreEnd
657
-                            'event_espresso'
658
-                        ),
659
-                    ),
660
-                ),
661
-                'callback_args'   => array($version),
662
-            ),
663
-        );
664
-        return apply_filters(
665
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
666
-            $this_versions_routes,
667
-            $version,
668
-            $hidden_endpoint
669
-        );
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Gets the query params that can be used when request one or many
676
-     *
677
-     * @param EEM_Base $model
678
-     * @param string   $version
679
-     * @return array
680
-     */
681
-    protected function _get_response_selection_query_params(\EEM_Base $model, $version)
682
-    {
683
-        return apply_filters(
684
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
685
-            array(
686
-                'include'   => array(
687
-                    'required' => false,
688
-                    'default'  => '*',
689
-                    'type'     => 'string',
690
-                ),
691
-                'calculate' => array(
692
-                    'required'          => false,
693
-                    'default'           => '',
694
-                    'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
695
-                    'type'              => 'string',
696
-                    //because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
697
-                    //freaks out. We'll just validate this argument while handling the request
698
-                    'validate_callback' => null,
699
-                    'sanitize_callback' => null,
700
-                ),
701
-            ),
702
-            $model,
703
-            $version
704
-        );
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * Gets the parameters acceptable for delete requests
711
-     *
712
-     * @param \EEM_Base $model
713
-     * @param string    $version
714
-     * @return array
715
-     */
716
-    protected function _get_delete_query_params(\EEM_Base $model, $version)
717
-    {
718
-        $params_for_delete = array(
719
-            'allow_blocking' => array(
720
-                'required' => false,
721
-                'default'  => true,
722
-                'type'     => 'boolean',
723
-            ),
724
-        );
725
-        $params_for_delete['force'] = array(
726
-            'required' => false,
727
-            'default'  => false,
728
-            'type'     => 'boolean',
729
-        );
730
-        return apply_filters(
731
-            'FHEE__EED_Core_Rest_Api___get_delete_query_params',
732
-            $params_for_delete,
733
-            $model,
734
-            $version
735
-        );
736
-    }
737
-
738
-
739
-
740
-    /**
741
-     * Gets info about reading query params that are acceptable
742
-     *
743
-     * @param \EEM_Base $model eg 'Event' or 'Venue'
744
-     * @param  string   $version
745
-     * @return array    describing the args acceptable when querying this model
746
-     * @throws \EE_Error
747
-     */
748
-    protected function _get_read_query_params(\EEM_Base $model, $version)
749
-    {
750
-        $default_orderby = array();
751
-        foreach ($model->get_combined_primary_key_fields() as $key_field) {
752
-            $default_orderby[$key_field->get_name()] = 'ASC';
753
-        }
754
-        return array_merge(
755
-            $this->_get_response_selection_query_params($model, $version),
756
-            array(
757
-                'where'    => array(
758
-                    'required' => false,
759
-                    'default'  => array(),
760
-                    'type'     => 'object',
761
-                ),
762
-                'limit'    => array(
763
-                    'required' => false,
764
-                    'default'  => EED_Core_Rest_Api::get_default_query_limit(),
765
-                    'type'     => array(
766
-                        'object',
767
-                        'string',
768
-                        'integer',
769
-                    ),
770
-                ),
771
-                'order_by' => array(
772
-                    'required' => false,
773
-                    'default'  => $default_orderby,
774
-                    'type'     => array(
775
-                        'object',
776
-                        'string',
777
-                    ),
778
-                ),
779
-                'group_by' => array(
780
-                    'required' => false,
781
-                    'default'  => null,
782
-                    'type'     => array(
783
-                        'object',
784
-                        'string',
785
-                    ),
786
-                ),
787
-                'having'   => array(
788
-                    'required' => false,
789
-                    'default'  => null,
790
-                    'type'     => 'object',
791
-                ),
792
-                'caps'     => array(
793
-                    'required' => false,
794
-                    'default'  => EEM_Base::caps_read,
795
-                    'type'     => 'string',
796
-                ),
797
-            )
798
-        );
799
-    }
800
-
801
-
802
-
803
-    /**
804
-     * Gets parameter information for a model regarding writing data
805
-     *
806
-     * @param string           $model_name
807
-     * @param ModelVersionInfo $model_version_info
808
-     * @param boolean          $create                                       whether this is for request to create (in which case we need
809
-     *                                                                       all required params) or just to update (in which case we don't need those on every request)
810
-     * @return array
811
-     */
812
-    protected function _get_write_params(
813
-        $model_name,
814
-        ModelVersionInfo $model_version_info,
815
-        $create = false
816
-    ) {
817
-        $model = EE_Registry::instance()->load_model($model_name);
818
-        $fields = $model_version_info->fieldsOnModelInThisVersion($model);
819
-        $args_info = array();
820
-        foreach ($fields as $field_name => $field_obj) {
821
-            if ($field_obj->is_auto_increment()) {
822
-                //totally ignore auto increment IDs
823
-                continue;
824
-            }
825
-            $arg_info = $field_obj->getSchema();
826
-            $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
827
-            $arg_info['required'] = $required;
828
-            //remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
829
-            unset($arg_info['readonly']);
830
-            $schema_properties = $field_obj->getSchemaProperties();
831
-            if ($field_obj->getSchemaType() === 'object'
832
-                && isset($schema_properties['raw'])
833
-            ) {
834
-                //if there's a "raw" form of this argument, use those properties instead
835
-                $arg_info = array_replace(
836
-                    $arg_info,
837
-                    $schema_properties['raw']
838
-                );
839
-            }
840
-            $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
841
-                $field_obj,
842
-                $field_obj->get_default_value(),
843
-                $model_version_info->requestedVersion()
844
-            );
845
-            //we do our own validation and sanitization within the controller
846
-            $arg_info['sanitize_callback'] =
847
-                array(
848
-                    'EED_Core_Rest_Api',
849
-                    'default_sanitize_callback',
850
-                );
851
-            $args_info[$field_name] = $arg_info;
852
-            if ($field_obj instanceof EE_Datetime_Field) {
853
-                $gmt_arg_info = $arg_info;
854
-                $gmt_arg_info['description'] = sprintf(
855
-                    esc_html__(
856
-                        '%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
857
-                        'event_espresso'
858
-                    ),
859
-                    $field_obj->get_nicename(),
860
-                    $field_name
861
-                );
862
-                $args_info[$field_name . '_gmt'] = $gmt_arg_info;
863
-            }
864
-        }
865
-        return $args_info;
866
-    }
867
-
868
-
869
-
870
-    /**
871
-     * Replacement for WP API's 'rest_parse_request_arg'. If the value is blank but not required, don't bother validating it.
872
-     * Also, it uses our email validation instead of WP API's default.
873
-     * @param                 $value
874
-     * @param WP_REST_Request $request
875
-     * @param                 $param
876
-     * @return bool|true|WP_Error
877
-     */
878
-    public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
879
-    {
880
-        $attributes = $request->get_attributes();
881
-        if (! isset($attributes['args'][$param])
882
-            || ! is_array($attributes['args'][$param])) {
883
-            $validation_result = true;
884
-        } else {
885
-            $args = $attributes['args'][$param];
886
-            if ((
887
-                    $value === ''
888
-                    || $value === null
889
-                )
890
-                && (! isset($args['required'])
891
-                    || $args['required'] === false
892
-                )
893
-            ) {
894
-                //not required and not provided? that's cool
895
-                $validation_result = true;
896
-            } elseif (isset($args['format'])
897
-                && $args['format'] === 'email'
898
-            ) {
899
-                if (! self::_validate_email($value)) {
900
-                    $validation_result = new WP_Error(
901
-                        'rest_invalid_param',
902
-                        esc_html__('The email address is not valid or does not exist.', 'event_espresso')
903
-                    );
904
-                } else {
905
-                    $validation_result = true;
906
-                }
907
-            } else {
908
-                $validation_result = rest_validate_value_from_schema($value, $args, $param);
909
-            }
910
-        }
911
-        if (is_wp_error($validation_result)) {
912
-            return $validation_result;
913
-        }
914
-        return rest_sanitize_request_arg($value, $request, $param);
915
-    }
916
-
917
-
918
-
919
-    /**
920
-     * Returns whether or not this email address is vaild. Copied from EE_Email_Valdiation_Strategy::_validate_email()
921
-     * @param $email
922
-     * @return bool
923
-     */
924
-    protected static function _validate_email($email){
925
-        $validation_level = isset( EE_Registry::instance()->CFG->registration->email_validation_level )
926
-            ? EE_Registry::instance()->CFG->registration->email_validation_level
927
-            : 'wp_default';
928
-        if ( ! preg_match( '/^.+\@\S+$/', $email ) ) { // \.\S+
929
-            // email not in correct {string}@{string} format
930
-            return false;
931
-        } else {
932
-            $atIndex = strrpos( $email, "@" );
933
-            $domain = substr( $email, $atIndex + 1 );
934
-            $local = substr( $email, 0, $atIndex );
935
-            $localLen = strlen( $local );
936
-            $domainLen = strlen( $domain );
937
-            if ( $localLen < 1 || $localLen > 64 ) {
938
-                // local part length exceeded
939
-                return false;
940
-            } else if ( $domainLen < 1 || $domainLen > 255 ) {
941
-                // domain part length exceeded
942
-                return false;
943
-            } else if ( $local[ 0 ] === '.' || $local[ $localLen - 1 ] === '.' ) {
944
-                // local part starts or ends with '.'
945
-                return false;
946
-            } else if ( preg_match( '/\\.\\./', $local ) ) {
947
-                // local part has two consecutive dots
948
-                return false;
949
-            } else if ( preg_match( '/\\.\\./', $domain ) ) {
950
-                // domain part has two consecutive dots
951
-                return false;
952
-            } else if ( $validation_level === 'wp_default' ) {
953
-                return is_email( $email );
954
-            } else if (
955
-                ( $validation_level === 'i18n' || $validation_level === 'i18n_dns' )
956
-                // plz see http://stackoverflow.com/a/24817336 re: the following regex
957
-                && ! preg_match(
958
-                    '/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\.!#$%&\'*+-\/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\-\.\d]+)((\.([a-zA-Z\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}]){2,63})+)$/u',
959
-                    $email
960
-                )
961
-            ) {
962
-                return false;
963
-            }
964
-            if ( $validation_level === 'i18n_dns' ) {
965
-                if ( ! checkdnsrr( $domain, "MX" ) ) {
966
-                    // domain not found in MX records
967
-                    return false;
968
-                } else if ( ! checkdnsrr( $domain, "A" ) ) {
969
-                    // domain not found in A records
970
-                    return false;
971
-                }
972
-            }
973
-        }
974
-        // you have successfully run the gauntlet young Padawan
975
-        return true;
976
-    }
977
-
978
-
979
-
980
-    /**
981
-     * Gets routes for the config
982
-     *
983
-     * @return array @see _register_model_routes
984
-     * @deprecated since version 4.9.1
985
-     */
986
-    protected function _register_config_routes()
987
-    {
988
-        $config_routes = array();
989
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
990
-            $config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
991
-                $version,
992
-                $hidden_endpoint
993
-            );
994
-        }
995
-        return $config_routes;
996
-    }
997
-
998
-
999
-
1000
-    /**
1001
-     * Gets routes for the config for the specified version
1002
-     *
1003
-     * @param string  $version
1004
-     * @param boolean $hidden_endpoint
1005
-     * @return array
1006
-     */
1007
-    protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1008
-    {
1009
-        return array(
1010
-            'config'    => array(
1011
-                array(
1012
-                    'callback'        => array(
1013
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1014
-                        'handleRequest',
1015
-                    ),
1016
-                    'methods'         => WP_REST_Server::READABLE,
1017
-                    'hidden_endpoint' => $hidden_endpoint,
1018
-                    'callback_args'   => array($version),
1019
-                ),
1020
-            ),
1021
-            'site_info' => array(
1022
-                array(
1023
-                    'callback'        => array(
1024
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1025
-                        'handleRequestSiteInfo',
1026
-                    ),
1027
-                    'methods'         => WP_REST_Server::READABLE,
1028
-                    'hidden_endpoint' => $hidden_endpoint,
1029
-                    'callback_args'   => array($version),
1030
-                ),
1031
-            ),
1032
-        );
1033
-    }
1034
-
1035
-
1036
-
1037
-    /**
1038
-     * Gets the meta info routes
1039
-     *
1040
-     * @return array @see _register_model_routes
1041
-     * @deprecated since version 4.9.1
1042
-     */
1043
-    protected function _register_meta_routes()
1044
-    {
1045
-        $meta_routes = array();
1046
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1047
-            $meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1048
-                $version,
1049
-                $hidden_endpoint
1050
-            );
1051
-        }
1052
-        return $meta_routes;
1053
-    }
1054
-
1055
-
1056
-
1057
-    /**
1058
-     * @param string  $version
1059
-     * @param boolean $hidden_endpoint
1060
-     * @return array
1061
-     */
1062
-    protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1063
-    {
1064
-        return array(
1065
-            'resources' => array(
1066
-                array(
1067
-                    'callback'        => array(
1068
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1069
-                        'handleRequestModelsMeta',
1070
-                    ),
1071
-                    'methods'         => WP_REST_Server::READABLE,
1072
-                    'hidden_endpoint' => $hidden_endpoint,
1073
-                    'callback_args'   => array($version),
1074
-                ),
1075
-            ),
1076
-        );
1077
-    }
1078
-
1079
-
1080
-
1081
-    /**
1082
-     * Tries to hide old 4.6 endpoints from the
1083
-     *
1084
-     * @param array $route_data
1085
-     * @return array
1086
-     */
1087
-    public static function hide_old_endpoints($route_data)
1088
-    {
1089
-        //allow API clients to override which endpoints get hidden, in case
1090
-        //they want to discover particular endpoints
1091
-        //also, we don't have access to the request so we have to just grab it from the superglobal
1092
-        $force_show_ee_namespace = ltrim(
1093
-            EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1094
-            '/'
1095
-        );
1096
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1097
-            foreach ($relative_urls as $resource_name => $endpoints) {
1098
-                foreach ($endpoints as $key => $endpoint) {
1099
-                    //skip schema and other route options
1100
-                    if (! is_numeric($key)) {
1101
-                        continue;
1102
-                    }
1103
-                    //by default, hide "hidden_endpoint"s, unless the request indicates
1104
-                    //to $force_show_ee_namespace, in which case only show that one
1105
-                    //namespace's endpoints (and hide all others)
1106
-                    if (($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1107
-                        || ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1108
-                    ) {
1109
-                        $full_route = '/' . ltrim($namespace, '/') . '/' . ltrim($resource_name, '/');
1110
-                        unset($route_data[$full_route]);
1111
-                    }
1112
-                }
1113
-            }
1114
-        }
1115
-        return $route_data;
1116
-    }
1117
-
1118
-
1119
-
1120
-    /**
1121
-     * Returns an array describing which versions of core support serving requests for.
1122
-     * Keys are core versions' major and minor version, and values are the
1123
-     * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1124
-     * data by just removing a few models and fields from the responses. However, 4.15 might remove
1125
-     * the answers table entirely, in which case it would be very difficult for
1126
-     * it to serve 4.6-style responses.
1127
-     * Versions of core that are missing from this array are unknowns.
1128
-     * previous ver
1129
-     *
1130
-     * @return array
1131
-     */
1132
-    public static function version_compatibilities()
1133
-    {
1134
-        return apply_filters(
1135
-            'FHEE__EED_Core_REST_API__version_compatibilities',
1136
-            array(
1137
-                '4.8.29' => '4.8.29',
1138
-                '4.8.33' => '4.8.29',
1139
-                '4.8.34' => '4.8.29',
1140
-                '4.8.36' => '4.8.29',
1141
-            )
1142
-        );
1143
-    }
1144
-
1145
-
1146
-
1147
-    /**
1148
-     * Gets the latest API version served. Eg if there
1149
-     * are two versions served of the API, 4.8.29 and 4.8.32, and
1150
-     * we are on core version 4.8.34, it will return the string "4.8.32"
1151
-     *
1152
-     * @return string
1153
-     */
1154
-    public static function latest_rest_api_version()
1155
-    {
1156
-        $versions_served = \EED_Core_Rest_Api::versions_served();
1157
-        $versions_served_keys = array_keys($versions_served);
1158
-        return end($versions_served_keys);
1159
-    }
1160
-
1161
-
1162
-
1163
-    /**
1164
-     * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1165
-     * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1166
-     * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1167
-     * We also indicate whether or not this version should be put in the index or not
1168
-     *
1169
-     * @return array keys are API version numbers (just major and minor numbers), and values
1170
-     * are whether or not they should be hidden
1171
-     */
1172
-    public static function versions_served()
1173
-    {
1174
-        $versions_served = array();
1175
-        $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1176
-        $lowest_compatible_version = end($possibly_served_versions);
1177
-        reset($possibly_served_versions);
1178
-        $versions_served_historically = array_keys($possibly_served_versions);
1179
-        $latest_version = end($versions_served_historically);
1180
-        reset($versions_served_historically);
1181
-        //for each version of core we have ever served:
1182
-        foreach ($versions_served_historically as $key_versioned_endpoint) {
1183
-            //if it's not above the current core version, and it's compatible with the current version of core
1184
-            if ($key_versioned_endpoint == $latest_version) {
1185
-                //don't hide the latest version in the index
1186
-                $versions_served[$key_versioned_endpoint] = false;
1187
-            } elseif ($key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1188
-                && $key_versioned_endpoint >= $lowest_compatible_version
1189
-            ) {
1190
-                //include, but hide, previous versions which are still supported
1191
-                $versions_served[$key_versioned_endpoint] = true;
1192
-            } elseif (apply_filters(
1193
-                'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1194
-                false,
1195
-                $possibly_served_versions
1196
-            )) {
1197
-                //if a version is no longer supported, don't include it in index or list of versions served
1198
-                $versions_served[$key_versioned_endpoint] = true;
1199
-            }
1200
-        }
1201
-        return $versions_served;
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Gets the major and minor version of EE core's version string
1208
-     *
1209
-     * @return string
1210
-     */
1211
-    public static function core_version()
1212
-    {
1213
-        return apply_filters(
1214
-            'FHEE__EED_Core_REST_API__core_version',
1215
-            implode(
1216
-                '.',
1217
-                array_slice(
1218
-                    explode(
1219
-                        '.',
1220
-                        espresso_version()
1221
-                    ),
1222
-                0,
1223
-                3
1224
-                )
1225
-            )
1226
-        );
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * Gets the default limit that should be used when querying for resources
1233
-     *
1234
-     * @return int
1235
-     */
1236
-    public static function get_default_query_limit()
1237
-    {
1238
-        //we actually don't use a const because we want folks to always use
1239
-        //this method, not the const directly
1240
-        return apply_filters(
1241
-            'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1242
-            50
1243
-        );
1244
-    }
1245
-
1246
-
1247
-
1248
-    /**
1249
-     *    run - initial module setup
1250
-     *
1251
-     * @access    public
1252
-     * @param  WP $WP
1253
-     * @return    void
1254
-     */
1255
-    public function run($WP)
1256
-    {
1257
-    }
25
+	const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
26
+
27
+	const saved_routes_option_names  = 'ee_core_routes';
28
+
29
+	/**
30
+	 * string used in _links response bodies to make them globally unique.
31
+	 *
32
+	 * @see http://v2.wp-api.org/extending/linking/
33
+	 */
34
+	const ee_api_link_namespace = 'https://api.eventespresso.com/';
35
+
36
+	/**
37
+	 * @var CalculatedModelFields
38
+	 */
39
+	protected static $_field_calculator = null;
40
+
41
+
42
+
43
+	/**
44
+	 * @return EED_Core_Rest_Api
45
+	 */
46
+	public static function instance()
47
+	{
48
+		self::$_field_calculator = new CalculatedModelFields();
49
+		return parent::get_instance(__CLASS__);
50
+	}
51
+
52
+
53
+
54
+	/**
55
+	 *    set_hooks - for hooking into EE Core, other modules, etc
56
+	 *
57
+	 * @access    public
58
+	 * @return    void
59
+	 */
60
+	public static function set_hooks()
61
+	{
62
+		self::set_hooks_both();
63
+	}
64
+
65
+
66
+
67
+	/**
68
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
+	 *
70
+	 * @access    public
71
+	 * @return    void
72
+	 */
73
+	public static function set_hooks_admin()
74
+	{
75
+		self::set_hooks_both();
76
+	}
77
+
78
+
79
+
80
+	public static function set_hooks_both()
81
+	{
82
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
83
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
84
+		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
85
+		add_filter('rest_index',
86
+			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
87
+		EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 * sets up hooks which only need to be included as part of REST API requests;
94
+	 * other requests like to the frontend or admin etc don't need them
95
+	 */
96
+	public static function set_hooks_rest_api()
97
+	{
98
+		//set hooks which account for changes made to the API
99
+		EED_Core_Rest_Api::_set_hooks_for_changes();
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 * public wrapper of _set_hooks_for_changes.
106
+	 * Loads all the hooks which make requests to old versions of the API
107
+	 * appear the same as they always did
108
+	 */
109
+	public static function set_hooks_for_changes()
110
+	{
111
+		self::_set_hooks_for_changes();
112
+	}
113
+
114
+
115
+
116
+	/**
117
+	 * Loads all the hooks which make requests to old versions of the API
118
+	 * appear the same as they always did
119
+	 */
120
+	protected static function _set_hooks_for_changes()
121
+	{
122
+		$folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
123
+		foreach ($folder_contents as $classname_in_namespace => $filepath) {
124
+			//ignore the base parent class
125
+			//and legacy named classes
126
+			if ($classname_in_namespace === 'ChangesInBase'
127
+				|| strpos($classname_in_namespace, 'Changes_In_') === 0
128
+			) {
129
+				continue;
130
+			}
131
+			$full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
132
+			if (class_exists($full_classname)) {
133
+				$instance_of_class = new $full_classname;
134
+				if ($instance_of_class instanceof ChangesInBase) {
135
+					$instance_of_class->setHooks();
136
+				}
137
+			}
138
+		}
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * Filters the WP routes to add our EE-related ones. This takes a bit of time
145
+	 * so we actually prefer to only do it when an EE plugin is activated or upgraded
146
+	 */
147
+	public static function register_routes()
148
+	{
149
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
150
+			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
151
+				/**
152
+				 * @var array $data_for_multiple_endpoints numerically indexed array
153
+				 *                                         but can also contain route options like {
154
+				 * @type array    $schema                      {
155
+				 * @type callable $schema_callback
156
+				 * @type array    $callback_args               arguments that will be passed to the callback, after the
157
+				 * WP_REST_Request of course
158
+				 * }
159
+				 * }
160
+				 */
161
+				//when registering routes, register all the endpoints' data at the same time
162
+				$multiple_endpoint_args = array();
163
+				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
164
+					/**
165
+					 * @var array     $data_for_single_endpoint {
166
+					 * @type callable $callback
167
+					 * @type string methods
168
+					 * @type array args
169
+					 * @type array _links
170
+					 * @type array    $callback_args            arguments that will be passed to the callback, after the
171
+					 * WP_REST_Request of course
172
+					 * }
173
+					 */
174
+					//skip route options
175
+					if (! is_numeric($endpoint_key)) {
176
+						continue;
177
+					}
178
+					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
179
+						throw new EE_Error(
180
+							esc_html__(
181
+								// @codingStandardsIgnoreStart
182
+								'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
183
+								// @codingStandardsIgnoreEnd
184
+								'event_espresso')
185
+						);
186
+					}
187
+					$callback = $data_for_single_endpoint['callback'];
188
+					$single_endpoint_args = array(
189
+						'methods' => $data_for_single_endpoint['methods'],
190
+						'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
191
+							: array(),
192
+					);
193
+					if (isset($data_for_single_endpoint['_links'])) {
194
+						$single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
195
+					}
196
+					if (isset($data_for_single_endpoint['callback_args'])) {
197
+						$callback_args = $data_for_single_endpoint['callback_args'];
198
+						$single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
199
+							$callback,
200
+							$callback_args
201
+						) {
202
+							array_unshift($callback_args, $request);
203
+							return call_user_func_array(
204
+								$callback,
205
+								$callback_args
206
+							);
207
+						};
208
+					} else {
209
+						$single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
210
+					}
211
+					$multiple_endpoint_args[] = $single_endpoint_args;
212
+				}
213
+				if (isset($data_for_multiple_endpoints['schema'])) {
214
+					$schema_route_data = $data_for_multiple_endpoints['schema'];
215
+					$schema_callback = $schema_route_data['schema_callback'];
216
+					$callback_args = $schema_route_data['callback_args'];
217
+					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
218
+						return call_user_func_array(
219
+							$schema_callback,
220
+							$callback_args
221
+						);
222
+					};
223
+				}
224
+				register_rest_route(
225
+					$namespace,
226
+					$relative_route,
227
+					$multiple_endpoint_args
228
+				);
229
+			}
230
+		}
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * Checks if there was a version change or something that merits invalidating the cached
237
+	 * route data. If so, invalidates the cached route data so that it gets refreshed
238
+	 * next time the WP API is used
239
+	 */
240
+	public static function invalidate_cached_route_data_on_version_change()
241
+	{
242
+		if (EE_System::instance()->detect_req_type() != EE_System::req_type_normal) {
243
+			EED_Core_Rest_Api::invalidate_cached_route_data();
244
+		}
245
+		foreach (EE_Registry::instance()->addons as $addon) {
246
+			if ($addon instanceof EE_Addon && $addon->detect_req_type() != EE_System::req_type_normal) {
247
+				EED_Core_Rest_Api::invalidate_cached_route_data();
248
+			}
249
+		}
250
+	}
251
+
252
+
253
+
254
+	/**
255
+	 * Removes the cached route data so it will get refreshed next time the WP API is used
256
+	 */
257
+	public static function invalidate_cached_route_data()
258
+	{
259
+		//delete the saved EE REST API routes
260
+		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
261
+			delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
262
+		}
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * Gets the EE route data
269
+	 *
270
+	 * @return array top-level key is the namespace, next-level key is the route and its value is array{
271
+	 * @type string|array $callback
272
+	 * @type string       $methods
273
+	 * @type boolean      $hidden_endpoint
274
+	 * }
275
+	 */
276
+	public static function get_ee_route_data()
277
+	{
278
+		$ee_routes = array();
279
+		foreach (self::versions_served() as $version => $hidden_endpoints) {
280
+			$ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
281
+				$version,
282
+				$hidden_endpoints
283
+			);
284
+		}
285
+		return $ee_routes;
286
+	}
287
+
288
+
289
+
290
+	/**
291
+	 * Gets the EE route data from the wp options if it exists already,
292
+	 * otherwise re-generates it and saves it to the option
293
+	 *
294
+	 * @param string  $version
295
+	 * @param boolean $hidden_endpoints
296
+	 * @return array
297
+	 */
298
+	protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
299
+	{
300
+		$ee_routes = get_option(self::saved_routes_option_names . $version, null);
301
+		if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
302
+			$ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
303
+		}
304
+		return $ee_routes;
305
+	}
306
+
307
+
308
+
309
+	/**
310
+	 * Saves the EE REST API route data to a wp option and returns it
311
+	 *
312
+	 * @param string  $version
313
+	 * @param boolean $hidden_endpoints
314
+	 * @return mixed|null
315
+	 */
316
+	protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
317
+	{
318
+		$instance = self::instance();
319
+		$routes = apply_filters(
320
+			'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
321
+			array_replace_recursive(
322
+				$instance->_get_config_route_data_for_version($version, $hidden_endpoints),
323
+				$instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
324
+				$instance->_get_model_route_data_for_version($version, $hidden_endpoints),
325
+				$instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
326
+			)
327
+		);
328
+		$option_name = self::saved_routes_option_names . $version;
329
+		if (get_option($option_name)) {
330
+			update_option($option_name, $routes, true);
331
+		} else {
332
+			add_option($option_name, $routes, null, 'no');
333
+		}
334
+		return $routes;
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * Calculates all the EE routes and saves it to a WordPress option so we don't
341
+	 * need to calculate it on every request
342
+	 *
343
+	 * @deprecated since version 4.9.1
344
+	 * @return void
345
+	 */
346
+	public static function save_ee_routes()
347
+	{
348
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
349
+			$instance = self::instance();
350
+			$routes = apply_filters(
351
+				'EED_Core_Rest_Api__save_ee_routes__routes',
352
+				array_replace_recursive(
353
+					$instance->_register_config_routes(),
354
+					$instance->_register_meta_routes(),
355
+					$instance->_register_model_routes(),
356
+					$instance->_register_rpc_routes()
357
+				)
358
+			);
359
+			update_option(self::saved_routes_option_names, $routes, true);
360
+		}
361
+	}
362
+
363
+
364
+
365
+	/**
366
+	 * Gets all the route information relating to EE models
367
+	 *
368
+	 * @return array @see get_ee_route_data
369
+	 * @deprecated since version 4.9.1
370
+	 */
371
+	protected function _register_model_routes()
372
+	{
373
+		$model_routes = array();
374
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
375
+			$model_routes[EED_Core_Rest_Api::ee_api_namespace
376
+						  . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
377
+		}
378
+		return $model_routes;
379
+	}
380
+
381
+
382
+
383
+	/**
384
+	 * Decides whether or not to add write endpoints for this model.
385
+	 *
386
+	 * Currently, this defaults to exclude all global tables and models
387
+	 * which would allow inserting WP core data (we don't want to duplicate
388
+	 * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
389
+	 * @param EEM_Base $model
390
+	 * @return bool
391
+	 */
392
+	public static function should_have_write_endpoints(EEM_Base $model)
393
+	{
394
+		if ($model->is_wp_core_model()){
395
+			return false;
396
+		}
397
+		foreach($model->get_tables() as $table){
398
+			if( $table->is_global()){
399
+				return false;
400
+			}
401
+		}
402
+		return true;
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
409
+	 * in this versioned namespace of EE4
410
+	 * @param $version
411
+	 * @return array keys are model names (eg 'Event') and values ar etheir classnames (eg 'EEM_Event')
412
+	 */
413
+	public static function model_names_with_plural_routes($version){
414
+		$model_version_info = new ModelVersionInfo($version);
415
+		$models_to_register = $model_version_info->modelsForRequestedVersion();
416
+		//let's not bother having endpoints for extra metas
417
+		unset($models_to_register['Extra_Meta']);
418
+		unset($models_to_register['Extra_Join']);
419
+		unset($models_to_register['Post_Meta']);
420
+		return apply_filters(
421
+			'FHEE__EED_Core_REST_API___register_model_routes',
422
+			$models_to_register
423
+		);
424
+	}
425
+
426
+
427
+
428
+	/**
429
+	 * Gets the route data for EE models in the specified version
430
+	 *
431
+	 * @param string  $version
432
+	 * @param boolean $hidden_endpoint
433
+	 * @return array
434
+	 */
435
+	protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
436
+	{
437
+		$model_routes = array();
438
+		$model_version_info = new ModelVersionInfo($version);
439
+		foreach ($this->model_names_with_plural_routes($version) as $model_name => $model_classname) {
440
+			$model = \EE_Registry::instance()->load_model($model_name);
441
+			//if this isn't a valid model then let's skip iterate to the next item in the loop.
442
+			if (! $model instanceof EEM_Base) {
443
+				continue;
444
+			}
445
+			//yes we could just register one route for ALL models, but then they wouldn't show up in the index
446
+			$plural_model_route = EED_Core_Rest_Api::get_plural_route_to($model_name);
447
+			$singular_model_route = EED_Core_Rest_Api::get_singular_route_to($model_name, '(?P<id>[^\/]+)');
448
+			$model_routes[$plural_model_route] = array(
449
+				array(
450
+					'callback'        => array(
451
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
452
+						'handleRequestGetAll',
453
+					),
454
+					'callback_args'   => array($version, $model_name),
455
+					'methods'         => WP_REST_Server::READABLE,
456
+					'hidden_endpoint' => $hidden_endpoint,
457
+					'args'            => $this->_get_read_query_params($model, $version),
458
+					'_links'          => array(
459
+						'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
460
+					),
461
+				),
462
+				'schema' => array(
463
+					'schema_callback' => array(
464
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
465
+						'handleSchemaRequest',
466
+					),
467
+					'callback_args'   => array($version, $model_name),
468
+				),
469
+			);
470
+			$model_routes[$singular_model_route] = array(
471
+				array(
472
+					'callback'        => array(
473
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
474
+						'handleRequestGetOne',
475
+					),
476
+					'callback_args'   => array($version, $model_name),
477
+					'methods'         => WP_REST_Server::READABLE,
478
+					'hidden_endpoint' => $hidden_endpoint,
479
+					'args'            => $this->_get_response_selection_query_params($model, $version),
480
+				),
481
+			);
482
+			if( apply_filters(
483
+				'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
484
+				$this->should_have_write_endpoints($model),
485
+				$model
486
+			)){
487
+				$model_routes[$plural_model_route][] = array(
488
+					'callback'        => array(
489
+						'EventEspresso\core\libraries\rest_api\controllers\model\Write',
490
+						'handleRequestInsert',
491
+					),
492
+					'callback_args'   => array($version, $model_name),
493
+					'methods'         => WP_REST_Server::CREATABLE,
494
+					'hidden_endpoint' => $hidden_endpoint,
495
+					'args'            => $this->_get_write_params($model_name, $model_version_info, true),
496
+				);
497
+				$model_routes[$singular_model_route] = array_merge(
498
+					$model_routes[$singular_model_route],
499
+					array(
500
+						array(
501
+							'callback'        => array(
502
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
503
+								'handleRequestUpdate',
504
+							),
505
+							'callback_args'   => array($version, $model_name),
506
+							'methods'         => WP_REST_Server::EDITABLE,
507
+							'hidden_endpoint' => $hidden_endpoint,
508
+							'args'            => $this->_get_write_params($model_name, $model_version_info, false),
509
+						),
510
+						array(
511
+							'callback'        => array(
512
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
513
+								'handleRequestDelete',
514
+							),
515
+							'callback_args'   => array($version, $model_name),
516
+							'methods'         => WP_REST_Server::DELETABLE,
517
+							'hidden_endpoint' => $hidden_endpoint,
518
+							'args'            => $this->_get_delete_query_params($model, $version),
519
+						)
520
+					)
521
+				);
522
+			}
523
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
524
+
525
+				$related_route = EED_Core_Rest_Api::get_related_route_to(
526
+					$model_name,
527
+					'(?P<id>[^\/]+)',
528
+					$relation_obj
529
+				);
530
+				$endpoints = array(
531
+					array(
532
+						'callback'        => array(
533
+							'EventEspresso\core\libraries\rest_api\controllers\model\Read',
534
+							'handleRequestGetRelated',
535
+						),
536
+						'callback_args'   => array($version, $model_name, $relation_name),
537
+						'methods'         => WP_REST_Server::READABLE,
538
+						'hidden_endpoint' => $hidden_endpoint,
539
+						'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
540
+					),
541
+				);
542
+				$model_routes[$related_route] = $endpoints;
543
+			}
544
+		}
545
+		return $model_routes;
546
+	}
547
+
548
+
549
+
550
+	/**
551
+	 * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
552
+	 * excluding the preceding slash.
553
+	 * Eg you pass get_plural_route_to('Event') = 'events'
554
+	 * @param string $model_name eg Event or Venue
555
+	 * @return string
556
+	 */
557
+	public static function get_plural_route_to($model_name)
558
+	{
559
+		return EEH_Inflector::pluralize_and_lower($model_name);
560
+	}
561
+
562
+
563
+
564
+	/**
565
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
566
+	 * excluding the preceding slash.
567
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
568
+	 * @param string $model_name eg Event or Venue
569
+	 * @param string $id
570
+	 * @return string
571
+	 */
572
+	public static function get_singular_route_to($model_name, $id)
573
+	{
574
+		return EEH_Inflector::pluralize_and_lower($model_name) . '/' . $id;
575
+	}
576
+
577
+
578
+	/**
579
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
580
+	 * excluding the preceding slash.
581
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
582
+	 *
583
+	 * @param string                $model_name eg Event or Venue
584
+	 * @param string                $id
585
+	 * @param EE_Model_Relation_Base $relation_obj
586
+	 * @return string
587
+	 */
588
+	public static function get_related_route_to($model_name, $id, $relation_obj)
589
+	{
590
+		$related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
591
+			$relation_obj->get_other_model()->get_this_model_name(),
592
+			$relation_obj
593
+		);
594
+		return EED_Core_Rest_Api::get_singular_route_to($model_name, $id) . '/' . $related_model_name_endpoint_part;
595
+	}
596
+
597
+
598
+
599
+	/**
600
+	 * Adds onto the $relative_route the EE4 REST API versioned namespace.
601
+	 * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
602
+	 * @param string $relative_route
603
+	 * @param string $version
604
+	 * @return string
605
+	 */
606
+	public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
607
+		return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
608
+	}
609
+
610
+
611
+
612
+	/**
613
+	 * Adds all the RPC-style routes (remote procedure call-like routes, ie
614
+	 * routes that don't conform to the traditional REST CRUD-style).
615
+	 *
616
+	 * @deprecated since 4.9.1
617
+	 */
618
+	protected function _register_rpc_routes()
619
+	{
620
+		$routes = array();
621
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
622
+			$routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
623
+				$version,
624
+				$hidden_endpoint
625
+			);
626
+		}
627
+		return $routes;
628
+	}
629
+
630
+
631
+
632
+	/**
633
+	 * @param string  $version
634
+	 * @param boolean $hidden_endpoint
635
+	 * @return array
636
+	 */
637
+	protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
638
+	{
639
+		$this_versions_routes = array();
640
+		//checkin endpoint
641
+		$this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
642
+			array(
643
+				'callback'        => array(
644
+					'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
645
+					'handleRequestToggleCheckin',
646
+				),
647
+				'methods'         => WP_REST_Server::CREATABLE,
648
+				'hidden_endpoint' => $hidden_endpoint,
649
+				'args'            => array(
650
+					'force' => array(
651
+						'required'    => false,
652
+						'default'     => false,
653
+						'description' => __(
654
+							// @codingStandardsIgnoreStart
655
+							'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
656
+							// @codingStandardsIgnoreEnd
657
+							'event_espresso'
658
+						),
659
+					),
660
+				),
661
+				'callback_args'   => array($version),
662
+			),
663
+		);
664
+		return apply_filters(
665
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
666
+			$this_versions_routes,
667
+			$version,
668
+			$hidden_endpoint
669
+		);
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Gets the query params that can be used when request one or many
676
+	 *
677
+	 * @param EEM_Base $model
678
+	 * @param string   $version
679
+	 * @return array
680
+	 */
681
+	protected function _get_response_selection_query_params(\EEM_Base $model, $version)
682
+	{
683
+		return apply_filters(
684
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
685
+			array(
686
+				'include'   => array(
687
+					'required' => false,
688
+					'default'  => '*',
689
+					'type'     => 'string',
690
+				),
691
+				'calculate' => array(
692
+					'required'          => false,
693
+					'default'           => '',
694
+					'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
695
+					'type'              => 'string',
696
+					//because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
697
+					//freaks out. We'll just validate this argument while handling the request
698
+					'validate_callback' => null,
699
+					'sanitize_callback' => null,
700
+				),
701
+			),
702
+			$model,
703
+			$version
704
+		);
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * Gets the parameters acceptable for delete requests
711
+	 *
712
+	 * @param \EEM_Base $model
713
+	 * @param string    $version
714
+	 * @return array
715
+	 */
716
+	protected function _get_delete_query_params(\EEM_Base $model, $version)
717
+	{
718
+		$params_for_delete = array(
719
+			'allow_blocking' => array(
720
+				'required' => false,
721
+				'default'  => true,
722
+				'type'     => 'boolean',
723
+			),
724
+		);
725
+		$params_for_delete['force'] = array(
726
+			'required' => false,
727
+			'default'  => false,
728
+			'type'     => 'boolean',
729
+		);
730
+		return apply_filters(
731
+			'FHEE__EED_Core_Rest_Api___get_delete_query_params',
732
+			$params_for_delete,
733
+			$model,
734
+			$version
735
+		);
736
+	}
737
+
738
+
739
+
740
+	/**
741
+	 * Gets info about reading query params that are acceptable
742
+	 *
743
+	 * @param \EEM_Base $model eg 'Event' or 'Venue'
744
+	 * @param  string   $version
745
+	 * @return array    describing the args acceptable when querying this model
746
+	 * @throws \EE_Error
747
+	 */
748
+	protected function _get_read_query_params(\EEM_Base $model, $version)
749
+	{
750
+		$default_orderby = array();
751
+		foreach ($model->get_combined_primary_key_fields() as $key_field) {
752
+			$default_orderby[$key_field->get_name()] = 'ASC';
753
+		}
754
+		return array_merge(
755
+			$this->_get_response_selection_query_params($model, $version),
756
+			array(
757
+				'where'    => array(
758
+					'required' => false,
759
+					'default'  => array(),
760
+					'type'     => 'object',
761
+				),
762
+				'limit'    => array(
763
+					'required' => false,
764
+					'default'  => EED_Core_Rest_Api::get_default_query_limit(),
765
+					'type'     => array(
766
+						'object',
767
+						'string',
768
+						'integer',
769
+					),
770
+				),
771
+				'order_by' => array(
772
+					'required' => false,
773
+					'default'  => $default_orderby,
774
+					'type'     => array(
775
+						'object',
776
+						'string',
777
+					),
778
+				),
779
+				'group_by' => array(
780
+					'required' => false,
781
+					'default'  => null,
782
+					'type'     => array(
783
+						'object',
784
+						'string',
785
+					),
786
+				),
787
+				'having'   => array(
788
+					'required' => false,
789
+					'default'  => null,
790
+					'type'     => 'object',
791
+				),
792
+				'caps'     => array(
793
+					'required' => false,
794
+					'default'  => EEM_Base::caps_read,
795
+					'type'     => 'string',
796
+				),
797
+			)
798
+		);
799
+	}
800
+
801
+
802
+
803
+	/**
804
+	 * Gets parameter information for a model regarding writing data
805
+	 *
806
+	 * @param string           $model_name
807
+	 * @param ModelVersionInfo $model_version_info
808
+	 * @param boolean          $create                                       whether this is for request to create (in which case we need
809
+	 *                                                                       all required params) or just to update (in which case we don't need those on every request)
810
+	 * @return array
811
+	 */
812
+	protected function _get_write_params(
813
+		$model_name,
814
+		ModelVersionInfo $model_version_info,
815
+		$create = false
816
+	) {
817
+		$model = EE_Registry::instance()->load_model($model_name);
818
+		$fields = $model_version_info->fieldsOnModelInThisVersion($model);
819
+		$args_info = array();
820
+		foreach ($fields as $field_name => $field_obj) {
821
+			if ($field_obj->is_auto_increment()) {
822
+				//totally ignore auto increment IDs
823
+				continue;
824
+			}
825
+			$arg_info = $field_obj->getSchema();
826
+			$required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
827
+			$arg_info['required'] = $required;
828
+			//remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
829
+			unset($arg_info['readonly']);
830
+			$schema_properties = $field_obj->getSchemaProperties();
831
+			if ($field_obj->getSchemaType() === 'object'
832
+				&& isset($schema_properties['raw'])
833
+			) {
834
+				//if there's a "raw" form of this argument, use those properties instead
835
+				$arg_info = array_replace(
836
+					$arg_info,
837
+					$schema_properties['raw']
838
+				);
839
+			}
840
+			$arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
841
+				$field_obj,
842
+				$field_obj->get_default_value(),
843
+				$model_version_info->requestedVersion()
844
+			);
845
+			//we do our own validation and sanitization within the controller
846
+			$arg_info['sanitize_callback'] =
847
+				array(
848
+					'EED_Core_Rest_Api',
849
+					'default_sanitize_callback',
850
+				);
851
+			$args_info[$field_name] = $arg_info;
852
+			if ($field_obj instanceof EE_Datetime_Field) {
853
+				$gmt_arg_info = $arg_info;
854
+				$gmt_arg_info['description'] = sprintf(
855
+					esc_html__(
856
+						'%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
857
+						'event_espresso'
858
+					),
859
+					$field_obj->get_nicename(),
860
+					$field_name
861
+				);
862
+				$args_info[$field_name . '_gmt'] = $gmt_arg_info;
863
+			}
864
+		}
865
+		return $args_info;
866
+	}
867
+
868
+
869
+
870
+	/**
871
+	 * Replacement for WP API's 'rest_parse_request_arg'. If the value is blank but not required, don't bother validating it.
872
+	 * Also, it uses our email validation instead of WP API's default.
873
+	 * @param                 $value
874
+	 * @param WP_REST_Request $request
875
+	 * @param                 $param
876
+	 * @return bool|true|WP_Error
877
+	 */
878
+	public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
879
+	{
880
+		$attributes = $request->get_attributes();
881
+		if (! isset($attributes['args'][$param])
882
+			|| ! is_array($attributes['args'][$param])) {
883
+			$validation_result = true;
884
+		} else {
885
+			$args = $attributes['args'][$param];
886
+			if ((
887
+					$value === ''
888
+					|| $value === null
889
+				)
890
+				&& (! isset($args['required'])
891
+					|| $args['required'] === false
892
+				)
893
+			) {
894
+				//not required and not provided? that's cool
895
+				$validation_result = true;
896
+			} elseif (isset($args['format'])
897
+				&& $args['format'] === 'email'
898
+			) {
899
+				if (! self::_validate_email($value)) {
900
+					$validation_result = new WP_Error(
901
+						'rest_invalid_param',
902
+						esc_html__('The email address is not valid or does not exist.', 'event_espresso')
903
+					);
904
+				} else {
905
+					$validation_result = true;
906
+				}
907
+			} else {
908
+				$validation_result = rest_validate_value_from_schema($value, $args, $param);
909
+			}
910
+		}
911
+		if (is_wp_error($validation_result)) {
912
+			return $validation_result;
913
+		}
914
+		return rest_sanitize_request_arg($value, $request, $param);
915
+	}
916
+
917
+
918
+
919
+	/**
920
+	 * Returns whether or not this email address is vaild. Copied from EE_Email_Valdiation_Strategy::_validate_email()
921
+	 * @param $email
922
+	 * @return bool
923
+	 */
924
+	protected static function _validate_email($email){
925
+		$validation_level = isset( EE_Registry::instance()->CFG->registration->email_validation_level )
926
+			? EE_Registry::instance()->CFG->registration->email_validation_level
927
+			: 'wp_default';
928
+		if ( ! preg_match( '/^.+\@\S+$/', $email ) ) { // \.\S+
929
+			// email not in correct {string}@{string} format
930
+			return false;
931
+		} else {
932
+			$atIndex = strrpos( $email, "@" );
933
+			$domain = substr( $email, $atIndex + 1 );
934
+			$local = substr( $email, 0, $atIndex );
935
+			$localLen = strlen( $local );
936
+			$domainLen = strlen( $domain );
937
+			if ( $localLen < 1 || $localLen > 64 ) {
938
+				// local part length exceeded
939
+				return false;
940
+			} else if ( $domainLen < 1 || $domainLen > 255 ) {
941
+				// domain part length exceeded
942
+				return false;
943
+			} else if ( $local[ 0 ] === '.' || $local[ $localLen - 1 ] === '.' ) {
944
+				// local part starts or ends with '.'
945
+				return false;
946
+			} else if ( preg_match( '/\\.\\./', $local ) ) {
947
+				// local part has two consecutive dots
948
+				return false;
949
+			} else if ( preg_match( '/\\.\\./', $domain ) ) {
950
+				// domain part has two consecutive dots
951
+				return false;
952
+			} else if ( $validation_level === 'wp_default' ) {
953
+				return is_email( $email );
954
+			} else if (
955
+				( $validation_level === 'i18n' || $validation_level === 'i18n_dns' )
956
+				// plz see http://stackoverflow.com/a/24817336 re: the following regex
957
+				&& ! preg_match(
958
+					'/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\.!#$%&\'*+-\/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\-\.\d]+)((\.([a-zA-Z\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}]){2,63})+)$/u',
959
+					$email
960
+				)
961
+			) {
962
+				return false;
963
+			}
964
+			if ( $validation_level === 'i18n_dns' ) {
965
+				if ( ! checkdnsrr( $domain, "MX" ) ) {
966
+					// domain not found in MX records
967
+					return false;
968
+				} else if ( ! checkdnsrr( $domain, "A" ) ) {
969
+					// domain not found in A records
970
+					return false;
971
+				}
972
+			}
973
+		}
974
+		// you have successfully run the gauntlet young Padawan
975
+		return true;
976
+	}
977
+
978
+
979
+
980
+	/**
981
+	 * Gets routes for the config
982
+	 *
983
+	 * @return array @see _register_model_routes
984
+	 * @deprecated since version 4.9.1
985
+	 */
986
+	protected function _register_config_routes()
987
+	{
988
+		$config_routes = array();
989
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
990
+			$config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
991
+				$version,
992
+				$hidden_endpoint
993
+			);
994
+		}
995
+		return $config_routes;
996
+	}
997
+
998
+
999
+
1000
+	/**
1001
+	 * Gets routes for the config for the specified version
1002
+	 *
1003
+	 * @param string  $version
1004
+	 * @param boolean $hidden_endpoint
1005
+	 * @return array
1006
+	 */
1007
+	protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1008
+	{
1009
+		return array(
1010
+			'config'    => array(
1011
+				array(
1012
+					'callback'        => array(
1013
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1014
+						'handleRequest',
1015
+					),
1016
+					'methods'         => WP_REST_Server::READABLE,
1017
+					'hidden_endpoint' => $hidden_endpoint,
1018
+					'callback_args'   => array($version),
1019
+				),
1020
+			),
1021
+			'site_info' => array(
1022
+				array(
1023
+					'callback'        => array(
1024
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1025
+						'handleRequestSiteInfo',
1026
+					),
1027
+					'methods'         => WP_REST_Server::READABLE,
1028
+					'hidden_endpoint' => $hidden_endpoint,
1029
+					'callback_args'   => array($version),
1030
+				),
1031
+			),
1032
+		);
1033
+	}
1034
+
1035
+
1036
+
1037
+	/**
1038
+	 * Gets the meta info routes
1039
+	 *
1040
+	 * @return array @see _register_model_routes
1041
+	 * @deprecated since version 4.9.1
1042
+	 */
1043
+	protected function _register_meta_routes()
1044
+	{
1045
+		$meta_routes = array();
1046
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1047
+			$meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1048
+				$version,
1049
+				$hidden_endpoint
1050
+			);
1051
+		}
1052
+		return $meta_routes;
1053
+	}
1054
+
1055
+
1056
+
1057
+	/**
1058
+	 * @param string  $version
1059
+	 * @param boolean $hidden_endpoint
1060
+	 * @return array
1061
+	 */
1062
+	protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1063
+	{
1064
+		return array(
1065
+			'resources' => array(
1066
+				array(
1067
+					'callback'        => array(
1068
+						'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1069
+						'handleRequestModelsMeta',
1070
+					),
1071
+					'methods'         => WP_REST_Server::READABLE,
1072
+					'hidden_endpoint' => $hidden_endpoint,
1073
+					'callback_args'   => array($version),
1074
+				),
1075
+			),
1076
+		);
1077
+	}
1078
+
1079
+
1080
+
1081
+	/**
1082
+	 * Tries to hide old 4.6 endpoints from the
1083
+	 *
1084
+	 * @param array $route_data
1085
+	 * @return array
1086
+	 */
1087
+	public static function hide_old_endpoints($route_data)
1088
+	{
1089
+		//allow API clients to override which endpoints get hidden, in case
1090
+		//they want to discover particular endpoints
1091
+		//also, we don't have access to the request so we have to just grab it from the superglobal
1092
+		$force_show_ee_namespace = ltrim(
1093
+			EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1094
+			'/'
1095
+		);
1096
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1097
+			foreach ($relative_urls as $resource_name => $endpoints) {
1098
+				foreach ($endpoints as $key => $endpoint) {
1099
+					//skip schema and other route options
1100
+					if (! is_numeric($key)) {
1101
+						continue;
1102
+					}
1103
+					//by default, hide "hidden_endpoint"s, unless the request indicates
1104
+					//to $force_show_ee_namespace, in which case only show that one
1105
+					//namespace's endpoints (and hide all others)
1106
+					if (($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1107
+						|| ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1108
+					) {
1109
+						$full_route = '/' . ltrim($namespace, '/') . '/' . ltrim($resource_name, '/');
1110
+						unset($route_data[$full_route]);
1111
+					}
1112
+				}
1113
+			}
1114
+		}
1115
+		return $route_data;
1116
+	}
1117
+
1118
+
1119
+
1120
+	/**
1121
+	 * Returns an array describing which versions of core support serving requests for.
1122
+	 * Keys are core versions' major and minor version, and values are the
1123
+	 * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1124
+	 * data by just removing a few models and fields from the responses. However, 4.15 might remove
1125
+	 * the answers table entirely, in which case it would be very difficult for
1126
+	 * it to serve 4.6-style responses.
1127
+	 * Versions of core that are missing from this array are unknowns.
1128
+	 * previous ver
1129
+	 *
1130
+	 * @return array
1131
+	 */
1132
+	public static function version_compatibilities()
1133
+	{
1134
+		return apply_filters(
1135
+			'FHEE__EED_Core_REST_API__version_compatibilities',
1136
+			array(
1137
+				'4.8.29' => '4.8.29',
1138
+				'4.8.33' => '4.8.29',
1139
+				'4.8.34' => '4.8.29',
1140
+				'4.8.36' => '4.8.29',
1141
+			)
1142
+		);
1143
+	}
1144
+
1145
+
1146
+
1147
+	/**
1148
+	 * Gets the latest API version served. Eg if there
1149
+	 * are two versions served of the API, 4.8.29 and 4.8.32, and
1150
+	 * we are on core version 4.8.34, it will return the string "4.8.32"
1151
+	 *
1152
+	 * @return string
1153
+	 */
1154
+	public static function latest_rest_api_version()
1155
+	{
1156
+		$versions_served = \EED_Core_Rest_Api::versions_served();
1157
+		$versions_served_keys = array_keys($versions_served);
1158
+		return end($versions_served_keys);
1159
+	}
1160
+
1161
+
1162
+
1163
+	/**
1164
+	 * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1165
+	 * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1166
+	 * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1167
+	 * We also indicate whether or not this version should be put in the index or not
1168
+	 *
1169
+	 * @return array keys are API version numbers (just major and minor numbers), and values
1170
+	 * are whether or not they should be hidden
1171
+	 */
1172
+	public static function versions_served()
1173
+	{
1174
+		$versions_served = array();
1175
+		$possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1176
+		$lowest_compatible_version = end($possibly_served_versions);
1177
+		reset($possibly_served_versions);
1178
+		$versions_served_historically = array_keys($possibly_served_versions);
1179
+		$latest_version = end($versions_served_historically);
1180
+		reset($versions_served_historically);
1181
+		//for each version of core we have ever served:
1182
+		foreach ($versions_served_historically as $key_versioned_endpoint) {
1183
+			//if it's not above the current core version, and it's compatible with the current version of core
1184
+			if ($key_versioned_endpoint == $latest_version) {
1185
+				//don't hide the latest version in the index
1186
+				$versions_served[$key_versioned_endpoint] = false;
1187
+			} elseif ($key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1188
+				&& $key_versioned_endpoint >= $lowest_compatible_version
1189
+			) {
1190
+				//include, but hide, previous versions which are still supported
1191
+				$versions_served[$key_versioned_endpoint] = true;
1192
+			} elseif (apply_filters(
1193
+				'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1194
+				false,
1195
+				$possibly_served_versions
1196
+			)) {
1197
+				//if a version is no longer supported, don't include it in index or list of versions served
1198
+				$versions_served[$key_versioned_endpoint] = true;
1199
+			}
1200
+		}
1201
+		return $versions_served;
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Gets the major and minor version of EE core's version string
1208
+	 *
1209
+	 * @return string
1210
+	 */
1211
+	public static function core_version()
1212
+	{
1213
+		return apply_filters(
1214
+			'FHEE__EED_Core_REST_API__core_version',
1215
+			implode(
1216
+				'.',
1217
+				array_slice(
1218
+					explode(
1219
+						'.',
1220
+						espresso_version()
1221
+					),
1222
+				0,
1223
+				3
1224
+				)
1225
+			)
1226
+		);
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * Gets the default limit that should be used when querying for resources
1233
+	 *
1234
+	 * @return int
1235
+	 */
1236
+	public static function get_default_query_limit()
1237
+	{
1238
+		//we actually don't use a const because we want folks to always use
1239
+		//this method, not the const directly
1240
+		return apply_filters(
1241
+			'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1242
+			50
1243
+		);
1244
+	}
1245
+
1246
+
1247
+
1248
+	/**
1249
+	 *    run - initial module setup
1250
+	 *
1251
+	 * @access    public
1252
+	 * @param  WP $WP
1253
+	 * @return    void
1254
+	 */
1255
+	public function run($WP)
1256
+	{
1257
+	}
1258 1258
 }
1259 1259
 
1260 1260
 // End of file EED_Core_Rest_Api.module.php
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
      */
120 120
     protected static function _set_hooks_for_changes()
121 121
     {
122
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
122
+        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES.'rest_api'.DS.'changes'), false);
123 123
         foreach ($folder_contents as $classname_in_namespace => $filepath) {
124 124
             //ignore the base parent class
125 125
             //and legacy named classes
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
             ) {
129 129
                 continue;
130 130
             }
131
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
131
+            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\'.$classname_in_namespace;
132 132
             if (class_exists($full_classname)) {
133 133
                 $instance_of_class = new $full_classname;
134 134
                 if ($instance_of_class instanceof ChangesInBase) {
@@ -172,10 +172,10 @@  discard block
 block discarded – undo
172 172
                      * }
173 173
                      */
174 174
                     //skip route options
175
-                    if (! is_numeric($endpoint_key)) {
175
+                    if ( ! is_numeric($endpoint_key)) {
176 176
                         continue;
177 177
                     }
178
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
178
+                    if ( ! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
179 179
                         throw new EE_Error(
180 180
                             esc_html__(
181 181
                                 // @codingStandardsIgnoreStart
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
                     }
196 196
                     if (isset($data_for_single_endpoint['callback_args'])) {
197 197
                         $callback_args = $data_for_single_endpoint['callback_args'];
198
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
198
+                        $single_endpoint_args['callback'] = function(\WP_REST_Request $request) use (
199 199
                             $callback,
200 200
                             $callback_args
201 201
                         ) {
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
                     $schema_route_data = $data_for_multiple_endpoints['schema'];
215 215
                     $schema_callback = $schema_route_data['schema_callback'];
216 216
                     $callback_args = $schema_route_data['callback_args'];
217
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
217
+                    $multiple_endpoint_args['schema'] = function() use ($schema_callback, $callback_args) {
218 218
                         return call_user_func_array(
219 219
                             $schema_callback,
220 220
                             $callback_args
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
     {
259 259
         //delete the saved EE REST API routes
260 260
         foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
261
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
261
+            delete_option(EED_Core_Rest_Api::saved_routes_option_names.$version);
262 262
         }
263 263
     }
264 264
 
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
     {
278 278
         $ee_routes = array();
279 279
         foreach (self::versions_served() as $version => $hidden_endpoints) {
280
-            $ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
280
+            $ee_routes[self::ee_api_namespace.$version] = self::_get_ee_route_data_for_version(
281 281
                 $version,
282 282
                 $hidden_endpoints
283 283
             );
@@ -297,8 +297,8 @@  discard block
 block discarded – undo
297 297
      */
298 298
     protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
299 299
     {
300
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
301
-        if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
300
+        $ee_routes = get_option(self::saved_routes_option_names.$version, null);
301
+        if ( ! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
302 302
             $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
303 303
         }
304 304
         return $ee_routes;
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
                 $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
326 326
             )
327 327
         );
328
-        $option_name = self::saved_routes_option_names . $version;
328
+        $option_name = self::saved_routes_option_names.$version;
329 329
         if (get_option($option_name)) {
330 330
             update_option($option_name, $routes, true);
331 331
         } else {
@@ -391,11 +391,11 @@  discard block
 block discarded – undo
391 391
      */
392 392
     public static function should_have_write_endpoints(EEM_Base $model)
393 393
     {
394
-        if ($model->is_wp_core_model()){
394
+        if ($model->is_wp_core_model()) {
395 395
             return false;
396 396
         }
397
-        foreach($model->get_tables() as $table){
398
-            if( $table->is_global()){
397
+        foreach ($model->get_tables() as $table) {
398
+            if ($table->is_global()) {
399 399
                 return false;
400 400
             }
401 401
         }
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
      * @param $version
411 411
      * @return array keys are model names (eg 'Event') and values ar etheir classnames (eg 'EEM_Event')
412 412
      */
413
-    public static function model_names_with_plural_routes($version){
413
+    public static function model_names_with_plural_routes($version) {
414 414
         $model_version_info = new ModelVersionInfo($version);
415 415
         $models_to_register = $model_version_info->modelsForRequestedVersion();
416 416
         //let's not bother having endpoints for extra metas
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
         foreach ($this->model_names_with_plural_routes($version) as $model_name => $model_classname) {
440 440
             $model = \EE_Registry::instance()->load_model($model_name);
441 441
             //if this isn't a valid model then let's skip iterate to the next item in the loop.
442
-            if (! $model instanceof EEM_Base) {
442
+            if ( ! $model instanceof EEM_Base) {
443 443
                 continue;
444 444
             }
445 445
             //yes we could just register one route for ALL models, but then they wouldn't show up in the index
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
                     'hidden_endpoint' => $hidden_endpoint,
457 457
                     'args'            => $this->_get_read_query_params($model, $version),
458 458
                     '_links'          => array(
459
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
459
+                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace.$version.$singular_model_route),
460 460
                     ),
461 461
                 ),
462 462
                 'schema' => array(
@@ -479,11 +479,11 @@  discard block
 block discarded – undo
479 479
                     'args'            => $this->_get_response_selection_query_params($model, $version),
480 480
                 ),
481 481
             );
482
-            if( apply_filters(
482
+            if (apply_filters(
483 483
                 'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
484 484
                 $this->should_have_write_endpoints($model),
485 485
                 $model
486
-            )){
486
+            )) {
487 487
                 $model_routes[$plural_model_route][] = array(
488 488
                     'callback'        => array(
489 489
                         'EventEspresso\core\libraries\rest_api\controllers\model\Write',
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
      */
572 572
     public static function get_singular_route_to($model_name, $id)
573 573
     {
574
-        return EEH_Inflector::pluralize_and_lower($model_name) . '/' . $id;
574
+        return EEH_Inflector::pluralize_and_lower($model_name).'/'.$id;
575 575
     }
576 576
 
577 577
 
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
             $relation_obj->get_other_model()->get_this_model_name(),
592 592
             $relation_obj
593 593
         );
594
-        return EED_Core_Rest_Api::get_singular_route_to($model_name, $id) . '/' . $related_model_name_endpoint_part;
594
+        return EED_Core_Rest_Api::get_singular_route_to($model_name, $id).'/'.$related_model_name_endpoint_part;
595 595
     }
596 596
 
597 597
 
@@ -603,8 +603,8 @@  discard block
 block discarded – undo
603 603
      * @param string $version
604 604
      * @return string
605 605
      */
606
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
607
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
606
+    public static function get_versioned_route_to($relative_route, $version = '4.8.36') {
607
+        return '/'.EED_Core_Rest_Api::ee_api_namespace.$version.'/'.$relative_route;
608 608
     }
609 609
 
610 610
 
@@ -619,7 +619,7 @@  discard block
 block discarded – undo
619 619
     {
620 620
         $routes = array();
621 621
         foreach (self::versions_served() as $version => $hidden_endpoint) {
622
-            $routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
622
+            $routes[self::ee_api_namespace.$version] = $this->_get_rpc_route_data_for_version(
623 623
                 $version,
624 624
                 $hidden_endpoint
625 625
             );
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
                     $field_obj->get_nicename(),
860 860
                     $field_name
861 861
                 );
862
-                $args_info[$field_name . '_gmt'] = $gmt_arg_info;
862
+                $args_info[$field_name.'_gmt'] = $gmt_arg_info;
863 863
             }
864 864
         }
865 865
         return $args_info;
@@ -875,10 +875,10 @@  discard block
 block discarded – undo
875 875
      * @param                 $param
876 876
      * @return bool|true|WP_Error
877 877
      */
878
-    public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
878
+    public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
879 879
     {
880 880
         $attributes = $request->get_attributes();
881
-        if (! isset($attributes['args'][$param])
881
+        if ( ! isset($attributes['args'][$param])
882 882
             || ! is_array($attributes['args'][$param])) {
883 883
             $validation_result = true;
884 884
         } else {
@@ -887,7 +887,7 @@  discard block
 block discarded – undo
887 887
                     $value === ''
888 888
                     || $value === null
889 889
                 )
890
-                && (! isset($args['required'])
890
+                && ( ! isset($args['required'])
891 891
                     || $args['required'] === false
892 892
                 )
893 893
             ) {
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
             } elseif (isset($args['format'])
897 897
                 && $args['format'] === 'email'
898 898
             ) {
899
-                if (! self::_validate_email($value)) {
899
+                if ( ! self::_validate_email($value)) {
900 900
                     $validation_result = new WP_Error(
901 901
                         'rest_invalid_param',
902 902
                         esc_html__('The email address is not valid or does not exist.', 'event_espresso')
@@ -921,38 +921,38 @@  discard block
 block discarded – undo
921 921
      * @param $email
922 922
      * @return bool
923 923
      */
924
-    protected static function _validate_email($email){
925
-        $validation_level = isset( EE_Registry::instance()->CFG->registration->email_validation_level )
924
+    protected static function _validate_email($email) {
925
+        $validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
926 926
             ? EE_Registry::instance()->CFG->registration->email_validation_level
927 927
             : 'wp_default';
928
-        if ( ! preg_match( '/^.+\@\S+$/', $email ) ) { // \.\S+
928
+        if ( ! preg_match('/^.+\@\S+$/', $email)) { // \.\S+
929 929
             // email not in correct {string}@{string} format
930 930
             return false;
931 931
         } else {
932
-            $atIndex = strrpos( $email, "@" );
933
-            $domain = substr( $email, $atIndex + 1 );
934
-            $local = substr( $email, 0, $atIndex );
935
-            $localLen = strlen( $local );
936
-            $domainLen = strlen( $domain );
937
-            if ( $localLen < 1 || $localLen > 64 ) {
932
+            $atIndex = strrpos($email, "@");
933
+            $domain = substr($email, $atIndex + 1);
934
+            $local = substr($email, 0, $atIndex);
935
+            $localLen = strlen($local);
936
+            $domainLen = strlen($domain);
937
+            if ($localLen < 1 || $localLen > 64) {
938 938
                 // local part length exceeded
939 939
                 return false;
940
-            } else if ( $domainLen < 1 || $domainLen > 255 ) {
940
+            } else if ($domainLen < 1 || $domainLen > 255) {
941 941
                 // domain part length exceeded
942 942
                 return false;
943
-            } else if ( $local[ 0 ] === '.' || $local[ $localLen - 1 ] === '.' ) {
943
+            } else if ($local[0] === '.' || $local[$localLen - 1] === '.') {
944 944
                 // local part starts or ends with '.'
945 945
                 return false;
946
-            } else if ( preg_match( '/\\.\\./', $local ) ) {
946
+            } else if (preg_match('/\\.\\./', $local)) {
947 947
                 // local part has two consecutive dots
948 948
                 return false;
949
-            } else if ( preg_match( '/\\.\\./', $domain ) ) {
949
+            } else if (preg_match('/\\.\\./', $domain)) {
950 950
                 // domain part has two consecutive dots
951 951
                 return false;
952
-            } else if ( $validation_level === 'wp_default' ) {
953
-                return is_email( $email );
952
+            } else if ($validation_level === 'wp_default') {
953
+                return is_email($email);
954 954
             } else if (
955
-                ( $validation_level === 'i18n' || $validation_level === 'i18n_dns' )
955
+                ($validation_level === 'i18n' || $validation_level === 'i18n_dns')
956 956
                 // plz see http://stackoverflow.com/a/24817336 re: the following regex
957 957
                 && ! preg_match(
958 958
                     '/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\.!#$%&\'*+-\/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\-\.\d]+)((\.([a-zA-Z\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}]){2,63})+)$/u',
@@ -961,11 +961,11 @@  discard block
 block discarded – undo
961 961
             ) {
962 962
                 return false;
963 963
             }
964
-            if ( $validation_level === 'i18n_dns' ) {
965
-                if ( ! checkdnsrr( $domain, "MX" ) ) {
964
+            if ($validation_level === 'i18n_dns') {
965
+                if ( ! checkdnsrr($domain, "MX")) {
966 966
                     // domain not found in MX records
967 967
                     return false;
968
-                } else if ( ! checkdnsrr( $domain, "A" ) ) {
968
+                } else if ( ! checkdnsrr($domain, "A")) {
969 969
                     // domain not found in A records
970 970
                     return false;
971 971
                 }
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
     {
988 988
         $config_routes = array();
989 989
         foreach (self::versions_served() as $version => $hidden_endpoint) {
990
-            $config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
990
+            $config_routes[self::ee_api_namespace.$version] = $this->_get_config_route_data_for_version(
991 991
                 $version,
992 992
                 $hidden_endpoint
993 993
             );
@@ -1044,7 +1044,7 @@  discard block
 block discarded – undo
1044 1044
     {
1045 1045
         $meta_routes = array();
1046 1046
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1047
-            $meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1047
+            $meta_routes[self::ee_api_namespace.$version] = $this->_get_meta_route_data_for_version(
1048 1048
                 $version,
1049 1049
                 $hidden_endpoint
1050 1050
             );
@@ -1097,7 +1097,7 @@  discard block
 block discarded – undo
1097 1097
             foreach ($relative_urls as $resource_name => $endpoints) {
1098 1098
                 foreach ($endpoints as $key => $endpoint) {
1099 1099
                     //skip schema and other route options
1100
-                    if (! is_numeric($key)) {
1100
+                    if ( ! is_numeric($key)) {
1101 1101
                         continue;
1102 1102
                     }
1103 1103
                     //by default, hide "hidden_endpoint"s, unless the request indicates
@@ -1106,7 +1106,7 @@  discard block
 block discarded – undo
1106 1106
                     if (($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1107 1107
                         || ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1108 1108
                     ) {
1109
-                        $full_route = '/' . ltrim($namespace, '/') . '/' . ltrim($resource_name, '/');
1109
+                        $full_route = '/'.ltrim($namespace, '/').'/'.ltrim($resource_name, '/');
1110 1110
                         unset($route_data[$full_route]);
1111 1111
                     }
1112 1112
                 }
Please login to merge, or discard this patch.
core/db_models/EEM_Currency_Payment_Method.model.php 1 patch
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (!defined('EVENT_ESPRESSO_VERSION'))
3
+if ( ! defined('EVENT_ESPRESSO_VERSION'))
4 4
 	exit('No direct script access allowed');
5 5
 
6 6
 /**
@@ -25,22 +25,22 @@  discard block
 block discarded – undo
25 25
  *
26 26
  * ------------------------------------------------------------------------
27 27
  */
28
-class EEM_Currency_Payment_Method extends EEM_Base{
28
+class EEM_Currency_Payment_Method extends EEM_Base {
29 29
 	// private instance of the Attendee object
30 30
 	protected static $_instance = NULL;
31 31
 
32 32
 
33
-	protected function __construct( $timezone = NULL ) {
34
-		$this->singular_item = __('Currency Usable by Payment Method','event_espresso');
35
-		$this->plural_item = __('Currencies Usable by Payment Methods','event_espresso');
33
+	protected function __construct($timezone = NULL) {
34
+		$this->singular_item = __('Currency Usable by Payment Method', 'event_espresso');
35
+		$this->plural_item = __('Currencies Usable by Payment Methods', 'event_espresso');
36 36
 		$this->_tables = array(
37
-			'Currency_Payment_Method'=>new EE_Primary_Table('esp_currency_payment_method','CPM_ID')
37
+			'Currency_Payment_Method'=>new EE_Primary_Table('esp_currency_payment_method', 'CPM_ID')
38 38
 		);
39 39
 		$this->_fields = array(
40 40
 			'Currency_Payment_Method'=>array(
41
-				'CPM_ID'=>new EE_Primary_Key_Int_Field('CPM_ID', __('Currency to Payment Method LInk ID','event_espresso')),
42
-				'CUR_code'=>new EE_Foreign_Key_String_Field('CUR_code', __('Currency Code','event_espresso'), false, '', 'Currency'),
43
-				'PMD_ID'=>new EE_Foreign_Key_Int_Field('PMD_ID', __('Paymetn Method ID','event_espresso'), false, 0, 'Payment_Method')
41
+				'CPM_ID'=>new EE_Primary_Key_Int_Field('CPM_ID', __('Currency to Payment Method LInk ID', 'event_espresso')),
42
+				'CUR_code'=>new EE_Foreign_Key_String_Field('CUR_code', __('Currency Code', 'event_espresso'), false, '', 'Currency'),
43
+				'PMD_ID'=>new EE_Foreign_Key_Int_Field('PMD_ID', __('Paymetn Method ID', 'event_espresso'), false, 0, 'Payment_Method')
44 44
 			)
45 45
 		);
46 46
 		$this->_model_relations = array(
@@ -48,9 +48,9 @@  discard block
 block discarded – undo
48 48
 			'Payment_Method'=>new EE_Belongs_To_Relation()
49 49
 		);
50 50
 		//this model is generally available for reading
51
-		$this->_cap_restriction_generators[ EEM_Base::caps_read ] = new EE_Restriction_Generator_Public();
51
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
52 52
 		$this->_caps_slug = 'payment_methods';
53
-		parent::__construct( $timezone );
53
+		parent::__construct($timezone);
54 54
 	}
55 55
 }
56 56
 
Please login to merge, or discard this patch.
core/db_models/EEM_Status.model.php 1 patch
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if (! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -25,291 +25,291 @@  discard block
 block discarded – undo
25 25
 class EEM_Status extends EEM_Base
26 26
 {
27 27
 
28
-    // private instance of the Attendee object
29
-    protected static $_instance = null;
28
+	// private instance of the Attendee object
29
+	protected static $_instance = null;
30 30
 
31 31
 
32
-    /**
33
-     * @return EEM_Status
34
-     */
35
-    protected function __construct($timezone = null)
36
-    {
37
-        $this->singular_item    = __('Status', 'event_espresso');
38
-        $this->plural_item      = __('Stati', 'event_espresso');
39
-        $this->_tables          = array(
40
-            'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
-        );
42
-        $this->_fields          = array(
43
-            'StatusTable' => array(
44
-                'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
-                'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
-                'STS_type'     => new EE_Enum_Text_Field(
47
-                    'STS_type',
48
-                    __("Type", "event_espresso"),
49
-                    false,
50
-                    'event',
51
-                    array(
52
-                        'event'        => __("Event", "event_espresso"),//deprecated
53
-                        'registration' => __("Registration", "event_espresso"),
54
-                        'transaction'  => __("Transaction", "event_espresso"),
55
-                        'payment'      => __("Payment", "event_espresso"),
56
-                        'email'        => __("Email", "event_espresso"),
57
-                        'message'      => __("Message", "event_espresso"),
58
-                    )),
59
-                'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false, false),
60
-                'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
-                'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
-            ),
63
-        );
64
-        $this->_model_relations = array(
65
-            'Registration' => new EE_Has_Many_Relation(),
66
-            'Transaction'  => new EE_Has_Many_Relation(),
67
-            'Payment'      => new EE_Has_Many_Relation(),
68
-        );
69
-        //this model is generally available for reading
70
-        $this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
32
+	/**
33
+	 * @return EEM_Status
34
+	 */
35
+	protected function __construct($timezone = null)
36
+	{
37
+		$this->singular_item    = __('Status', 'event_espresso');
38
+		$this->plural_item      = __('Stati', 'event_espresso');
39
+		$this->_tables          = array(
40
+			'StatusTable' => new EE_Primary_Table('esp_status', 'STS_ID'),
41
+		);
42
+		$this->_fields          = array(
43
+			'StatusTable' => array(
44
+				'STS_ID'       => new EE_Primary_Key_String_Field('STS_ID', __('Status ID', 'event_espresso')),
45
+				'STS_code'     => new EE_Plain_Text_Field('STS_code', __('Status Code', 'event_espresso'), false, ''),
46
+				'STS_type'     => new EE_Enum_Text_Field(
47
+					'STS_type',
48
+					__("Type", "event_espresso"),
49
+					false,
50
+					'event',
51
+					array(
52
+						'event'        => __("Event", "event_espresso"),//deprecated
53
+						'registration' => __("Registration", "event_espresso"),
54
+						'transaction'  => __("Transaction", "event_espresso"),
55
+						'payment'      => __("Payment", "event_espresso"),
56
+						'email'        => __("Email", "event_espresso"),
57
+						'message'      => __("Message", "event_espresso"),
58
+					)),
59
+				'STS_can_edit' => new EE_Boolean_Field('STS_can_edit', __('Editable?', 'event_espresso'), false, false),
60
+				'STS_desc'     => new EE_Simple_HTML_Field('STS_desc', __("Description", "event_espresso"), false, ''),
61
+				'STS_open'     => new EE_Boolean_Field('STS_open', __("Open?", "event_espresso"), false, false),
62
+			),
63
+		);
64
+		$this->_model_relations = array(
65
+			'Registration' => new EE_Has_Many_Relation(),
66
+			'Transaction'  => new EE_Has_Many_Relation(),
67
+			'Payment'      => new EE_Has_Many_Relation(),
68
+		);
69
+		//this model is generally available for reading
70
+		$this->_cap_restriction_generators[EEM_Base::caps_read] = new EE_Restriction_Generator_Public();
71 71
 
72
-        parent::__construct($timezone);
73
-    }
72
+		parent::__construct($timezone);
73
+	}
74 74
 
75 75
 
76
-    /**
77
-     * This method provides the localized singular or plural string for a given status id
78
-     *
79
-     * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
-     *                           That way if there isn't a translation in the index we'll return the default code.
81
-     * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
-     *                           same as the singular (in English), however, this may NOT be the case with other
83
-     *                           languages
84
-     * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
-     *                           the status string returned ( UPPER, lower, Sentence)
86
-     * @throws EE_Error
87
-     * @return array             an array of translated strings for the incoming status id.
88
-     */
89
-    public function localized_status($statuses, $plural = false, $schema = 'upper')
90
-    {
91
-        //note these are all in lower case because ucwords() on upper case will NOT convert.
92
-        $translation_array = array(
93
-            EEM_Registration::status_id_pending_payment => array(
94
-                __('pending payment', 'event_espresso'), //singular
95
-                __('pending payments', 'event_espresso') //plural
96
-            ),
97
-            EEM_Registration::status_id_approved        => array(
98
-                __('approved', 'event_espresso'), //singular
99
-                __('approved', 'event_espresso') //plural
100
-            ),
101
-            EEM_Registration::status_id_not_approved    => array(
102
-                __('not approved', 'event_espresso'),
103
-                __('not approved', 'event_espresso'),
104
-            ),
105
-            EEM_Registration::status_id_cancelled       => array(
106
-                __('cancelled', 'event_espresso'),
107
-                __('cancelled', 'event_espresso'),
108
-            ),
109
-            EEM_Registration::status_id_incomplete      => array(
110
-                __('incomplete', 'event_espresso'),
111
-                __('incomplete', 'event_espresso'),
112
-            ),
113
-            EEM_Registration::status_id_declined        => array(
114
-                __('declined', 'event_espresso'),
115
-                __('declined', 'event_espresso'),
116
-            ),
117
-            EEM_Registration::status_id_wait_list       => array(
118
-                __('wait list', 'event_espresso'),
119
-                __('wait list', 'event_espresso'),
120
-            ),
121
-            EEM_Transaction::overpaid_status_code       => array(
122
-                __('overpaid', 'event_espresso'),
123
-                __('overpaid', 'event_espresso'),
124
-            ),
125
-            EEM_Transaction::complete_status_code       => array(
126
-                __('complete', 'event_espresso'),
127
-                __('complete', 'event_espresso'),
128
-            ),
129
-            EEM_Transaction::incomplete_status_code     => array(
130
-                __('incomplete', 'event_espresso'),
131
-                __('incomplete', 'event_espresso'),
132
-            ),
133
-            EEM_Transaction::failed_status_code         => array(
134
-                __('failed', 'event_espresso'),
135
-                __('failed', 'event_espresso'),
136
-            ),
137
-            EEM_Transaction::abandoned_status_code      => array(
138
-                __('abandoned', 'event_espresso'),
139
-                __('abandoned', 'event_espresso'),
140
-            ),
141
-            EEM_Payment::status_id_approved             => array(
142
-                __('accepted', 'event_espresso'),
143
-                __('accepted', 'event_espresso'),
144
-            ),
145
-            EEM_Payment::status_id_pending              => array(
146
-                __('pending', 'event_espresso'),
147
-                __('pending', 'event_espresso'),
148
-            ),
149
-            EEM_Payment::status_id_cancelled            => array(
150
-                __('cancelled', 'event_espresso'),
151
-                __('cancelled', 'event_espresso'),
152
-            ),
153
-            EEM_Payment::status_id_declined             => array(
154
-                __('declined', 'event_espresso'),
155
-                __('declined', 'event_espresso'),
156
-            ),
157
-            EEM_Payment::status_id_failed               => array(
158
-                __('failed', 'event_espresso'),
159
-                __('failed', 'event_espresso'),
160
-            ),
161
-            //following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
-            EEM_Event::sold_out                         => array(
163
-                __('sold out', 'event_espresso'),
164
-                __('sold out', 'event_espresso'),
165
-            ),
166
-            EEM_Event::postponed                        => array(
167
-                __('postponed', 'event_espresso'),
168
-                __('Postponed', 'event_espresso'),
169
-            ),
170
-            EEM_Event::cancelled                        => array(
171
-                __('cancelled', 'event_espresso'),
172
-                __('cancelled', 'event_espresso'),
173
-            ),
174
-            EE_Ticket::archived                         => array(
175
-                __('archived', 'event_espresso'),
176
-                __('archived', 'event_espresso'),
177
-            ),
178
-            EE_Ticket::expired                          => array(
179
-                __('expired', 'event_espresso'),
180
-                __('expired', 'event_espresso'),
181
-            ),
182
-            EE_Ticket::sold_out                         => array(
183
-                __('sold out', 'event_espresso'),
184
-                __('sold out', 'event_espresso'),
185
-            ),
186
-            EE_Ticket::pending                          => array(
187
-                __('upcoming', 'event_espresso'),
188
-                __('upcoming', 'event_espresso'),
189
-            ),
190
-            EE_Ticket::onsale                           => array(
191
-                __('on sale', 'event_espresso'),
192
-                __('on sale', 'event_espresso'),
193
-            ),
194
-            EE_Datetime::cancelled                      => array(
195
-                __('cancelled', 'event_espresso'),
196
-                __('cancelled', 'event_espresso'),
197
-            ),
198
-            EE_Datetime::sold_out                       => array(
199
-                __('sold out', 'event_espresso'),
200
-                __('sold out', 'event_espresso'),
201
-            ),
202
-            EE_Datetime::expired                        => array(
203
-                __('expired', 'event_espresso'),
204
-                __('expired', 'event_espresso'),
205
-            ),
206
-            EE_Datetime::inactive                       => array(
207
-                __('inactive', 'event_espresso'),
208
-                __('inactive', 'event_espresso'),
209
-            ),
210
-            EE_Datetime::upcoming                       => array(
211
-                __('upcoming', 'event_espresso'),
212
-                __('upcoming', 'event_espresso'),
213
-            ),
214
-            EE_Datetime::active                         => array(
215
-                __('active', 'event_espresso'),
216
-                __('active', 'event_espresso'),
217
-            ),
218
-            EE_Datetime::postponed                      => array(
219
-                __('postponed', 'event_espresso'),
220
-                __('postponed', 'event_espresso'),
221
-            ),
222
-            //messages related
223
-            EEM_Message::status_sent                    => array(
224
-                __('sent', 'event_espresso'),
225
-                __('sent', 'event_espresso'),
226
-            ),
227
-            EEM_Message::status_idle                    => array(
228
-                __('queued for sending', 'event_espresso'),
229
-                __('queued for sending', 'event_espresso'),
230
-            ),
231
-            EEM_Message::status_failed                  => array(
232
-                __('failed', 'event_espresso'),
233
-                __('failed', 'event_espresso'),
234
-            ),
235
-            EEM_Message::status_debug_only              => array(
236
-                __('debug only', 'event_espresso'),
237
-                __('debug only', 'event_espresso'),
238
-            ),
239
-            EEM_Message::status_messenger_executing     => array(
240
-                __('messenger is executing', 'event_espresso'),
241
-                __('messenger is executing', 'event_espresso'),
242
-            ),
243
-            EEM_Message::status_resend                  => array(
244
-                __('queued for resending', 'event_espresso'),
245
-                __('queued for resending', 'event_espresso'),
246
-            ),
247
-            EEM_Message::status_incomplete              => array(
248
-                __('queued for generating', 'event_espresso'),
249
-                __('queued for generating', 'event_espresso'),
250
-            ),
251
-            EEM_Message::status_retry                   => array(
252
-                __('failed sending, can be retried', 'event_espresso'),
253
-                __('failed sending, can be retried', 'event_espresso'),
254
-            ),
255
-            EEM_CPT_Base::post_status_publish           => array(
256
-                __('published', 'event_espresso'),
257
-                __('published', 'event_espresso'),
258
-            ),
259
-            EEM_CPT_Base::post_status_future            => array(
260
-                __('scheduled', 'event_espresso'),
261
-                __('scheduled', 'event_espresso'),
262
-            ),
263
-            EEM_CPT_Base::post_status_draft             => array(
264
-                __('draft', 'event_espresso'),
265
-                __('draft', 'event_espresso'),
266
-            ),
267
-            EEM_CPT_Base::post_status_pending           => array(
268
-                __('pending', 'event_espresso'),
269
-                __('pending', 'event_espresso'),
270
-            ),
271
-            EEM_CPT_Base::post_status_private           => array(
272
-                __('private', 'event_espresso'),
273
-                __('private', 'event_espresso'),
274
-            ),
275
-            EEM_CPT_Base::post_status_trashed           => array(
276
-                __('trashed', 'event_espresso'),
277
-                __('trashed', 'event_espresso'),
278
-            ),
279
-        );
76
+	/**
77
+	 * This method provides the localized singular or plural string for a given status id
78
+	 *
79
+	 * @param  array   $statuses This should be an array of statuses in the format array( $status_id, $status_code ).
80
+	 *                           That way if there isn't a translation in the index we'll return the default code.
81
+	 * @param  boolean $plural   Whether to return plural string or not. Note, nearly all of the plural strings are the
82
+	 *                           same as the singular (in English), however, this may NOT be the case with other
83
+	 *                           languages
84
+	 * @param  string  $schema   This can be either 'upper', 'lower', or 'sentence'.  Basically indicates how we want
85
+	 *                           the status string returned ( UPPER, lower, Sentence)
86
+	 * @throws EE_Error
87
+	 * @return array             an array of translated strings for the incoming status id.
88
+	 */
89
+	public function localized_status($statuses, $plural = false, $schema = 'upper')
90
+	{
91
+		//note these are all in lower case because ucwords() on upper case will NOT convert.
92
+		$translation_array = array(
93
+			EEM_Registration::status_id_pending_payment => array(
94
+				__('pending payment', 'event_espresso'), //singular
95
+				__('pending payments', 'event_espresso') //plural
96
+			),
97
+			EEM_Registration::status_id_approved        => array(
98
+				__('approved', 'event_espresso'), //singular
99
+				__('approved', 'event_espresso') //plural
100
+			),
101
+			EEM_Registration::status_id_not_approved    => array(
102
+				__('not approved', 'event_espresso'),
103
+				__('not approved', 'event_espresso'),
104
+			),
105
+			EEM_Registration::status_id_cancelled       => array(
106
+				__('cancelled', 'event_espresso'),
107
+				__('cancelled', 'event_espresso'),
108
+			),
109
+			EEM_Registration::status_id_incomplete      => array(
110
+				__('incomplete', 'event_espresso'),
111
+				__('incomplete', 'event_espresso'),
112
+			),
113
+			EEM_Registration::status_id_declined        => array(
114
+				__('declined', 'event_espresso'),
115
+				__('declined', 'event_espresso'),
116
+			),
117
+			EEM_Registration::status_id_wait_list       => array(
118
+				__('wait list', 'event_espresso'),
119
+				__('wait list', 'event_espresso'),
120
+			),
121
+			EEM_Transaction::overpaid_status_code       => array(
122
+				__('overpaid', 'event_espresso'),
123
+				__('overpaid', 'event_espresso'),
124
+			),
125
+			EEM_Transaction::complete_status_code       => array(
126
+				__('complete', 'event_espresso'),
127
+				__('complete', 'event_espresso'),
128
+			),
129
+			EEM_Transaction::incomplete_status_code     => array(
130
+				__('incomplete', 'event_espresso'),
131
+				__('incomplete', 'event_espresso'),
132
+			),
133
+			EEM_Transaction::failed_status_code         => array(
134
+				__('failed', 'event_espresso'),
135
+				__('failed', 'event_espresso'),
136
+			),
137
+			EEM_Transaction::abandoned_status_code      => array(
138
+				__('abandoned', 'event_espresso'),
139
+				__('abandoned', 'event_espresso'),
140
+			),
141
+			EEM_Payment::status_id_approved             => array(
142
+				__('accepted', 'event_espresso'),
143
+				__('accepted', 'event_espresso'),
144
+			),
145
+			EEM_Payment::status_id_pending              => array(
146
+				__('pending', 'event_espresso'),
147
+				__('pending', 'event_espresso'),
148
+			),
149
+			EEM_Payment::status_id_cancelled            => array(
150
+				__('cancelled', 'event_espresso'),
151
+				__('cancelled', 'event_espresso'),
152
+			),
153
+			EEM_Payment::status_id_declined             => array(
154
+				__('declined', 'event_espresso'),
155
+				__('declined', 'event_espresso'),
156
+			),
157
+			EEM_Payment::status_id_failed               => array(
158
+				__('failed', 'event_espresso'),
159
+				__('failed', 'event_espresso'),
160
+			),
161
+			//following statuses are NOT part of the EEM_Status but to keep things centralized we include in here.
162
+			EEM_Event::sold_out                         => array(
163
+				__('sold out', 'event_espresso'),
164
+				__('sold out', 'event_espresso'),
165
+			),
166
+			EEM_Event::postponed                        => array(
167
+				__('postponed', 'event_espresso'),
168
+				__('Postponed', 'event_espresso'),
169
+			),
170
+			EEM_Event::cancelled                        => array(
171
+				__('cancelled', 'event_espresso'),
172
+				__('cancelled', 'event_espresso'),
173
+			),
174
+			EE_Ticket::archived                         => array(
175
+				__('archived', 'event_espresso'),
176
+				__('archived', 'event_espresso'),
177
+			),
178
+			EE_Ticket::expired                          => array(
179
+				__('expired', 'event_espresso'),
180
+				__('expired', 'event_espresso'),
181
+			),
182
+			EE_Ticket::sold_out                         => array(
183
+				__('sold out', 'event_espresso'),
184
+				__('sold out', 'event_espresso'),
185
+			),
186
+			EE_Ticket::pending                          => array(
187
+				__('upcoming', 'event_espresso'),
188
+				__('upcoming', 'event_espresso'),
189
+			),
190
+			EE_Ticket::onsale                           => array(
191
+				__('on sale', 'event_espresso'),
192
+				__('on sale', 'event_espresso'),
193
+			),
194
+			EE_Datetime::cancelled                      => array(
195
+				__('cancelled', 'event_espresso'),
196
+				__('cancelled', 'event_espresso'),
197
+			),
198
+			EE_Datetime::sold_out                       => array(
199
+				__('sold out', 'event_espresso'),
200
+				__('sold out', 'event_espresso'),
201
+			),
202
+			EE_Datetime::expired                        => array(
203
+				__('expired', 'event_espresso'),
204
+				__('expired', 'event_espresso'),
205
+			),
206
+			EE_Datetime::inactive                       => array(
207
+				__('inactive', 'event_espresso'),
208
+				__('inactive', 'event_espresso'),
209
+			),
210
+			EE_Datetime::upcoming                       => array(
211
+				__('upcoming', 'event_espresso'),
212
+				__('upcoming', 'event_espresso'),
213
+			),
214
+			EE_Datetime::active                         => array(
215
+				__('active', 'event_espresso'),
216
+				__('active', 'event_espresso'),
217
+			),
218
+			EE_Datetime::postponed                      => array(
219
+				__('postponed', 'event_espresso'),
220
+				__('postponed', 'event_espresso'),
221
+			),
222
+			//messages related
223
+			EEM_Message::status_sent                    => array(
224
+				__('sent', 'event_espresso'),
225
+				__('sent', 'event_espresso'),
226
+			),
227
+			EEM_Message::status_idle                    => array(
228
+				__('queued for sending', 'event_espresso'),
229
+				__('queued for sending', 'event_espresso'),
230
+			),
231
+			EEM_Message::status_failed                  => array(
232
+				__('failed', 'event_espresso'),
233
+				__('failed', 'event_espresso'),
234
+			),
235
+			EEM_Message::status_debug_only              => array(
236
+				__('debug only', 'event_espresso'),
237
+				__('debug only', 'event_espresso'),
238
+			),
239
+			EEM_Message::status_messenger_executing     => array(
240
+				__('messenger is executing', 'event_espresso'),
241
+				__('messenger is executing', 'event_espresso'),
242
+			),
243
+			EEM_Message::status_resend                  => array(
244
+				__('queued for resending', 'event_espresso'),
245
+				__('queued for resending', 'event_espresso'),
246
+			),
247
+			EEM_Message::status_incomplete              => array(
248
+				__('queued for generating', 'event_espresso'),
249
+				__('queued for generating', 'event_espresso'),
250
+			),
251
+			EEM_Message::status_retry                   => array(
252
+				__('failed sending, can be retried', 'event_espresso'),
253
+				__('failed sending, can be retried', 'event_espresso'),
254
+			),
255
+			EEM_CPT_Base::post_status_publish           => array(
256
+				__('published', 'event_espresso'),
257
+				__('published', 'event_espresso'),
258
+			),
259
+			EEM_CPT_Base::post_status_future            => array(
260
+				__('scheduled', 'event_espresso'),
261
+				__('scheduled', 'event_espresso'),
262
+			),
263
+			EEM_CPT_Base::post_status_draft             => array(
264
+				__('draft', 'event_espresso'),
265
+				__('draft', 'event_espresso'),
266
+			),
267
+			EEM_CPT_Base::post_status_pending           => array(
268
+				__('pending', 'event_espresso'),
269
+				__('pending', 'event_espresso'),
270
+			),
271
+			EEM_CPT_Base::post_status_private           => array(
272
+				__('private', 'event_espresso'),
273
+				__('private', 'event_espresso'),
274
+			),
275
+			EEM_CPT_Base::post_status_trashed           => array(
276
+				__('trashed', 'event_espresso'),
277
+				__('trashed', 'event_espresso'),
278
+			),
279
+		);
280 280
 
281
-        $translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
281
+		$translation_array = apply_filters('FHEE__EEM_Status__localized_status__translation_array', $translation_array);
282 282
 
283
-        if ( ! is_array($statuses)) {
284
-            throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
-                'event_espresso'));
286
-        }
283
+		if ( ! is_array($statuses)) {
284
+			throw new EE_Error(__('The incoming statuses argument must be an array with keys as the $status_id and values as the $status_code',
285
+				'event_espresso'));
286
+		}
287 287
 
288
-        $translation = array();
288
+		$translation = array();
289 289
 
290
-        foreach ($statuses as $id => $code) {
291
-            if (isset($translation_array[$id])) {
292
-                $translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
-            } else {
294
-                $translation[$id] = $code;
295
-            }
290
+		foreach ($statuses as $id => $code) {
291
+			if (isset($translation_array[$id])) {
292
+				$translation[$id] = $plural ? $translation_array[$id][1] : $translation_array[$id][0];
293
+			} else {
294
+				$translation[$id] = $code;
295
+			}
296 296
 
297
-            //schema
298
-            switch ($schema) {
299
-                case 'lower' :
300
-                    $translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
-                    break;
302
-                case 'sentence' :
303
-                    $translation[$id] = ucwords($translation[$id]);
304
-                    break;
305
-                case 'upper' :
306
-                    $translation[$id] = strtoupper($translation[$id]);
307
-                    break;
308
-            }
309
-        }
297
+			//schema
298
+			switch ($schema) {
299
+				case 'lower' :
300
+					$translation[$id] = strtolower($translation[$id]); //even though these start in lower case, this will catch any statuses added via filter.
301
+					break;
302
+				case 'sentence' :
303
+					$translation[$id] = ucwords($translation[$id]);
304
+					break;
305
+				case 'upper' :
306
+					$translation[$id] = strtoupper($translation[$id]);
307
+					break;
308
+			}
309
+		}
310 310
 
311
-        return $translation;
312
-    }
311
+		return $translation;
312
+	}
313 313
 
314 314
 
315 315
 }
Please login to merge, or discard this patch.
core/libraries/rest_api/controllers/model/Write.php 2 patches
Indentation   +333 added lines, -333 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
 use EE_Error;
19 19
 
20 20
 if (! defined('EVENT_ESPRESSO_VERSION')) {
21
-    exit('No direct script access allowed');
21
+	exit('No direct script access allowed');
22 22
 }
23 23
 
24 24
 
@@ -36,337 +36,337 @@  discard block
 block discarded – undo
36 36
 
37 37
 
38 38
 
39
-    public function __construct()
40
-    {
41
-        parent::__construct();
42
-        EE_Registry::instance()->load_helper('Inflector');
43
-    }
44
-
45
-
46
-
47
-    /**
48
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
49
-     *
50
-     * @param WP_REST_Request $request
51
-     * @param string          $version
52
-     * @param string          $model_name
53
-     * @return WP_REST_Response|\WP_Error
54
-     */
55
-    public static function handleRequestInsert(WP_REST_Request $request, $version, $model_name)
56
-    {
57
-        $controller = new Write();
58
-        try {
59
-            $controller->setRequestedVersion($version);
60
-            return $controller->sendResponse(
61
-                $controller->insert(
62
-                    $controller->getModelVersionInfo()->loadModel($model_name),
63
-                    $request
64
-                )
65
-            );
66
-        } catch (\Exception $e) {
67
-            return $controller->sendResponse($e);
68
-        }
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * Handles a request from \WP_REST_Server to update an EE model
75
-     *
76
-     * @param WP_REST_Request $request
77
-     * @param string          $version
78
-     * @param string          $model_name
79
-     * @return WP_REST_Response|\WP_Error
80
-     */
81
-    public static function handleRequestUpdate(WP_REST_Request $request, $version, $model_name)
82
-    {
83
-        $controller = new Write();
84
-        try {
85
-            $controller->setRequestedVersion($version);
86
-            return $controller->sendResponse(
87
-                $controller->update(
88
-                    $controller->getModelVersionInfo()->loadModel($model_name),
89
-                    $request
90
-                )
91
-            );
92
-        } catch (\Exception $e) {
93
-            return $controller->sendResponse($e);
94
-        }
95
-    }
96
-
97
-
98
-
99
-    /**
100
-     * Deletes a single model object and returns it. Unless
101
-     *
102
-     * @param WP_REST_Request $request
103
-     * @param string          $version
104
-     * @param string          $model_name
105
-     * @return WP_REST_Response|\WP_Error
106
-     */
107
-    public static function handleRequestDelete(WP_REST_Request $request, $version, $model_name)
108
-    {
109
-        $controller = new Write();
110
-        try {
111
-            $controller->setRequestedVersion($version);
112
-            return $controller->sendResponse(
113
-                $controller->delete(
114
-                    $controller->getModelVersionInfo()->loadModel($model_name),
115
-                    $request
116
-                )
117
-            );
118
-        } catch (\Exception $e) {
119
-            return $controller->sendResponse($e);
120
-        }
121
-    }
122
-
123
-
124
-
125
-    /**
126
-     * Inserts a new model object according to the $request
127
-     *
128
-     * @param EEM_Base        $model
129
-     * @param WP_REST_Request $request
130
-     * @return array
131
-     * @throws EE_Error
132
-     * @throws RestException
133
-     */
134
-    public function insert(EEM_Base $model, WP_REST_Request $request)
135
-    {
136
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
137
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
138
-        if (! current_user_can($default_cap_to_check_for)) {
139
-            throw new RestException(
140
-                'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
141
-                sprintf(
142
-                    esc_html__(
143
-                        // @codingStandardsIgnoreStart
144
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to insert data into Event Espresso.',
145
-                        // @codingStandardsIgnoreEnd
146
-                        'event_espresso'
147
-                    ),
148
-                    $default_cap_to_check_for
149
-                ),
150
-                array('status' => 403)
151
-            );
152
-        }
153
-        $submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
154
-        $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
155
-            $submitted_json_data,
156
-            $model,
157
-            $this->getModelVersionInfo()->requestedVersion(),
158
-            true
159
-        );
160
-        $model_obj = EE_Registry::instance()->load_class(
161
-            $model->get_this_model_name(),
162
-            array($model_data, $model->get_timezone()),
163
-            false,
164
-            false
165
-        );
166
-        $model_obj->save();
167
-        $new_id = $model_obj->ID();
168
-        if (! $new_id) {
169
-            throw new RestException(
170
-                'rest_insertion_failed',
171
-                sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
172
-            );
173
-        }
174
-        return $this->returnModelObjAsJsonResponse($model_obj, $request);
175
-    }
176
-
177
-
178
-
179
-    /**
180
-     * Updates an existing model object according to the $request
181
-     *
182
-     * @param EEM_Base        $model
183
-     * @param WP_REST_Request $request
184
-     * @return array
185
-     * @throws EE_Error
186
-     */
187
-    public function update(EEM_Base $model, WP_REST_Request $request)
188
-    {
189
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
190
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
191
-        if (! current_user_can($default_cap_to_check_for)) {
192
-            throw new RestException(
193
-                'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
194
-                sprintf(
195
-                    esc_html__(
196
-                        // @codingStandardsIgnoreStart
197
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to update data into Event Espresso.',
198
-                        // @codingStandardsIgnoreEnd
199
-                        'event_espresso'
200
-                    ),
201
-                    $default_cap_to_check_for
202
-                ),
203
-                array('status' => 403)
204
-            );
205
-        }
206
-        $obj_id = $request->get_param('id');
207
-        if (! $obj_id) {
208
-            throw new RestException(
209
-                'rest_edit_failed',
210
-                sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
211
-            );
212
-        }
213
-        $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
214
-            $this->getBodyParams($request),
215
-            $model,
216
-            $this->getModelVersionInfo()->requestedVersion(),
217
-            true
218
-        );
219
-        $model_obj = $model->get_one_by_ID($obj_id);
220
-        $model_obj->save($model_data);
221
-        return $this->returnModelObjAsJsonResponse($model_obj, $request);
222
-    }
223
-
224
-
225
-
226
-    /**
227
-     * Updates an existing model object according to the $request
228
-     *
229
-     * @param EEM_Base        $model
230
-     * @param WP_REST_Request $request
231
-     * @return array of either the soft-deleted item, or
232
-     * @throws EE_Error
233
-     */
234
-    public function delete(EEM_Base $model, WP_REST_Request $request)
235
-    {
236
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
237
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
238
-        if (! current_user_can($default_cap_to_check_for)) {
239
-            throw new RestException(
240
-                'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
241
-                sprintf(
242
-                    esc_html__(
243
-                        // @codingStandardsIgnoreStart
244
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to delete data into Event Espresso.',
245
-                        // @codingStandardsIgnoreEnd
246
-                        'event_espresso'
247
-                    ),
248
-                    $default_cap_to_check_for
249
-                ),
250
-                array('status' => 403)
251
-            );
252
-        }
253
-        $obj_id = $request->get_param('id');
254
-        $requested_permanent_delete = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN);
255
-        $requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN);
256
-        if ($requested_permanent_delete) {
257
-            $read_controller = new Read();
258
-            $read_controller->setRequestedVersion($this->getRequestedVersion());
259
-            $simulated_get_request = new WP_REST_Request('GET', $request->get_route());
260
-            $simulated_get_request->set_url_params($request->get_url_params());
261
-            $simulated_get_request->set_query_params(
262
-                array(
263
-                    'caps' => EEM_Base::caps_delete
264
-                )
265
-            );
266
-            //not just grab the entity, but also use sendResponse to verify in case there's an error retrieving it
267
-            $original_response = $read_controller->sendResponse(
268
-                $read_controller->getOneOrReportPermissionError(
269
-                    $model,
270
-                    $simulated_get_request,
271
-                    EEM_Base::caps_delete
272
-                )
273
-            );
274
-            if ($original_response instanceof WP_REST_Response) {
275
-                $original_entity = $original_response->get_data();
276
-            } else {
277
-                $original_entity = null;
278
-            }
279
-            $deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
280
-            return array(
281
-                'deleted'  => $deleted,
282
-                'previous' => $original_entity,
283
-            );
284
-        } else {
285
-            if ($model instanceof EEM_Soft_Delete_Base) {
286
-                $model->delete_by_ID($obj_id, $requested_allow_blocking);
287
-                return $this->getOneBasedOnRequest($model, $request, $obj_id);
288
-            } else {
289
-                throw new RestException(
290
-                    'rest_trash_not_supported',
291
-                    501,
292
-                    sprintf(
293
-                        esc_html__('%1$s do not support trashing. Set force=1 to delete.', 'event_espresso'),
294
-                        EEH_Inflector::pluralize($model->get_this_model_name())
295
-                    )
296
-                );
297
-            }
298
-        }
299
-    }
300
-
301
-
302
-
303
-    /**
304
-     * Returns an array ready to be converted into a JSON response, based solely on the model object
305
-     *
306
-     * @param EE_Base_Class $model_obj
307
-     * @param WP_REST_Request $request
308
-     * @return array ready for a response
309
-     */
310
-    protected function returnModelObjAsJsonResponse(EE_Base_Class $model_obj, WP_REST_Request $request)
311
-    {
312
-        $model = $model_obj->get_model();
313
-        //create an array exactly like the wpdb results row,
314
-        // so we can pass it to controllers/model/Read::create_entity_from_wpdb_result()
315
-        $simulated_db_row = array();
316
-        foreach ($model->field_settings(true) as $field_name => $field_obj) {
317
-            //we need to reconstruct the normal wpdb results, including the db-only fields
318
-            //like a secondary table's primary key. The models expect those (but don't care what value they have)
319
-            if( $field_obj instanceof EE_DB_Only_Field_Base){
320
-                $raw_value = true;
321
-            } elseif ($field_obj instanceof EE_Datetime_Field) {
322
-                $raw_value = $model_obj->get_DateTime_object($field_name);
323
-            } else {
324
-                $raw_value = $model_obj->get_raw($field_name);
325
-            }
326
-            $simulated_db_row[$field_obj->get_qualified_column()] = $field_obj->prepare_for_use_in_db($raw_value);
327
-        }
328
-        $read_controller = new Read();
329
-        $read_controller->setRequestedVersion($this->getRequestedVersion());
330
-        //the simulates request really doesn't need any info downstream
331
-        $simulated_request = new WP_REST_Request('GET');
332
-        return $read_controller->createEntityFromWpdbResult(
333
-            $model_obj->get_model(),
334
-            $simulated_db_row,
335
-            $simulated_request
336
-        );
337
-    }
338
-
339
-
340
-
341
-    /**
342
-     * Gets the item affected by this request
343
-     *
344
-     * @param EEM_Base        $model
345
-     * @param WP_REST_Request $request
346
-     * @param  int|string     $obj_id
347
-     * @return \WP_Error|array
348
-     */
349
-    protected function getOneBasedOnRequest(EEM_Base $model, WP_REST_Request $request, $obj_id)
350
-    {
351
-        $requested_version = $this->getRequestedVersion($request->get_route());
352
-        $get_request = new WP_REST_Request(
353
-            'GET',
354
-            EED_Core_Rest_Api::ee_api_namespace
355
-            . $requested_version
356
-            . '/'
357
-            . EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
358
-            . '/'
359
-            . $obj_id
360
-        );
361
-        $get_request->set_url_params(
362
-            array(
363
-                'id'      => $obj_id,
364
-                'include' => $request->get_param('include'),
365
-            )
366
-        );
367
-        $read_controller = new Read();
368
-        $read_controller->setRequestedVersion($this->getRequestedVersion());
369
-        return $read_controller->getEntityFromModel($model, $get_request);
370
-    }
39
+	public function __construct()
40
+	{
41
+		parent::__construct();
42
+		EE_Registry::instance()->load_helper('Inflector');
43
+	}
44
+
45
+
46
+
47
+	/**
48
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
49
+	 *
50
+	 * @param WP_REST_Request $request
51
+	 * @param string          $version
52
+	 * @param string          $model_name
53
+	 * @return WP_REST_Response|\WP_Error
54
+	 */
55
+	public static function handleRequestInsert(WP_REST_Request $request, $version, $model_name)
56
+	{
57
+		$controller = new Write();
58
+		try {
59
+			$controller->setRequestedVersion($version);
60
+			return $controller->sendResponse(
61
+				$controller->insert(
62
+					$controller->getModelVersionInfo()->loadModel($model_name),
63
+					$request
64
+				)
65
+			);
66
+		} catch (\Exception $e) {
67
+			return $controller->sendResponse($e);
68
+		}
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * Handles a request from \WP_REST_Server to update an EE model
75
+	 *
76
+	 * @param WP_REST_Request $request
77
+	 * @param string          $version
78
+	 * @param string          $model_name
79
+	 * @return WP_REST_Response|\WP_Error
80
+	 */
81
+	public static function handleRequestUpdate(WP_REST_Request $request, $version, $model_name)
82
+	{
83
+		$controller = new Write();
84
+		try {
85
+			$controller->setRequestedVersion($version);
86
+			return $controller->sendResponse(
87
+				$controller->update(
88
+					$controller->getModelVersionInfo()->loadModel($model_name),
89
+					$request
90
+				)
91
+			);
92
+		} catch (\Exception $e) {
93
+			return $controller->sendResponse($e);
94
+		}
95
+	}
96
+
97
+
98
+
99
+	/**
100
+	 * Deletes a single model object and returns it. Unless
101
+	 *
102
+	 * @param WP_REST_Request $request
103
+	 * @param string          $version
104
+	 * @param string          $model_name
105
+	 * @return WP_REST_Response|\WP_Error
106
+	 */
107
+	public static function handleRequestDelete(WP_REST_Request $request, $version, $model_name)
108
+	{
109
+		$controller = new Write();
110
+		try {
111
+			$controller->setRequestedVersion($version);
112
+			return $controller->sendResponse(
113
+				$controller->delete(
114
+					$controller->getModelVersionInfo()->loadModel($model_name),
115
+					$request
116
+				)
117
+			);
118
+		} catch (\Exception $e) {
119
+			return $controller->sendResponse($e);
120
+		}
121
+	}
122
+
123
+
124
+
125
+	/**
126
+	 * Inserts a new model object according to the $request
127
+	 *
128
+	 * @param EEM_Base        $model
129
+	 * @param WP_REST_Request $request
130
+	 * @return array
131
+	 * @throws EE_Error
132
+	 * @throws RestException
133
+	 */
134
+	public function insert(EEM_Base $model, WP_REST_Request $request)
135
+	{
136
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
137
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
138
+		if (! current_user_can($default_cap_to_check_for)) {
139
+			throw new RestException(
140
+				'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
141
+				sprintf(
142
+					esc_html__(
143
+						// @codingStandardsIgnoreStart
144
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to insert data into Event Espresso.',
145
+						// @codingStandardsIgnoreEnd
146
+						'event_espresso'
147
+					),
148
+					$default_cap_to_check_for
149
+				),
150
+				array('status' => 403)
151
+			);
152
+		}
153
+		$submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
154
+		$model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
155
+			$submitted_json_data,
156
+			$model,
157
+			$this->getModelVersionInfo()->requestedVersion(),
158
+			true
159
+		);
160
+		$model_obj = EE_Registry::instance()->load_class(
161
+			$model->get_this_model_name(),
162
+			array($model_data, $model->get_timezone()),
163
+			false,
164
+			false
165
+		);
166
+		$model_obj->save();
167
+		$new_id = $model_obj->ID();
168
+		if (! $new_id) {
169
+			throw new RestException(
170
+				'rest_insertion_failed',
171
+				sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
172
+			);
173
+		}
174
+		return $this->returnModelObjAsJsonResponse($model_obj, $request);
175
+	}
176
+
177
+
178
+
179
+	/**
180
+	 * Updates an existing model object according to the $request
181
+	 *
182
+	 * @param EEM_Base        $model
183
+	 * @param WP_REST_Request $request
184
+	 * @return array
185
+	 * @throws EE_Error
186
+	 */
187
+	public function update(EEM_Base $model, WP_REST_Request $request)
188
+	{
189
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
190
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
191
+		if (! current_user_can($default_cap_to_check_for)) {
192
+			throw new RestException(
193
+				'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
194
+				sprintf(
195
+					esc_html__(
196
+						// @codingStandardsIgnoreStart
197
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to update data into Event Espresso.',
198
+						// @codingStandardsIgnoreEnd
199
+						'event_espresso'
200
+					),
201
+					$default_cap_to_check_for
202
+				),
203
+				array('status' => 403)
204
+			);
205
+		}
206
+		$obj_id = $request->get_param('id');
207
+		if (! $obj_id) {
208
+			throw new RestException(
209
+				'rest_edit_failed',
210
+				sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
211
+			);
212
+		}
213
+		$model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
214
+			$this->getBodyParams($request),
215
+			$model,
216
+			$this->getModelVersionInfo()->requestedVersion(),
217
+			true
218
+		);
219
+		$model_obj = $model->get_one_by_ID($obj_id);
220
+		$model_obj->save($model_data);
221
+		return $this->returnModelObjAsJsonResponse($model_obj, $request);
222
+	}
223
+
224
+
225
+
226
+	/**
227
+	 * Updates an existing model object according to the $request
228
+	 *
229
+	 * @param EEM_Base        $model
230
+	 * @param WP_REST_Request $request
231
+	 * @return array of either the soft-deleted item, or
232
+	 * @throws EE_Error
233
+	 */
234
+	public function delete(EEM_Base $model, WP_REST_Request $request)
235
+	{
236
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
237
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
238
+		if (! current_user_can($default_cap_to_check_for)) {
239
+			throw new RestException(
240
+				'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
241
+				sprintf(
242
+					esc_html__(
243
+						// @codingStandardsIgnoreStart
244
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to delete data into Event Espresso.',
245
+						// @codingStandardsIgnoreEnd
246
+						'event_espresso'
247
+					),
248
+					$default_cap_to_check_for
249
+				),
250
+				array('status' => 403)
251
+			);
252
+		}
253
+		$obj_id = $request->get_param('id');
254
+		$requested_permanent_delete = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN);
255
+		$requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN);
256
+		if ($requested_permanent_delete) {
257
+			$read_controller = new Read();
258
+			$read_controller->setRequestedVersion($this->getRequestedVersion());
259
+			$simulated_get_request = new WP_REST_Request('GET', $request->get_route());
260
+			$simulated_get_request->set_url_params($request->get_url_params());
261
+			$simulated_get_request->set_query_params(
262
+				array(
263
+					'caps' => EEM_Base::caps_delete
264
+				)
265
+			);
266
+			//not just grab the entity, but also use sendResponse to verify in case there's an error retrieving it
267
+			$original_response = $read_controller->sendResponse(
268
+				$read_controller->getOneOrReportPermissionError(
269
+					$model,
270
+					$simulated_get_request,
271
+					EEM_Base::caps_delete
272
+				)
273
+			);
274
+			if ($original_response instanceof WP_REST_Response) {
275
+				$original_entity = $original_response->get_data();
276
+			} else {
277
+				$original_entity = null;
278
+			}
279
+			$deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
280
+			return array(
281
+				'deleted'  => $deleted,
282
+				'previous' => $original_entity,
283
+			);
284
+		} else {
285
+			if ($model instanceof EEM_Soft_Delete_Base) {
286
+				$model->delete_by_ID($obj_id, $requested_allow_blocking);
287
+				return $this->getOneBasedOnRequest($model, $request, $obj_id);
288
+			} else {
289
+				throw new RestException(
290
+					'rest_trash_not_supported',
291
+					501,
292
+					sprintf(
293
+						esc_html__('%1$s do not support trashing. Set force=1 to delete.', 'event_espresso'),
294
+						EEH_Inflector::pluralize($model->get_this_model_name())
295
+					)
296
+				);
297
+			}
298
+		}
299
+	}
300
+
301
+
302
+
303
+	/**
304
+	 * Returns an array ready to be converted into a JSON response, based solely on the model object
305
+	 *
306
+	 * @param EE_Base_Class $model_obj
307
+	 * @param WP_REST_Request $request
308
+	 * @return array ready for a response
309
+	 */
310
+	protected function returnModelObjAsJsonResponse(EE_Base_Class $model_obj, WP_REST_Request $request)
311
+	{
312
+		$model = $model_obj->get_model();
313
+		//create an array exactly like the wpdb results row,
314
+		// so we can pass it to controllers/model/Read::create_entity_from_wpdb_result()
315
+		$simulated_db_row = array();
316
+		foreach ($model->field_settings(true) as $field_name => $field_obj) {
317
+			//we need to reconstruct the normal wpdb results, including the db-only fields
318
+			//like a secondary table's primary key. The models expect those (but don't care what value they have)
319
+			if( $field_obj instanceof EE_DB_Only_Field_Base){
320
+				$raw_value = true;
321
+			} elseif ($field_obj instanceof EE_Datetime_Field) {
322
+				$raw_value = $model_obj->get_DateTime_object($field_name);
323
+			} else {
324
+				$raw_value = $model_obj->get_raw($field_name);
325
+			}
326
+			$simulated_db_row[$field_obj->get_qualified_column()] = $field_obj->prepare_for_use_in_db($raw_value);
327
+		}
328
+		$read_controller = new Read();
329
+		$read_controller->setRequestedVersion($this->getRequestedVersion());
330
+		//the simulates request really doesn't need any info downstream
331
+		$simulated_request = new WP_REST_Request('GET');
332
+		return $read_controller->createEntityFromWpdbResult(
333
+			$model_obj->get_model(),
334
+			$simulated_db_row,
335
+			$simulated_request
336
+		);
337
+	}
338
+
339
+
340
+
341
+	/**
342
+	 * Gets the item affected by this request
343
+	 *
344
+	 * @param EEM_Base        $model
345
+	 * @param WP_REST_Request $request
346
+	 * @param  int|string     $obj_id
347
+	 * @return \WP_Error|array
348
+	 */
349
+	protected function getOneBasedOnRequest(EEM_Base $model, WP_REST_Request $request, $obj_id)
350
+	{
351
+		$requested_version = $this->getRequestedVersion($request->get_route());
352
+		$get_request = new WP_REST_Request(
353
+			'GET',
354
+			EED_Core_Rest_Api::ee_api_namespace
355
+			. $requested_version
356
+			. '/'
357
+			. EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
358
+			. '/'
359
+			. $obj_id
360
+		);
361
+		$get_request->set_url_params(
362
+			array(
363
+				'id'      => $obj_id,
364
+				'include' => $request->get_param('include'),
365
+			)
366
+		);
367
+		$read_controller = new Read();
368
+		$read_controller->setRequestedVersion($this->getRequestedVersion());
369
+		return $read_controller->getEntityFromModel($model, $get_request);
370
+	}
371 371
 }
372 372
 // End of file Read.php
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 use EEH_Inflector;
18 18
 use EE_Error;
19 19
 
20
-if (! defined('EVENT_ESPRESSO_VERSION')) {
20
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
21 21
     exit('No direct script access allowed');
22 22
 }
23 23
 
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
     {
136 136
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
137 137
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
138
-        if (! current_user_can($default_cap_to_check_for)) {
138
+        if ( ! current_user_can($default_cap_to_check_for)) {
139 139
             throw new RestException(
140
-                'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
140
+                'rest_cannot_create_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
141 141
                 sprintf(
142 142
                     esc_html__(
143 143
                         // @codingStandardsIgnoreStart
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
                 array('status' => 403)
151 151
             );
152 152
         }
153
-        $submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
153
+        $submitted_json_data = array_merge((array) $request->get_body_params(), (array) $request->get_json_params());
154 154
         $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
155 155
             $submitted_json_data,
156 156
             $model,
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
         );
166 166
         $model_obj->save();
167 167
         $new_id = $model_obj->ID();
168
-        if (! $new_id) {
168
+        if ( ! $new_id) {
169 169
             throw new RestException(
170 170
                 'rest_insertion_failed',
171 171
                 sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
@@ -188,9 +188,9 @@  discard block
 block discarded – undo
188 188
     {
189 189
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
190 190
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
191
-        if (! current_user_can($default_cap_to_check_for)) {
191
+        if ( ! current_user_can($default_cap_to_check_for)) {
192 192
             throw new RestException(
193
-                'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
193
+                'rest_cannot_edit_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
194 194
                 sprintf(
195 195
                     esc_html__(
196 196
                         // @codingStandardsIgnoreStart
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
             );
205 205
         }
206 206
         $obj_id = $request->get_param('id');
207
-        if (! $obj_id) {
207
+        if ( ! $obj_id) {
208 208
             throw new RestException(
209 209
                 'rest_edit_failed',
210 210
                 sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
@@ -235,9 +235,9 @@  discard block
 block discarded – undo
235 235
     {
236 236
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
237 237
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
238
-        if (! current_user_can($default_cap_to_check_for)) {
238
+        if ( ! current_user_can($default_cap_to_check_for)) {
239 239
             throw new RestException(
240
-                'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
240
+                'rest_cannot_delete_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
241 241
                 sprintf(
242 242
                     esc_html__(
243 243
                         // @codingStandardsIgnoreStart
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
             } else {
277 277
                 $original_entity = null;
278 278
             }
279
-            $deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
279
+            $deleted = (bool) $model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
280 280
             return array(
281 281
                 'deleted'  => $deleted,
282 282
                 'previous' => $original_entity,
@@ -316,7 +316,7 @@  discard block
 block discarded – undo
316 316
         foreach ($model->field_settings(true) as $field_name => $field_obj) {
317 317
             //we need to reconstruct the normal wpdb results, including the db-only fields
318 318
             //like a secondary table's primary key. The models expect those (but don't care what value they have)
319
-            if( $field_obj instanceof EE_DB_Only_Field_Base){
319
+            if ($field_obj instanceof EE_DB_Only_Field_Base) {
320 320
                 $raw_value = true;
321 321
             } elseif ($field_obj instanceof EE_Datetime_Field) {
322 322
                 $raw_value = $model_obj->get_DateTime_object($field_name);
Please login to merge, or discard this patch.