Completed
Branch BUG-10202-persistent-admin-not... (9f1ecb)
by
unknown
22:02 queued 10:36
created
admin_pages/maintenance/templates/ee_data_reset_and_delete.template.php 1 patch
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -7,13 +7,13 @@  discard block
 block discarded – undo
7 7
 /** @var string $delete_db_url */
8 8
 ?>
9 9
 <h2>
10
-	<?php esc_html_e( 'Reset/Delete Data for Event Espresso', 'event_espresso' );?>
10
+	<?php esc_html_e('Reset/Delete Data for Event Espresso', 'event_espresso'); ?>
11 11
 </h2>
12 12
 <br />
13 13
 
14 14
 <div class="padding">
15
-	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Ticket and Datetime Reserved Counts', 'event_espresso');?></h4>
16
-	<p><?php esc_html_e('Use this to reset the counts for ticket and datetime reservations.', 'event_espresso');?></p>
15
+	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Ticket and Datetime Reserved Counts', 'event_espresso'); ?></h4>
16
+	<p><?php esc_html_e('Use this to reset the counts for ticket and datetime reservations.', 'event_espresso'); ?></p>
17 17
 	<div class="float-right"><?php echo $reset_reservations_button; ?></div>
18 18
 	<div class="clear"></div>
19 19
 </div>
@@ -22,8 +22,8 @@  discard block
 block discarded – undo
22 22
 
23 23
 <!-- reset DB url is here. Just need to make it look pretty and unhide it-->
24 24
 <div class="padding">
25
-	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Event Espresso Capabilities', 'event_espresso');?></h4>
26
-	<p><?php esc_html_e('Use this to reset the capabilities on WP roles to the defaults as defined via EE_Capabilities.  Note this reset does not REMOVE any existing capabilities, it just ensures that all the defaults are ADDED to the roles.', 'event_espresso');?></p>
25
+	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Event Espresso Capabilities', 'event_espresso'); ?></h4>
26
+	<p><?php esc_html_e('Use this to reset the capabilities on WP roles to the defaults as defined via EE_Capabilities.  Note this reset does not REMOVE any existing capabilities, it just ensures that all the defaults are ADDED to the roles.', 'event_espresso'); ?></p>
27 27
 	<div class="float-right"><?php echo $reset_capabilities_button; ?></div>
28 28
 	<div class="clear"></div>
29 29
 </div>
@@ -31,29 +31,29 @@  discard block
 block discarded – undo
31 31
 <br />
32 32
 
33 33
 <div class="padding">
34
-	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Event Espresso Data', 'event_espresso');?></h4>
35
-    <p><?php esc_html_e(' This will reset data for Event Espresso 4, and for all active add-ons. Inactive add-ons will not be affected.', 'event_espresso');?></p>
36
-    <p><?php esc_html_e('Your Event Espresso data will return to its default settings. The rest of your website will be unaffected.', 'event_espresso');?></p>
37
-	<div class="float-right"><a class="button button-primary ee-confirm" href="<?php echo $reset_db_url;?>"><?php esc_html_e('Reset Event Espresso Tables', 'event_espresso');?></a></div>
34
+	<h4 class="espresso-header"><span class="dashicons dashicons-update ee-icon-size-22"></span><?php esc_html_e('Reset Event Espresso Data', 'event_espresso'); ?></h4>
35
+    <p><?php esc_html_e(' This will reset data for Event Espresso 4, and for all active add-ons. Inactive add-ons will not be affected.', 'event_espresso'); ?></p>
36
+    <p><?php esc_html_e('Your Event Espresso data will return to its default settings. The rest of your website will be unaffected.', 'event_espresso'); ?></p>
37
+	<div class="float-right"><a class="button button-primary ee-confirm" href="<?php echo $reset_db_url; ?>"><?php esc_html_e('Reset Event Espresso Tables', 'event_espresso'); ?></a></div>
38 38
 	<div class="clear"></div>
39 39
 </div>
40 40
 <br />
41 41
 <br />
42 42
 
43 43
 <div class="padding">
44
-	<h4 class="espresso-header"><span class="dashicons dashicons-post-trash ee-icon-size-22"></span><?php esc_html_e('Permanently Delete ALL Event Espresso Data', 'event_espresso');?></h4>
44
+	<h4 class="espresso-header"><span class="dashicons dashicons-post-trash ee-icon-size-22"></span><?php esc_html_e('Permanently Delete ALL Event Espresso Data', 'event_espresso'); ?></h4>
45 45
     <p><?php esc_html_e(' This will delete data for Event Espresso 4, and all currently active add-ons. Event Espresso will then be deactivated. You may need to manually deactivate each add-on individually.',
46
-            'event_espresso');?></p>
47
-	<p><?php esc_html_e('If you know for certain that you will no longer be using Event Espresso and you wish to remove ALL traces of the plugin from your system, then perform the following steps.', 'event_espresso');?></p>
48
-	<p class="important-notice"><?php printf( esc_html__('Please note: %sThis is permanent and can NOT be undone.%s', 'event_espresso'), '<em>', '</em>' ); ?><br/></p>
46
+            'event_espresso'); ?></p>
47
+	<p><?php esc_html_e('If you know for certain that you will no longer be using Event Espresso and you wish to remove ALL traces of the plugin from your system, then perform the following steps.', 'event_espresso'); ?></p>
48
+	<p class="important-notice"><?php printf(esc_html__('Please note: %sThis is permanent and can NOT be undone.%s', 'event_espresso'), '<em>', '</em>'); ?><br/></p>
49 49
 	<ol>
50
-		<li><?php  printf( esc_html__('First, click the button below to permanently delete all Event Espresso tables, records, and options from your WordPress database . If you receive a "500 Internal Server Error" or a blank white screen, it means the server has timed out due to the large number of records being updated. This is not a cause for concern. Simply %1$srefresh the page%2$s and the Database Update will continue where it left off.', 'event_espresso'), '<strong>', '</strong>' );?></li>
51
-		<li><?php printf( esc_html__('Then, locate Event Espresso on the WordPress Plugins page, and click on %sDelete%s', 'event_espresso'), '<strong>', '</strong>' ); ?></li>
52
-        <li><?php printf( esc_html__('Once you are on the Delete Plugin page, click on %sYes, Delete these files and data%s', 'event_espresso'), '<strong>', '</strong>' ); ?></li>
53
-		<li><?php printf( esc_html__('Note: Event Espresso 4 categories are %snot%s deleted by this script', 'event_espresso'), '<strong>', '</strong>' ); ?>
50
+		<li><?php  printf(esc_html__('First, click the button below to permanently delete all Event Espresso tables, records, and options from your WordPress database . If you receive a "500 Internal Server Error" or a blank white screen, it means the server has timed out due to the large number of records being updated. This is not a cause for concern. Simply %1$srefresh the page%2$s and the Database Update will continue where it left off.', 'event_espresso'), '<strong>', '</strong>'); ?></li>
51
+		<li><?php printf(esc_html__('Then, locate Event Espresso on the WordPress Plugins page, and click on %sDelete%s', 'event_espresso'), '<strong>', '</strong>'); ?></li>
52
+        <li><?php printf(esc_html__('Once you are on the Delete Plugin page, click on %sYes, Delete these files and data%s', 'event_espresso'), '<strong>', '</strong>'); ?></li>
53
+		<li><?php printf(esc_html__('Note: Event Espresso 4 categories are %snot%s deleted by this script', 'event_espresso'), '<strong>', '</strong>'); ?>
54 54
 		<br><a href="<?php echo admin_url('edit-tags.php?taxonomy=espresso_event_categories'); ?>"><?php esc_html_e('You can go here to delete Event Espresso categories', 'event_espresso'); ?></a></li>
55 55
 	</ol>
56
-	<div class="float-right"><a href="<?php echo $delete_db_url; ?>" id="delete-all-data-btn" class="button-primary ee-confirm"><?php esc_html_e('Permanently Delete All Event Espresso Data', 'event_espresso');?></a></div>
56
+	<div class="float-right"><a href="<?php echo $delete_db_url; ?>" id="delete-all-data-btn" class="button-primary ee-confirm"><?php esc_html_e('Permanently Delete All Event Espresso Data', 'event_espresso'); ?></a></div>
57 57
 	<div class="clear"></div>
58 58
 </div>
59 59
 <br/>
Please login to merge, or discard this patch.
core/data_migration_scripts/EE_DMS_Core_4_9_0.dms.php 2 patches
Indentation   +289 added lines, -289 removed lines patch added patch discarded remove patch
@@ -12,9 +12,9 @@  discard block
 block discarded – undo
12 12
 $stages = glob(EE_CORE . 'data_migration_scripts/4_9_0_stages/*');
13 13
 $class_to_filepath = array();
14 14
 foreach ($stages as $filepath) {
15
-    $matches = array();
16
-    preg_match('~4_9_0_stages/(.*).dmsstage.php~', $filepath, $matches);
17
-    $class_to_filepath[$matches[1]] = $filepath;
15
+	$matches = array();
16
+	preg_match('~4_9_0_stages/(.*).dmsstage.php~', $filepath, $matches);
17
+	$class_to_filepath[$matches[1]] = $filepath;
18 18
 }
19 19
 //give addons a chance to autoload their stages too
20 20
 $class_to_filepath = apply_filters('FHEE__EE_DMS_4_9_0__autoloaded_stages', $class_to_filepath);
@@ -33,68 +33,68 @@  discard block
 block discarded – undo
33 33
 class EE_DMS_Core_4_9_0 extends EE_Data_Migration_Script_Base
34 34
 {
35 35
 
36
-    /**
37
-     * return EE_DMS_Core_4_9_0
38
-     *
39
-     * @param TableManager  $table_manager
40
-     * @param TableAnalysis $table_analysis
41
-     */
42
-    public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
43
-    {
44
-        $this->_pretty_name = esc_html__("Data Update to Event Espresso 4.9.0", "event_espresso");
45
-        $this->_priority = 10;
46
-        $this->_migration_stages = array(
47
-            new EE_DMS_4_9_0_Email_System_Question(),
48
-            new EE_DMS_4_9_0_Answers_With_No_Registration(),
49
-        );
50
-        parent::__construct($table_manager, $table_analysis);
51
-    }
36
+	/**
37
+	 * return EE_DMS_Core_4_9_0
38
+	 *
39
+	 * @param TableManager  $table_manager
40
+	 * @param TableAnalysis $table_analysis
41
+	 */
42
+	public function __construct(TableManager $table_manager = null, TableAnalysis $table_analysis = null)
43
+	{
44
+		$this->_pretty_name = esc_html__("Data Update to Event Espresso 4.9.0", "event_espresso");
45
+		$this->_priority = 10;
46
+		$this->_migration_stages = array(
47
+			new EE_DMS_4_9_0_Email_System_Question(),
48
+			new EE_DMS_4_9_0_Answers_With_No_Registration(),
49
+		);
50
+		parent::__construct($table_manager, $table_analysis);
51
+	}
52 52
 
53 53
 
54 54
 
55
-    /**
56
-     * Whether to migrate or not.
57
-     *
58
-     * @param array $version_array
59
-     * @return bool
60
-     */
61
-    public function can_migrate_from_version($version_array)
62
-    {
63
-        $version_string = $version_array['Core'];
64
-        if (version_compare($version_string, '4.9.0', '<=') && version_compare($version_string, '4.8.0', '>=')) {
65
-            //			echo "$version_string can be migrated from";
66
-            return true;
67
-        } elseif ( ! $version_string) {
68
-            //			echo "no version string provided: $version_string";
69
-            //no version string provided... this must be pre 4.3
70
-            return false;//changed mind. dont want people thinking they should migrate yet because they cant
71
-        } else {
72
-            //			echo "$version_string doesnt apply";
73
-            return false;
74
-        }
75
-    }
55
+	/**
56
+	 * Whether to migrate or not.
57
+	 *
58
+	 * @param array $version_array
59
+	 * @return bool
60
+	 */
61
+	public function can_migrate_from_version($version_array)
62
+	{
63
+		$version_string = $version_array['Core'];
64
+		if (version_compare($version_string, '4.9.0', '<=') && version_compare($version_string, '4.8.0', '>=')) {
65
+			//			echo "$version_string can be migrated from";
66
+			return true;
67
+		} elseif ( ! $version_string) {
68
+			//			echo "no version string provided: $version_string";
69
+			//no version string provided... this must be pre 4.3
70
+			return false;//changed mind. dont want people thinking they should migrate yet because they cant
71
+		} else {
72
+			//			echo "$version_string doesnt apply";
73
+			return false;
74
+		}
75
+	}
76 76
 
77 77
 
78 78
 
79
-    /**
80
-     * @return bool
81
-     */
82
-    public function schema_changes_before_migration()
83
-    {
84
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
85
-        $now_in_mysql = current_time('mysql', true);
86
-        $table_name = 'esp_answer';
87
-        $sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
79
+	/**
80
+	 * @return bool
81
+	 */
82
+	public function schema_changes_before_migration()
83
+	{
84
+		require_once(EE_HELPERS . 'EEH_Activation.helper.php');
85
+		$now_in_mysql = current_time('mysql', true);
86
+		$table_name = 'esp_answer';
87
+		$sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
88 88
 					REG_ID int(10) unsigned NOT NULL,
89 89
 					QST_ID int(10) unsigned NOT NULL,
90 90
 					ANS_value text NOT NULL,
91 91
 					PRIMARY KEY  (ANS_ID),
92 92
 					KEY REG_ID (REG_ID),
93 93
 					KEY QST_ID (QST_ID)";
94
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
95
-        $table_name = 'esp_attendee_meta';
96
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'ATT_email');
97
-        $sql = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
94
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
95
+		$table_name = 'esp_attendee_meta';
96
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'ATT_email');
97
+		$sql = "ATTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
98 98
 				ATT_ID bigint(20) unsigned NOT NULL,
99 99
 				ATT_fname varchar(45) NOT NULL,
100 100
 				ATT_lname varchar(45) NOT NULL,
@@ -111,9 +111,9 @@  discard block
 block discarded – undo
111 111
 				KEY ATT_email (ATT_email(191)),
112 112
 				KEY ATT_lname (ATT_lname),
113 113
 				KEY ATT_fname (ATT_fname)";
114
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
115
-        $table_name = 'esp_checkin';
116
-        $sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
114
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
115
+		$table_name = 'esp_checkin';
116
+		$sql = "CHK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
117 117
 				REG_ID int(10) unsigned NOT NULL,
118 118
 				DTT_ID int(10) unsigned NOT NULL,
119 119
 				CHK_in tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -121,9 +121,9 @@  discard block
 block discarded – undo
121 121
 				PRIMARY KEY  (CHK_ID),
122 122
 				KEY REG_ID (REG_ID),
123 123
 				KEY DTT_ID (DTT_ID)";
124
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
125
-        $table_name = 'esp_country';
126
-        $sql = "CNT_ISO varchar(2) NOT NULL,
124
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
125
+		$table_name = 'esp_country';
126
+		$sql = "CNT_ISO varchar(2) NOT NULL,
127 127
 				CNT_ISO3 varchar(3) NOT NULL,
128 128
 				RGN_ID tinyint(3) unsigned DEFAULT NULL,
129 129
 				CNT_name varchar(45) NOT NULL,
@@ -139,29 +139,29 @@  discard block
 block discarded – undo
139 139
 				CNT_is_EU tinyint(1) DEFAULT '0',
140 140
 				CNT_active tinyint(1) DEFAULT '0',
141 141
 				PRIMARY KEY  (CNT_ISO)";
142
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
143
-        $table_name = 'esp_currency';
144
-        $sql = "CUR_code varchar(6) NOT NULL,
142
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
143
+		$table_name = 'esp_currency';
144
+		$sql = "CUR_code varchar(6) NOT NULL,
145 145
 				CUR_single varchar(45) DEFAULT 'dollar',
146 146
 				CUR_plural varchar(45) DEFAULT 'dollars',
147 147
 				CUR_sign varchar(45) DEFAULT '$',
148 148
 				CUR_dec_plc varchar(1) NOT NULL DEFAULT '2',
149 149
 				CUR_active tinyint(1) DEFAULT '0',
150 150
 				PRIMARY KEY  (CUR_code)";
151
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
152
-        //note: although this table is no longer in use,
153
-        //it hasn't been removed because then queries to the model will have errors.
154
-        //but you should expect this table and its corresponding model to be removed in
155
-        //the next few months
156
-        $table_name = 'esp_currency_payment_method';
157
-        $sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
151
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
152
+		//note: although this table is no longer in use,
153
+		//it hasn't been removed because then queries to the model will have errors.
154
+		//but you should expect this table and its corresponding model to be removed in
155
+		//the next few months
156
+		$table_name = 'esp_currency_payment_method';
157
+		$sql = "CPM_ID int(11) NOT NULL AUTO_INCREMENT,
158 158
 				CUR_code varchar(6) NOT NULL,
159 159
 				PMD_ID int(11) NOT NULL,
160 160
 				PRIMARY KEY  (CPM_ID),
161 161
 				KEY PMD_ID (PMD_ID)";
162
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
163
-        $table_name = 'esp_datetime';
164
-        $sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
162
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
163
+		$table_name = 'esp_datetime';
164
+		$sql = "DTT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
165 165
 				EVT_ID bigint(20) unsigned NOT NULL,
166 166
 				DTT_name varchar(255) NOT NULL DEFAULT '',
167 167
 				DTT_description text NOT NULL,
@@ -178,25 +178,25 @@  discard block
 block discarded – undo
178 178
 				KEY DTT_EVT_start (DTT_EVT_start),
179 179
 				KEY EVT_ID (EVT_ID),
180 180
 				KEY DTT_is_primary (DTT_is_primary)";
181
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
182
-        $table_name = "esp_datetime_ticket";
183
-        $sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
181
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
182
+		$table_name = "esp_datetime_ticket";
183
+		$sql = "DTK_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
184 184
 				DTT_ID int(10) unsigned NOT NULL,
185 185
 				TKT_ID int(10) unsigned NOT NULL,
186 186
 				PRIMARY KEY  (DTK_ID),
187 187
 				KEY DTT_ID (DTT_ID),
188 188
 				KEY TKT_ID (TKT_ID)";
189
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
190
-        $table_name = 'esp_event_message_template';
191
-        $sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
189
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
190
+		$table_name = 'esp_event_message_template';
191
+		$sql = "EMT_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
192 192
 				EVT_ID bigint(20) unsigned NOT NULL DEFAULT 0,
193 193
 				GRP_ID int(10) unsigned NOT NULL DEFAULT 0,
194 194
 				PRIMARY KEY  (EMT_ID),
195 195
 				KEY EVT_ID (EVT_ID),
196 196
 				KEY GRP_ID (GRP_ID)";
197
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
198
-        $table_name = 'esp_event_meta';
199
-        $sql = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
197
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
198
+		$table_name = 'esp_event_meta';
199
+		$sql = "EVTM_ID int(10) NOT NULL AUTO_INCREMENT,
200 200
 				EVT_ID bigint(20) unsigned NOT NULL,
201 201
 				EVT_display_desc tinyint(1) unsigned NOT NULL DEFAULT 1,
202 202
 				EVT_display_ticket_selector tinyint(1) unsigned NOT NULL DEFAULT 1,
@@ -211,34 +211,34 @@  discard block
 block discarded – undo
211 211
 				EVT_donations tinyint(1) NULL,
212 212
 				PRIMARY KEY  (EVTM_ID),
213 213
 				KEY EVT_ID (EVT_ID)";
214
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
215
-        $table_name = 'esp_event_question_group';
216
-        $sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
214
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
215
+		$table_name = 'esp_event_question_group';
216
+		$sql = "EQG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
217 217
 				EVT_ID bigint(20) unsigned NOT NULL,
218 218
 				QSG_ID int(10) unsigned NOT NULL,
219 219
 				EQG_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
220 220
 				PRIMARY KEY  (EQG_ID),
221 221
 				KEY EVT_ID (EVT_ID),
222 222
 				KEY QSG_ID (QSG_ID)";
223
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
224
-        $table_name = 'esp_event_venue';
225
-        $sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
223
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
224
+		$table_name = 'esp_event_venue';
225
+		$sql = "EVV_ID int(11) NOT NULL AUTO_INCREMENT,
226 226
 				EVT_ID bigint(20) unsigned NOT NULL,
227 227
 				VNU_ID bigint(20) unsigned NOT NULL,
228 228
 				EVV_primary tinyint(1) unsigned NOT NULL DEFAULT 0,
229 229
 				PRIMARY KEY  (EVV_ID)";
230
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
231
-        $table_name = 'esp_extra_meta';
232
-        $sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
230
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
231
+		$table_name = 'esp_extra_meta';
232
+		$sql = "EXM_ID int(11) NOT NULL AUTO_INCREMENT,
233 233
 				OBJ_ID int(11) DEFAULT NULL,
234 234
 				EXM_type varchar(45) DEFAULT NULL,
235 235
 				EXM_key varchar(45) DEFAULT NULL,
236 236
 				EXM_value text,
237 237
 				PRIMARY KEY  (EXM_ID),
238 238
 				KEY EXM_type (EXM_type,OBJ_ID,EXM_key)";
239
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
240
-        $table_name = 'esp_extra_join';
241
-        $sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
239
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
240
+		$table_name = 'esp_extra_join';
241
+		$sql = "EXJ_ID int(11) NOT NULL AUTO_INCREMENT,
242 242
 				EXJ_first_model_id varchar(6) NOT NULL,
243 243
 				EXJ_first_model_name varchar(20) NOT NULL,
244 244
 				EXJ_second_model_id varchar(6) NOT NULL,
@@ -246,9 +246,9 @@  discard block
 block discarded – undo
246 246
 				PRIMARY KEY  (EXJ_ID),
247 247
 				KEY first_model (EXJ_first_model_name,EXJ_first_model_id),
248 248
 				KEY second_model (EXJ_second_model_name,EXJ_second_model_id)";
249
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
250
-        $table_name = 'esp_line_item';
251
-        $sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
249
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
250
+		$table_name = 'esp_line_item';
251
+		$sql = "LIN_ID int(11) NOT NULL AUTO_INCREMENT,
252 252
 				LIN_code varchar(245) NOT NULL DEFAULT '',
253 253
 				TXN_ID int(11) DEFAULT NULL,
254 254
 				LIN_name varchar(245) NOT NULL DEFAULT '',
@@ -267,9 +267,9 @@  discard block
 block discarded – undo
267 267
 				PRIMARY KEY  (LIN_ID),
268 268
 				KEY LIN_code (LIN_code(191)),
269 269
 				KEY TXN_ID (TXN_ID)";
270
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
271
-        $table_name = 'esp_log';
272
-        $sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
270
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
271
+		$table_name = 'esp_log';
272
+		$sql = "LOG_ID int(11) NOT NULL AUTO_INCREMENT,
273 273
 				LOG_time datetime DEFAULT NULL,
274 274
 				OBJ_ID varchar(45) DEFAULT NULL,
275 275
 				OBJ_type varchar(45) DEFAULT NULL,
@@ -280,12 +280,12 @@  discard block
 block discarded – undo
280 280
 				KEY LOG_time (LOG_time),
281 281
 				KEY OBJ (OBJ_type,OBJ_ID),
282 282
 				KEY LOG_type (LOG_type)";
283
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
284
-        $table_name = 'esp_message';
285
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_to');
286
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_from');
287
-        $this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_subject');
288
-        $sql = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
283
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
284
+		$table_name = 'esp_message';
285
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_to');
286
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_from');
287
+		$this->_get_table_manager()->dropIndexIfSizeNot($table_name, 'MSG_subject');
288
+		$sql = "MSG_ID bigint(20) unsigned NOT NULL AUTO_INCREMENT,
289 289
 				GRP_ID int(10) unsigned NULL,
290 290
 				MSG_token varchar(255) NULL,
291 291
 				TXN_ID int(10) unsigned NULL,
@@ -317,18 +317,18 @@  discard block
 block discarded – undo
317 317
 				KEY STS_ID (STS_ID),
318 318
 				KEY MSG_created (MSG_created),
319 319
 				KEY MSG_modified (MSG_modified)";
320
-        $this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
321
-        $table_name = 'esp_message_template';
322
-        $sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
320
+		$this->_table_is_new_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
321
+		$table_name = 'esp_message_template';
322
+		$sql = "MTP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
323 323
 				GRP_ID int(10) unsigned NOT NULL,
324 324
 				MTP_context varchar(50) NOT NULL,
325 325
 				MTP_template_field varchar(30) NOT NULL,
326 326
 				MTP_content text NOT NULL,
327 327
 				PRIMARY KEY  (MTP_ID),
328 328
 				KEY GRP_ID (GRP_ID)";
329
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
330
-        $table_name = 'esp_message_template_group';
331
-        $sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
329
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
330
+		$table_name = 'esp_message_template_group';
331
+		$sql = "GRP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
332 332
 				MTP_user_id int(10) NOT NULL DEFAULT '1',
333 333
 				MTP_name varchar(245) NOT NULL DEFAULT '',
334 334
 				MTP_description varchar(245) NOT NULL DEFAULT '',
@@ -340,9 +340,9 @@  discard block
 block discarded – undo
340 340
 				MTP_is_active tinyint(1) NOT NULL DEFAULT '1',
341 341
 				PRIMARY KEY  (GRP_ID),
342 342
 				KEY MTP_user_id (MTP_user_id)";
343
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
344
-        $table_name = 'esp_payment';
345
-        $sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
343
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
344
+		$table_name = 'esp_payment';
345
+		$sql = "PAY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
346 346
 				TXN_ID int(10) unsigned DEFAULT NULL,
347 347
 				STS_ID varchar(3) DEFAULT NULL,
348 348
 				PAY_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
@@ -359,9 +359,9 @@  discard block
 block discarded – undo
359 359
 				PRIMARY KEY  (PAY_ID),
360 360
 				KEY PAY_timestamp (PAY_timestamp),
361 361
 				KEY TXN_ID (TXN_ID)";
362
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
363
-        $table_name = 'esp_payment_method';
364
-        $sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
362
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
363
+		$table_name = 'esp_payment_method';
364
+		$sql = "PMD_ID int(11) NOT NULL AUTO_INCREMENT,
365 365
 				PMD_type varchar(124) DEFAULT NULL,
366 366
 				PMD_name varchar(255) DEFAULT NULL,
367 367
 				PMD_desc text,
@@ -377,24 +377,24 @@  discard block
 block discarded – undo
377 377
 				PRIMARY KEY  (PMD_ID),
378 378
 				UNIQUE KEY PMD_slug_UNIQUE (PMD_slug),
379 379
 				KEY PMD_type (PMD_type)";
380
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
381
-        $table_name = "esp_ticket_price";
382
-        $sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
380
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
381
+		$table_name = "esp_ticket_price";
382
+		$sql = "TKP_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
383 383
 				TKT_ID int(10) unsigned NOT NULL,
384 384
 				PRC_ID int(10) unsigned NOT NULL,
385 385
 				PRIMARY KEY  (TKP_ID),
386 386
 				KEY TKT_ID (TKT_ID),
387 387
 				KEY PRC_ID (PRC_ID)";
388
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
389
-        $table_name = "esp_ticket_template";
390
-        $sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
388
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
389
+		$table_name = "esp_ticket_template";
390
+		$sql = "TTM_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
391 391
 				TTM_name varchar(45) NOT NULL,
392 392
 				TTM_description text,
393 393
 				TTM_file varchar(45),
394 394
 				PRIMARY KEY  (TTM_ID)";
395
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
396
-        $table_name = 'esp_question';
397
-        $sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
395
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
396
+		$table_name = 'esp_question';
397
+		$sql = 'QST_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
398 398
 				QST_display_text text NOT NULL,
399 399
 				QST_admin_label varchar(255) NOT NULL,
400 400
 				QST_system varchar(25) DEFAULT NULL,
@@ -408,18 +408,18 @@  discard block
 block discarded – undo
408 408
 				QST_deleted tinyint(2) unsigned NOT NULL DEFAULT 0,
409 409
 				PRIMARY KEY  (QST_ID),
410 410
 				KEY QST_order (QST_order)';
411
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
412
-        $table_name = 'esp_question_group_question';
413
-        $sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
411
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
412
+		$table_name = 'esp_question_group_question';
413
+		$sql = "QGQ_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
414 414
 				QSG_ID int(10) unsigned NOT NULL,
415 415
 				QST_ID int(10) unsigned NOT NULL,
416 416
 				QGQ_order int(10) unsigned NOT NULL DEFAULT 0,
417 417
 				PRIMARY KEY  (QGQ_ID),
418 418
 				KEY QST_ID (QST_ID),
419 419
 				KEY QSG_ID_order (QSG_ID,QGQ_order)";
420
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
421
-        $table_name = 'esp_question_option';
422
-        $sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
420
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
421
+		$table_name = 'esp_question_option';
422
+		$sql = "QSO_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
423 423
 				QSO_value varchar(255) NOT NULL,
424 424
 				QSO_desc text NOT NULL,
425 425
 				QST_ID int(10) unsigned NOT NULL,
@@ -429,9 +429,9 @@  discard block
 block discarded – undo
429 429
 				PRIMARY KEY  (QSO_ID),
430 430
 				KEY QST_ID (QST_ID),
431 431
 				KEY QSO_order (QSO_order)";
432
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
433
-        $table_name = 'esp_registration';
434
-        $sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
432
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
433
+		$table_name = 'esp_registration';
434
+		$sql = "REG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
435 435
 				EVT_ID bigint(20) unsigned NOT NULL,
436 436
 				ATT_ID bigint(20) unsigned NOT NULL,
437 437
 				TXN_ID int(10) unsigned NOT NULL,
@@ -455,18 +455,18 @@  discard block
 block discarded – undo
455 455
 				KEY TKT_ID (TKT_ID),
456 456
 				KEY EVT_ID (EVT_ID),
457 457
 				KEY STS_ID (STS_ID)";
458
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
459
-        $table_name = 'esp_registration_payment';
460
-        $sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
458
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
459
+		$table_name = 'esp_registration_payment';
460
+		$sql = "RPY_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
461 461
 					  REG_ID int(10) unsigned NOT NULL,
462 462
 					  PAY_ID int(10) unsigned NULL,
463 463
 					  RPY_amount decimal(12,3) NOT NULL DEFAULT '0.00',
464 464
 					  PRIMARY KEY  (RPY_ID),
465 465
 					  KEY REG_ID (REG_ID),
466 466
 					  KEY PAY_ID (PAY_ID)";
467
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
468
-        $table_name = 'esp_state';
469
-        $sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
467
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB ');
468
+		$table_name = 'esp_state';
469
+		$sql = "STA_ID smallint(5) unsigned NOT NULL AUTO_INCREMENT,
470 470
 				CNT_ISO varchar(2) NOT NULL,
471 471
 				STA_abbrev varchar(24) NOT NULL,
472 472
 				STA_name varchar(100) NOT NULL,
@@ -474,9 +474,9 @@  discard block
 block discarded – undo
474 474
 				PRIMARY KEY  (STA_ID),
475 475
 				KEY STA_abbrev (STA_abbrev),
476 476
 				KEY CNT_ISO (CNT_ISO)";
477
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
478
-        $table_name = 'esp_status';
479
-        $sql = "STS_ID varchar(3) NOT NULL,
477
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
478
+		$table_name = 'esp_status';
479
+		$sql = "STS_ID varchar(3) NOT NULL,
480 480
 				STS_code varchar(45) NOT NULL,
481 481
 				STS_type varchar(45) NOT NULL,
482 482
 				STS_can_edit tinyint(1) NOT NULL DEFAULT 0,
@@ -484,9 +484,9 @@  discard block
 block discarded – undo
484 484
 				STS_open tinyint(1) NOT NULL DEFAULT 1,
485 485
 				UNIQUE KEY STS_ID_UNIQUE (STS_ID),
486 486
 				KEY STS_type (STS_type)";
487
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
488
-        $table_name = 'esp_transaction';
489
-        $sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
487
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
488
+		$table_name = 'esp_transaction';
489
+		$sql = "TXN_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
490 490
 				TXN_timestamp datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
491 491
 				TXN_total decimal(12,3) DEFAULT '0.00',
492 492
 				TXN_paid decimal(12,3) NOT NULL DEFAULT '0.00',
@@ -498,9 +498,9 @@  discard block
 block discarded – undo
498 498
 				PRIMARY KEY  (TXN_ID),
499 499
 				KEY TXN_timestamp (TXN_timestamp),
500 500
 				KEY STS_ID (STS_ID)";
501
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
502
-        $table_name = 'esp_venue_meta';
503
-        $sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
501
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
502
+		$table_name = 'esp_venue_meta';
503
+		$sql = "VNUM_ID int(11) NOT NULL AUTO_INCREMENT,
504 504
 			VNU_ID bigint(20) unsigned NOT NULL DEFAULT 0,
505 505
 			VNU_address varchar(255) DEFAULT NULL,
506 506
 			VNU_address2 varchar(255) DEFAULT NULL,
@@ -519,10 +519,10 @@  discard block
 block discarded – undo
519 519
 			KEY VNU_ID (VNU_ID),
520 520
 			KEY STA_ID (STA_ID),
521 521
 			KEY CNT_ISO (CNT_ISO)";
522
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
523
-        //modified tables
524
-        $table_name = "esp_price";
525
-        $sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
522
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
523
+		//modified tables
524
+		$table_name = "esp_price";
525
+		$sql = "PRC_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
526 526
 				PRT_ID tinyint(3) unsigned NOT NULL,
527 527
 				PRC_amount decimal(12,3) NOT NULL DEFAULT '0.00',
528 528
 				PRC_name varchar(245) NOT NULL,
@@ -535,9 +535,9 @@  discard block
 block discarded – undo
535 535
 				PRC_parent int(10) unsigned DEFAULT 0,
536 536
 				PRIMARY KEY  (PRC_ID),
537 537
 				KEY PRT_ID (PRT_ID)";
538
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
539
-        $table_name = "esp_price_type";
540
-        $sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
538
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
539
+		$table_name = "esp_price_type";
540
+		$sql = "PRT_ID tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
541 541
 				PRT_name varchar(45) NOT NULL,
542 542
 				PBT_ID tinyint(3) unsigned NOT NULL DEFAULT '1',
543 543
 				PRT_is_percent tinyint(1) NOT NULL DEFAULT '0',
@@ -546,9 +546,9 @@  discard block
 block discarded – undo
546 546
 				PRT_deleted tinyint(1) NOT NULL DEFAULT '0',
547 547
 				UNIQUE KEY PRT_name_UNIQUE (PRT_name),
548 548
 				PRIMARY KEY  (PRT_ID)";
549
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
550
-        $table_name = "esp_ticket";
551
-        $sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
549
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB ');
550
+		$table_name = "esp_ticket";
551
+		$sql = "TKT_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
552 552
 				TTM_ID int(10) unsigned NOT NULL,
553 553
 				TKT_name varchar(245) NOT NULL DEFAULT '',
554 554
 				TKT_description text NOT NULL,
@@ -571,9 +571,9 @@  discard block
 block discarded – undo
571 571
 				TKT_deleted tinyint(1) NOT NULL DEFAULT '0',
572 572
 				PRIMARY KEY  (TKT_ID),
573 573
 				KEY TKT_start_date (TKT_start_date)";
574
-        $this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
575
-        $table_name = 'esp_question_group';
576
-        $sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
574
+		$this->_table_is_changed_in_this_version($table_name, $sql, 'ENGINE=InnoDB');
575
+		$table_name = 'esp_question_group';
576
+		$sql = 'QSG_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
577 577
 				QSG_name varchar(255) NOT NULL,
578 578
 				QSG_identifier varchar(100) NOT NULL,
579 579
 				QSG_desc text NULL,
@@ -586,145 +586,145 @@  discard block
 block discarded – undo
586 586
 				PRIMARY KEY  (QSG_ID),
587 587
 				UNIQUE KEY QSG_identifier_UNIQUE (QSG_identifier),
588 588
 				KEY QSG_order (QSG_order)';
589
-        $this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
590
-        /** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
591
-        $script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
592
-        //(because many need to convert old string states to foreign keys into the states table)
593
-        $script_4_1_defaults->insert_default_states();
594
-        $script_4_1_defaults->insert_default_countries();
595
-        /** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
596
-        $script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
597
-        $script_4_5_defaults->insert_default_price_types();
598
-        $script_4_5_defaults->insert_default_prices();
599
-        $script_4_5_defaults->insert_default_tickets();
600
-        /** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
601
-        $script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
602
-        $script_4_6_defaults->add_default_admin_only_payments();
603
-        $script_4_6_defaults->insert_default_currencies();
604
-        /** @var EE_DMS_Core_4_8_0 $script_4_8_defaults */
605
-        $script_4_8_defaults = EE_Registry::instance()->load_dms('Core_4_8_0');
606
-        $script_4_8_defaults->verify_new_countries();
607
-        $script_4_8_defaults->verify_new_currencies();
608
-        $this->verify_db_collations();
609
-        $this->verify_db_collations_again();
610
-        return true;
611
-    }
589
+		$this->_table_has_not_changed_since_previous($table_name, $sql, 'ENGINE=InnoDB');
590
+		/** @var EE_DMS_Core_4_1_0 $script_4_1_defaults */
591
+		$script_4_1_defaults = EE_Registry::instance()->load_dms('Core_4_1_0');
592
+		//(because many need to convert old string states to foreign keys into the states table)
593
+		$script_4_1_defaults->insert_default_states();
594
+		$script_4_1_defaults->insert_default_countries();
595
+		/** @var EE_DMS_Core_4_5_0 $script_4_5_defaults */
596
+		$script_4_5_defaults = EE_Registry::instance()->load_dms('Core_4_5_0');
597
+		$script_4_5_defaults->insert_default_price_types();
598
+		$script_4_5_defaults->insert_default_prices();
599
+		$script_4_5_defaults->insert_default_tickets();
600
+		/** @var EE_DMS_Core_4_6_0 $script_4_6_defaults */
601
+		$script_4_6_defaults = EE_Registry::instance()->load_dms('Core_4_6_0');
602
+		$script_4_6_defaults->add_default_admin_only_payments();
603
+		$script_4_6_defaults->insert_default_currencies();
604
+		/** @var EE_DMS_Core_4_8_0 $script_4_8_defaults */
605
+		$script_4_8_defaults = EE_Registry::instance()->load_dms('Core_4_8_0');
606
+		$script_4_8_defaults->verify_new_countries();
607
+		$script_4_8_defaults->verify_new_currencies();
608
+		$this->verify_db_collations();
609
+		$this->verify_db_collations_again();
610
+		return true;
611
+	}
612 612
 
613 613
 
614 614
 
615
-    /**
616
-     * @return boolean
617
-     */
618
-    public function schema_changes_after_migration()
619
-    {
620
-        return true;
621
-    }
615
+	/**
616
+	 * @return boolean
617
+	 */
618
+	public function schema_changes_after_migration()
619
+	{
620
+		return true;
621
+	}
622 622
 
623 623
 
624 624
 
625
-    public function migration_page_hooks()
626
-    {
627
-    }
625
+	public function migration_page_hooks()
626
+	{
627
+	}
628 628
 
629 629
 
630 630
 
631
-    /**
632
-     * Verify all EE4 models' tables use utf8mb4 collation
633
-     *
634
-     * @return void
635
-     */
636
-    public function verify_db_collations()
637
-    {
638
-        global $wpdb;
639
-        //double-check we haven't already done it or that that the DB doesn't support utf8mb4
640
-        if ('utf8mb4' !== $wpdb->charset
641
-            || get_option('ee_verified_db_collations', false)) {
642
-            return;
643
-        }
644
-        // grab tables from each model
645
-        $tables_to_check = array();
646
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
647
-            if (method_exists($model_name, 'instance')) {
648
-                $model_obj = call_user_func(array($model_name, 'instance'));
649
-                if ($model_obj instanceof EEM_Base) {
650
-                    foreach ($model_obj->get_tables() as $table) {
651
-                        if (
652
-                            strpos($table->get_table_name(), 'esp_')
653
-                            && (is_main_site()//for main tables, verify global tables
654
-                                || ! $table->is_global()//if not the main site, then only verify non-global tables (avoid doubling up)
655
-                            )
656
-                            && function_exists('maybe_convert_table_to_utf8mb4')
657
-                        ) {
658
-                            $tables_to_check[] = $table->get_table_name();
659
-                        }
660
-                    }
661
-                }
662
-            }
663
-        }
664
-        //and let's just be sure these addons' tables get migrated too. They already get handled if their addons are active
665
-        //when this code is run, but not otherwise. Once we record what tables EE added, we'll be able to use that instead
666
-        //of hard-coding this
667
-        $addon_tables = array(
668
-            //mailchimp
669
-            'esp_event_mailchimp_list_group',
670
-            'esp_event_question_mailchimp_field',
671
-            //multisite
672
-            'esp_blog_meta',
673
-            //people
674
-            'esp_people_to_post',
675
-            //promotions
676
-            'esp_promotion',
677
-            'esp_promotion_object',
678
-        );
679
-        foreach ($addon_tables as $table_name) {
680
-                $tables_to_check[] = $table_name;
681
-        }
682
-        $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
683
-        //ok and now let's remember this was done (without needing to check the db schemas all over again)
684
-        add_option('ee_verified_db_collations', true, null, 'no');
685
-        //seeing how this ran with the fix from 10435, no need to check again
686
-        add_option('ee_verified_db_collations_again',true,null,'no');
687
-    }
631
+	/**
632
+	 * Verify all EE4 models' tables use utf8mb4 collation
633
+	 *
634
+	 * @return void
635
+	 */
636
+	public function verify_db_collations()
637
+	{
638
+		global $wpdb;
639
+		//double-check we haven't already done it or that that the DB doesn't support utf8mb4
640
+		if ('utf8mb4' !== $wpdb->charset
641
+			|| get_option('ee_verified_db_collations', false)) {
642
+			return;
643
+		}
644
+		// grab tables from each model
645
+		$tables_to_check = array();
646
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
647
+			if (method_exists($model_name, 'instance')) {
648
+				$model_obj = call_user_func(array($model_name, 'instance'));
649
+				if ($model_obj instanceof EEM_Base) {
650
+					foreach ($model_obj->get_tables() as $table) {
651
+						if (
652
+							strpos($table->get_table_name(), 'esp_')
653
+							&& (is_main_site()//for main tables, verify global tables
654
+								|| ! $table->is_global()//if not the main site, then only verify non-global tables (avoid doubling up)
655
+							)
656
+							&& function_exists('maybe_convert_table_to_utf8mb4')
657
+						) {
658
+							$tables_to_check[] = $table->get_table_name();
659
+						}
660
+					}
661
+				}
662
+			}
663
+		}
664
+		//and let's just be sure these addons' tables get migrated too. They already get handled if their addons are active
665
+		//when this code is run, but not otherwise. Once we record what tables EE added, we'll be able to use that instead
666
+		//of hard-coding this
667
+		$addon_tables = array(
668
+			//mailchimp
669
+			'esp_event_mailchimp_list_group',
670
+			'esp_event_question_mailchimp_field',
671
+			//multisite
672
+			'esp_blog_meta',
673
+			//people
674
+			'esp_people_to_post',
675
+			//promotions
676
+			'esp_promotion',
677
+			'esp_promotion_object',
678
+		);
679
+		foreach ($addon_tables as $table_name) {
680
+				$tables_to_check[] = $table_name;
681
+		}
682
+		$this->_verify_db_collations_for_tables(array_unique($tables_to_check));
683
+		//ok and now let's remember this was done (without needing to check the db schemas all over again)
684
+		add_option('ee_verified_db_collations', true, null, 'no');
685
+		//seeing how this ran with the fix from 10435, no need to check again
686
+		add_option('ee_verified_db_collations_again',true,null,'no');
687
+	}
688 688
 
689 689
 
690 690
 
691
-    /**
692
-     * Verifies DB collations because a bug was discovered on https://events.codebasehq.com/projects/event-espresso/tickets/10435
693
-     * which meant some DB collations might not have been updated
694
-     * @return void
695
-     */
696
-    public function verify_db_collations_again(){
697
-        global $wpdb;
698
-        //double-check we haven't already done this or that the DB doesn't support it
699
-        //compare to how WordPress' upgrade_430() function does this check
700
-        if ('utf8mb4' !== $wpdb->charset
701
-            || get_option('ee_verified_db_collations_again', false)) {
702
-            return;
703
-        }
704
-        $tables_to_check = array(
705
-            'esp_attendee_meta',
706
-            'esp_message'
707
-        );
708
-        $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
709
-        add_option('ee_verified_db_collations_again',true,null,'no');
710
-    }
691
+	/**
692
+	 * Verifies DB collations because a bug was discovered on https://events.codebasehq.com/projects/event-espresso/tickets/10435
693
+	 * which meant some DB collations might not have been updated
694
+	 * @return void
695
+	 */
696
+	public function verify_db_collations_again(){
697
+		global $wpdb;
698
+		//double-check we haven't already done this or that the DB doesn't support it
699
+		//compare to how WordPress' upgrade_430() function does this check
700
+		if ('utf8mb4' !== $wpdb->charset
701
+			|| get_option('ee_verified_db_collations_again', false)) {
702
+			return;
703
+		}
704
+		$tables_to_check = array(
705
+			'esp_attendee_meta',
706
+			'esp_message'
707
+		);
708
+		$this->_verify_db_collations_for_tables(array_unique($tables_to_check));
709
+		add_option('ee_verified_db_collations_again',true,null,'no');
710
+	}
711 711
 
712 712
 
713 713
 
714
-    /**
715
-     * Runs maybe_convert_table_to_utf8mb4 on the specified tables
716
-     * @param $tables_to_check
717
-     * @return boolean true if logic ran, false if it didn't
718
-     */
719
-    protected function _verify_db_collations_for_tables($tables_to_check)
720
-    {
721
-        foreach ($tables_to_check as $table_name) {
722
-            $table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
723
-            if ( ! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name )
724
-                && $this->_get_table_analysis()->tableExists($table_name)
725
-            ) {
726
-                maybe_convert_table_to_utf8mb4($table_name);
727
-            }
728
-        }
729
-    }
714
+	/**
715
+	 * Runs maybe_convert_table_to_utf8mb4 on the specified tables
716
+	 * @param $tables_to_check
717
+	 * @return boolean true if logic ran, false if it didn't
718
+	 */
719
+	protected function _verify_db_collations_for_tables($tables_to_check)
720
+	{
721
+		foreach ($tables_to_check as $table_name) {
722
+			$table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
723
+			if ( ! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name )
724
+				&& $this->_get_table_analysis()->tableExists($table_name)
725
+			) {
726
+				maybe_convert_table_to_utf8mb4($table_name);
727
+			}
728
+		}
729
+	}
730 730
 }
731 731
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -9,7 +9,7 @@  discard block
 block discarded – undo
9 9
 //unfortunately, this needs to be done upon INCLUSION of this file,
10 10
 //instead of construction, because it only gets constructed on first page load
11 11
 //(all other times it gets resurrected from a wordpress option)
12
-$stages = glob(EE_CORE . 'data_migration_scripts/4_9_0_stages/*');
12
+$stages = glob(EE_CORE.'data_migration_scripts/4_9_0_stages/*');
13 13
 $class_to_filepath = array();
14 14
 foreach ($stages as $filepath) {
15 15
     $matches = array();
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
         } elseif ( ! $version_string) {
68 68
             //			echo "no version string provided: $version_string";
69 69
             //no version string provided... this must be pre 4.3
70
-            return false;//changed mind. dont want people thinking they should migrate yet because they cant
70
+            return false; //changed mind. dont want people thinking they should migrate yet because they cant
71 71
         } else {
72 72
             //			echo "$version_string doesnt apply";
73 73
             return false;
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
      */
82 82
     public function schema_changes_before_migration()
83 83
     {
84
-        require_once(EE_HELPERS . 'EEH_Activation.helper.php');
84
+        require_once(EE_HELPERS.'EEH_Activation.helper.php');
85 85
         $now_in_mysql = current_time('mysql', true);
86 86
         $table_name = 'esp_answer';
87 87
         $sql = " ANS_ID int(10) unsigned NOT NULL AUTO_INCREMENT,
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
         //ok and now let's remember this was done (without needing to check the db schemas all over again)
684 684
         add_option('ee_verified_db_collations', true, null, 'no');
685 685
         //seeing how this ran with the fix from 10435, no need to check again
686
-        add_option('ee_verified_db_collations_again',true,null,'no');
686
+        add_option('ee_verified_db_collations_again', true, null, 'no');
687 687
     }
688 688
 
689 689
 
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
      * which meant some DB collations might not have been updated
694 694
      * @return void
695 695
      */
696
-    public function verify_db_collations_again(){
696
+    public function verify_db_collations_again() {
697 697
         global $wpdb;
698 698
         //double-check we haven't already done this or that the DB doesn't support it
699 699
         //compare to how WordPress' upgrade_430() function does this check
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
             'esp_message'
707 707
         );
708 708
         $this->_verify_db_collations_for_tables(array_unique($tables_to_check));
709
-        add_option('ee_verified_db_collations_again',true,null,'no');
709
+        add_option('ee_verified_db_collations_again', true, null, 'no');
710 710
     }
711 711
 
712 712
 
@@ -720,7 +720,7 @@  discard block
 block discarded – undo
720 720
     {
721 721
         foreach ($tables_to_check as $table_name) {
722 722
             $table_name = $this->_table_analysis->ensureTableNameHasPrefix($table_name);
723
-            if ( ! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name )
723
+            if ( ! apply_filters('FHEE__EE_DMS_Core_4_9_0__verify_db_collations__check_overridden', false, $table_name)
724 724
                 && $this->_get_table_analysis()->tableExists($table_name)
725 725
             ) {
726 726
                 maybe_convert_table_to_utf8mb4($table_name);
Please login to merge, or discard this patch.
core/EE_PUE.core.php 2 patches
Indentation   +420 added lines, -420 removed lines patch added patch discarded remove patch
@@ -17,247 +17,247 @@  discard block
 block discarded – undo
17 17
 {
18 18
 
19 19
 
20
-    /**
21
-     *    class constructor
22
-     *
23
-     * @access public
24
-     */
25
-    public function __construct()
26
-    {
20
+	/**
21
+	 *    class constructor
22
+	 *
23
+	 * @access public
24
+	 */
25
+	public function __construct()
26
+	{
27 27
 //		throw new EE_Error('error');
28 28
 
29
-        do_action('AHEE_log', __CLASS__, __FUNCTION__);
30
-
31
-        //wp have no MONTH_IN_SECONDS constant.  So we approximate our own assuming all months are 4 weeks long.
32
-        if (! defined('MONTH_IN_SECONDS')) {
33
-            define('MONTH_IN_SECONDS', WEEK_IN_SECONDS * 4);
34
-        }
35
-
36
-        if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
37
-            $this->_uxip_hooks();
38
-        }
39
-
40
-
41
-        $ueip_optin        = EE_Registry::instance()->CFG->core->ee_ueip_optin;
42
-        $ueip_has_notified = EE_Registry::instance()->CFG->core->ee_ueip_has_notified;
43
-
44
-        //has optin been selected for data collection?
45
-        $espresso_data_optin = ! empty($ueip_optin) ? $ueip_optin : null;
46
-
47
-        if (empty($ueip_has_notified)
48
-            && EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance
49
-        ) {
50
-            add_action('admin_notices', array($this, 'espresso_data_collection_optin_notice'), 10);
51
-            add_action('admin_enqueue_scripts', array($this, 'espresso_data_collection_enqueue_scripts'), 10);
52
-            add_action('wp_ajax_espresso_data_optin', array($this, 'espresso_data_optin_ajax_handler'), 10);
53
-            update_option('ee_ueip_optin', 'yes');
54
-            $espresso_data_optin = 'yes';
55
-        }
56
-
57
-        //let's prepare extra stats
58
-        $extra_stats = array();
59
-
60
-        //only collect extra stats if the plugin user has opted in and transient is expired.
61
-        if (! empty($espresso_data_optin) && $espresso_data_optin == 'yes') {
62
-            if (false === ($transient = get_transient('ee_extra_data'))
63
-                && EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance
64
-            ) {
65
-
66
-                $current_site = is_multisite() ? get_current_site() : null;
67
-                $site_pre     = ! is_main_site() && ! empty($current_site)
68
-                    ? trim(
69
-                        preg_replace('/\b\w\S\w\b/', '', $current_site->domain),
70
-                        '.'
71
-                    ) . '_'
72
-                    : '';
73
-
74
-
75
-                //active gateways
76
-                $active_gateways = get_option('event_espresso_active_gateways');
77
-                if (! empty($active_gateways)) {
78
-                    foreach ((array)$active_gateways as $gateway => $ignore) {
79
-                        $extra_stats[$site_pre . $gateway . '_gateway_active'] = 1;
80
-                    }
81
-                }
82
-
83
-                if (is_multisite() && is_main_site()) {
84
-                    $extra_stats['is_multisite'] = true;
85
-                }
86
-
87
-                //what is the current active theme?
88
-                $active_theme = get_option('uxip_ee_active_theme');
89
-                if (! empty($active_theme)) {
90
-                    $extra_stats[$site_pre . 'active_theme'] = $active_theme;
91
-                }
92
-
93
-                //event info regarding an all event count and all "active" event count
94
-                $all_events_count = get_option('uxip_ee4_all_events_count');
95
-                if (! empty($all_events_count)) {
96
-                    $extra_stats[$site_pre . 'ee4_all_events_count'] = $all_events_count;
97
-                }
98
-                $active_events_count = get_option('uxip_ee4_active_events_count');
99
-                if (! empty($active_events_count)) {
100
-                    $extra_stats[$site_pre . 'ee4_active_events_count'] = $active_events_count;
101
-                }
102
-
103
-                //datetime stuff
104
-                $dtt_count = get_option('uxip_ee_all_dtts_count');
105
-                if (! empty($dtt_count)) {
106
-                    $extra_stats[$site_pre . 'all_dtts_count'] = $dtt_count;
107
-                }
108
-
109
-                $dtt_sold = get_option('uxip_ee_dtt_sold');
110
-                if (! empty($dtt_sold)) {
111
-                    $extra_stats[$site_pre . 'dtt_sold'] = $dtt_sold;
112
-                }
113
-
114
-                //ticket stuff
115
-                $all_tkt_count = get_option('uxip_ee_all_tkt_count');
116
-                if (! empty($all_tkt_count)) {
117
-                    $extra_stats[$site_pre . 'all_tkt_count'] = $all_tkt_count;
118
-                }
119
-
120
-                $free_tkt_count = get_option('uxip_ee_free_tkt_count');
121
-                if (! empty($free_tkt_count)) {
122
-                    $extra_stats[$site_pre . 'free_tkt_count'] = $free_tkt_count;
123
-                }
124
-
125
-                $paid_tkt_count = get_option('uxip_ee_paid_tkt_count');
126
-                if (! empty($paid_tkt_count)) {
127
-                    $extra_stats[$site_pre . 'paid_tkt_count'] = $paid_tkt_count;
128
-                }
129
-
130
-                $tkt_sold = get_option('uxip_ee_tkt_sold');
131
-                if (! empty($tkt_sold)) {
132
-                    $extra_stats[$site_pre . 'tkt_sold'] = $tkt_sold;
133
-                }
134
-
135
-                //phpversion checking
136
-                $extra_stats['phpversion'] = function_exists('phpversion') ? phpversion() : 'unknown';
137
-
138
-                //set transient
139
-                set_transient('ee_extra_data', $extra_stats, WEEK_IN_SECONDS);
140
-            }
141
-        }
142
-
143
-
144
-        // PUE Auto Upgrades stuff
145
-        if (is_readable(EE_THIRD_PARTY . 'pue/pue-client.php')) { //include the file
146
-            require_once(EE_THIRD_PARTY . 'pue/pue-client.php');
147
-
148
-            $api_key         = isset(EE_Registry::instance()->NET_CFG->core->site_license_key)
149
-                ? EE_Registry::instance()->NET_CFG->core->site_license_key
150
-                : '';
151
-            //this needs to be the host server where plugin update engine is installed. Note, if you leave this blank
152
-            // then it is assumed the WordPress repo will be used and we'll just check there.
153
-            $host_server_url = 'https://eventespresso.com';
154
-
155
-            //Note: PUE uses a simple preg_match to determine what type is currently installed based on version number.
156
-            //  So it's important that you use a key for the version type that is unique and not found in another key.
157
-            //For example:
158
-            //$plugin_slug['premium']['p'] = 'some-premium-slug';
159
-            //$plugin_slug['prerelease']['pr'] = 'some-pre-release-slug';
160
-            //The above would not work because "p" is found in both keys for the version type. ( i.e 1.0.p vs 1.0.pr )
161
-            // so doing something like:
162
-            //$plugin_slug['premium']['p'] = 'some-premium-slug';
163
-            //$plugin_slug['prerelease']['b'] = 'some-pre-release-slug';
164
-            //..WOULD work!
165
-            $plugin_slug = array(
166
-                'free'       => array('decaf' => 'event-espresso-core-decaf'),
167
-                'premium'    => array('p' => 'event-espresso-core-reg'),
168
-                'prerelease' => array('beta' => 'event-espresso-core-pr'),
169
-            );
170
-
171
-
172
-            //$options needs to be an array with the included keys as listed.
173
-            $options = array(
174
-                //	'optionName' => '', //(optional) - used as the reference for saving update information in the
175
-                // clients options table.  Will be automatically set if left blank.
176
-                'apikey'                => $api_key,
177
-                //(required), you will need to obtain the apikey that the client gets from your site and
178
-                // then saves in their sites options table (see 'getting an api-key' below)
179
-                'lang_domain'           => 'event_espresso',
180
-                //(optional) - put here whatever reference you are using for the localization of your plugin (if it's
181
-                // localized).  That way strings in this file will be included in the translation for your plugin.
182
-                'checkPeriod'           => '24',
183
-                //(optional) - use this parameter to indicate how often you want the client's install to ping your
184
-                // server for update checks.  The integer indicates hours.  If you don't include this parameter it will
185
-                // default to 12 hours.
186
-                'option_key'            => 'site_license_key',
187
-                //this is what is used to reference the api_key in your plugin options.  PUE uses this to trigger
188
-                // updating your information message whenever this option_key is modified.
189
-                'options_page_slug'     => 'espresso_general_settings',
190
-                'plugin_basename'       => EE_PLUGIN_BASENAME,
191
-                'use_wp_update'         => true,
192
-                //if TRUE then you want FREE versions of the plugin to be updated from WP
193
-                'extra_stats'           => $extra_stats,
194
-                'turn_on_notices_saved' => true,
195
-            );
196
-            //initiate the class and start the plugin update engine!
197
-            new PluginUpdateEngineChecker($host_server_url, $plugin_slug, $options);
198
-        }
199
-    }
200
-
201
-
202
-    /**
203
-     * The purpose of this function is to display information about Event Espresso data collection
204
-     * and a optin selection for extra data collecting by users.
205
-     *
206
-     * @param bool $extra
207
-     * @return string html.
208
-     */
209
-    public static function espresso_data_collection_optin_text($extra = true)
210
-    {
211
-        if (! $extra) {
212
-            echo '<h2 class="ee-admin-settings-hdr" '
213
-                 . (! $extra ? 'id="UXIP_settings"' : '')
214
-                 . '>'
215
-                 . esc_html__('User eXperience Improvement Program (UXIP)', 'event_espresso')
216
-                 . EEH_Template::get_help_tab_link('organization_logo_info')
217
-                 . '</h2>';
218
-            printf(
219
-                esc_html__(
220
-                    '%sPlease help us make Event Espresso better and vote for your favorite features.%s The %sUser eXperience Improvement Program (UXIP)%s, has been created so when you use Event Espresso you are voting for the features and settings that are important to you. The UXIP helps us understand how you use our products and services, track problems and in what context. If you opt-out of the UXIP you essentially elect for us to disregard how you use Event Espresso as we build new features and make changes. Participation in the program is completely voluntary but it is enabled by default. The end results of the UXIP are software improvements to better meet your needs. The data we collect will never be sold, traded, or misused in any way. %sPlease see our %sPrivacy Policy%s for more information.',
221
-                    'event_espresso'
222
-                ),
223
-                '<p><em>',
224
-                '</em></p>',
225
-                '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
226
-                '</a>',
227
-                '<br><br>',
228
-                '<a href="https://eventespresso.com/about/privacy-policy/" target="_blank">',
229
-                '</a>'
230
-            );
231
-        } else {
232
-            $settings_url = EE_Admin_Page::add_query_args_and_nonce(
233
-                array('action' => 'default'),
234
-                admin_url('admin.php?page=espresso_general_settings')
235
-            );
236
-            $settings_url .= '#UXIP_settings';
237
-            printf(
238
-                esc_html__(
239
-                    'The Event Espresso UXIP feature is active on your site. For %smore info%s and to opt-out %sclick here%s.',
240
-                    'event_espresso'
241
-                ),
242
-                '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
243
-                '</a>',
244
-                '<a href="' . $settings_url . '" target="_blank">',
245
-                '</a>'
246
-            );
247
-        }
248
-    }
249
-
250
-
251
-    public function espresso_data_collection_optin_notice()
252
-    {
253
-        $ueip_has_notified = EE_Registry::instance()->CFG->core->ee_ueip_has_notified;
254
-        if ($ueip_has_notified) {
255
-            return;
256
-        }
257
-        // $settings_url = EE_Admin_Page::add_query_args_and_nonce( array( 'action' => 'default'),
258
-        // admin_url( 'admin.php?page=espresso_general_settings') );
259
-        // $settings_url = $settings_url . '#UXIP_settings';
260
-        ?>
29
+		do_action('AHEE_log', __CLASS__, __FUNCTION__);
30
+
31
+		//wp have no MONTH_IN_SECONDS constant.  So we approximate our own assuming all months are 4 weeks long.
32
+		if (! defined('MONTH_IN_SECONDS')) {
33
+			define('MONTH_IN_SECONDS', WEEK_IN_SECONDS * 4);
34
+		}
35
+
36
+		if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
37
+			$this->_uxip_hooks();
38
+		}
39
+
40
+
41
+		$ueip_optin        = EE_Registry::instance()->CFG->core->ee_ueip_optin;
42
+		$ueip_has_notified = EE_Registry::instance()->CFG->core->ee_ueip_has_notified;
43
+
44
+		//has optin been selected for data collection?
45
+		$espresso_data_optin = ! empty($ueip_optin) ? $ueip_optin : null;
46
+
47
+		if (empty($ueip_has_notified)
48
+			&& EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance
49
+		) {
50
+			add_action('admin_notices', array($this, 'espresso_data_collection_optin_notice'), 10);
51
+			add_action('admin_enqueue_scripts', array($this, 'espresso_data_collection_enqueue_scripts'), 10);
52
+			add_action('wp_ajax_espresso_data_optin', array($this, 'espresso_data_optin_ajax_handler'), 10);
53
+			update_option('ee_ueip_optin', 'yes');
54
+			$espresso_data_optin = 'yes';
55
+		}
56
+
57
+		//let's prepare extra stats
58
+		$extra_stats = array();
59
+
60
+		//only collect extra stats if the plugin user has opted in and transient is expired.
61
+		if (! empty($espresso_data_optin) && $espresso_data_optin == 'yes') {
62
+			if (false === ($transient = get_transient('ee_extra_data'))
63
+				&& EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance
64
+			) {
65
+
66
+				$current_site = is_multisite() ? get_current_site() : null;
67
+				$site_pre     = ! is_main_site() && ! empty($current_site)
68
+					? trim(
69
+						preg_replace('/\b\w\S\w\b/', '', $current_site->domain),
70
+						'.'
71
+					) . '_'
72
+					: '';
73
+
74
+
75
+				//active gateways
76
+				$active_gateways = get_option('event_espresso_active_gateways');
77
+				if (! empty($active_gateways)) {
78
+					foreach ((array)$active_gateways as $gateway => $ignore) {
79
+						$extra_stats[$site_pre . $gateway . '_gateway_active'] = 1;
80
+					}
81
+				}
82
+
83
+				if (is_multisite() && is_main_site()) {
84
+					$extra_stats['is_multisite'] = true;
85
+				}
86
+
87
+				//what is the current active theme?
88
+				$active_theme = get_option('uxip_ee_active_theme');
89
+				if (! empty($active_theme)) {
90
+					$extra_stats[$site_pre . 'active_theme'] = $active_theme;
91
+				}
92
+
93
+				//event info regarding an all event count and all "active" event count
94
+				$all_events_count = get_option('uxip_ee4_all_events_count');
95
+				if (! empty($all_events_count)) {
96
+					$extra_stats[$site_pre . 'ee4_all_events_count'] = $all_events_count;
97
+				}
98
+				$active_events_count = get_option('uxip_ee4_active_events_count');
99
+				if (! empty($active_events_count)) {
100
+					$extra_stats[$site_pre . 'ee4_active_events_count'] = $active_events_count;
101
+				}
102
+
103
+				//datetime stuff
104
+				$dtt_count = get_option('uxip_ee_all_dtts_count');
105
+				if (! empty($dtt_count)) {
106
+					$extra_stats[$site_pre . 'all_dtts_count'] = $dtt_count;
107
+				}
108
+
109
+				$dtt_sold = get_option('uxip_ee_dtt_sold');
110
+				if (! empty($dtt_sold)) {
111
+					$extra_stats[$site_pre . 'dtt_sold'] = $dtt_sold;
112
+				}
113
+
114
+				//ticket stuff
115
+				$all_tkt_count = get_option('uxip_ee_all_tkt_count');
116
+				if (! empty($all_tkt_count)) {
117
+					$extra_stats[$site_pre . 'all_tkt_count'] = $all_tkt_count;
118
+				}
119
+
120
+				$free_tkt_count = get_option('uxip_ee_free_tkt_count');
121
+				if (! empty($free_tkt_count)) {
122
+					$extra_stats[$site_pre . 'free_tkt_count'] = $free_tkt_count;
123
+				}
124
+
125
+				$paid_tkt_count = get_option('uxip_ee_paid_tkt_count');
126
+				if (! empty($paid_tkt_count)) {
127
+					$extra_stats[$site_pre . 'paid_tkt_count'] = $paid_tkt_count;
128
+				}
129
+
130
+				$tkt_sold = get_option('uxip_ee_tkt_sold');
131
+				if (! empty($tkt_sold)) {
132
+					$extra_stats[$site_pre . 'tkt_sold'] = $tkt_sold;
133
+				}
134
+
135
+				//phpversion checking
136
+				$extra_stats['phpversion'] = function_exists('phpversion') ? phpversion() : 'unknown';
137
+
138
+				//set transient
139
+				set_transient('ee_extra_data', $extra_stats, WEEK_IN_SECONDS);
140
+			}
141
+		}
142
+
143
+
144
+		// PUE Auto Upgrades stuff
145
+		if (is_readable(EE_THIRD_PARTY . 'pue/pue-client.php')) { //include the file
146
+			require_once(EE_THIRD_PARTY . 'pue/pue-client.php');
147
+
148
+			$api_key         = isset(EE_Registry::instance()->NET_CFG->core->site_license_key)
149
+				? EE_Registry::instance()->NET_CFG->core->site_license_key
150
+				: '';
151
+			//this needs to be the host server where plugin update engine is installed. Note, if you leave this blank
152
+			// then it is assumed the WordPress repo will be used and we'll just check there.
153
+			$host_server_url = 'https://eventespresso.com';
154
+
155
+			//Note: PUE uses a simple preg_match to determine what type is currently installed based on version number.
156
+			//  So it's important that you use a key for the version type that is unique and not found in another key.
157
+			//For example:
158
+			//$plugin_slug['premium']['p'] = 'some-premium-slug';
159
+			//$plugin_slug['prerelease']['pr'] = 'some-pre-release-slug';
160
+			//The above would not work because "p" is found in both keys for the version type. ( i.e 1.0.p vs 1.0.pr )
161
+			// so doing something like:
162
+			//$plugin_slug['premium']['p'] = 'some-premium-slug';
163
+			//$plugin_slug['prerelease']['b'] = 'some-pre-release-slug';
164
+			//..WOULD work!
165
+			$plugin_slug = array(
166
+				'free'       => array('decaf' => 'event-espresso-core-decaf'),
167
+				'premium'    => array('p' => 'event-espresso-core-reg'),
168
+				'prerelease' => array('beta' => 'event-espresso-core-pr'),
169
+			);
170
+
171
+
172
+			//$options needs to be an array with the included keys as listed.
173
+			$options = array(
174
+				//	'optionName' => '', //(optional) - used as the reference for saving update information in the
175
+				// clients options table.  Will be automatically set if left blank.
176
+				'apikey'                => $api_key,
177
+				//(required), you will need to obtain the apikey that the client gets from your site and
178
+				// then saves in their sites options table (see 'getting an api-key' below)
179
+				'lang_domain'           => 'event_espresso',
180
+				//(optional) - put here whatever reference you are using for the localization of your plugin (if it's
181
+				// localized).  That way strings in this file will be included in the translation for your plugin.
182
+				'checkPeriod'           => '24',
183
+				//(optional) - use this parameter to indicate how often you want the client's install to ping your
184
+				// server for update checks.  The integer indicates hours.  If you don't include this parameter it will
185
+				// default to 12 hours.
186
+				'option_key'            => 'site_license_key',
187
+				//this is what is used to reference the api_key in your plugin options.  PUE uses this to trigger
188
+				// updating your information message whenever this option_key is modified.
189
+				'options_page_slug'     => 'espresso_general_settings',
190
+				'plugin_basename'       => EE_PLUGIN_BASENAME,
191
+				'use_wp_update'         => true,
192
+				//if TRUE then you want FREE versions of the plugin to be updated from WP
193
+				'extra_stats'           => $extra_stats,
194
+				'turn_on_notices_saved' => true,
195
+			);
196
+			//initiate the class and start the plugin update engine!
197
+			new PluginUpdateEngineChecker($host_server_url, $plugin_slug, $options);
198
+		}
199
+	}
200
+
201
+
202
+	/**
203
+	 * The purpose of this function is to display information about Event Espresso data collection
204
+	 * and a optin selection for extra data collecting by users.
205
+	 *
206
+	 * @param bool $extra
207
+	 * @return string html.
208
+	 */
209
+	public static function espresso_data_collection_optin_text($extra = true)
210
+	{
211
+		if (! $extra) {
212
+			echo '<h2 class="ee-admin-settings-hdr" '
213
+				 . (! $extra ? 'id="UXIP_settings"' : '')
214
+				 . '>'
215
+				 . esc_html__('User eXperience Improvement Program (UXIP)', 'event_espresso')
216
+				 . EEH_Template::get_help_tab_link('organization_logo_info')
217
+				 . '</h2>';
218
+			printf(
219
+				esc_html__(
220
+					'%sPlease help us make Event Espresso better and vote for your favorite features.%s The %sUser eXperience Improvement Program (UXIP)%s, has been created so when you use Event Espresso you are voting for the features and settings that are important to you. The UXIP helps us understand how you use our products and services, track problems and in what context. If you opt-out of the UXIP you essentially elect for us to disregard how you use Event Espresso as we build new features and make changes. Participation in the program is completely voluntary but it is enabled by default. The end results of the UXIP are software improvements to better meet your needs. The data we collect will never be sold, traded, or misused in any way. %sPlease see our %sPrivacy Policy%s for more information.',
221
+					'event_espresso'
222
+				),
223
+				'<p><em>',
224
+				'</em></p>',
225
+				'<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
226
+				'</a>',
227
+				'<br><br>',
228
+				'<a href="https://eventespresso.com/about/privacy-policy/" target="_blank">',
229
+				'</a>'
230
+			);
231
+		} else {
232
+			$settings_url = EE_Admin_Page::add_query_args_and_nonce(
233
+				array('action' => 'default'),
234
+				admin_url('admin.php?page=espresso_general_settings')
235
+			);
236
+			$settings_url .= '#UXIP_settings';
237
+			printf(
238
+				esc_html__(
239
+					'The Event Espresso UXIP feature is active on your site. For %smore info%s and to opt-out %sclick here%s.',
240
+					'event_espresso'
241
+				),
242
+				'<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
243
+				'</a>',
244
+				'<a href="' . $settings_url . '" target="_blank">',
245
+				'</a>'
246
+			);
247
+		}
248
+	}
249
+
250
+
251
+	public function espresso_data_collection_optin_notice()
252
+	{
253
+		$ueip_has_notified = EE_Registry::instance()->CFG->core->ee_ueip_has_notified;
254
+		if ($ueip_has_notified) {
255
+			return;
256
+		}
257
+		// $settings_url = EE_Admin_Page::add_query_args_and_nonce( array( 'action' => 'default'),
258
+		// admin_url( 'admin.php?page=espresso_general_settings') );
259
+		// $settings_url = $settings_url . '#UXIP_settings';
260
+		?>
261 261
         <div class="updated data-collect-optin" id="espresso-data-collect-optin-container">
262 262
             <div id="data-collect-optin-options-container">
263 263
                 <span class="dashicons dashicons-admin-site"></span>
@@ -270,186 +270,186 @@  discard block
 block discarded – undo
270 270
             </div>
271 271
         </div>
272 272
         <?php
273
-    }
274
-
275
-
276
-    /**
277
-     * enqueue scripts/styles needed for data collection optin
278
-     *
279
-     * @return void
280
-     */
281
-    public function espresso_data_collection_enqueue_scripts()
282
-    {
283
-        wp_register_script(
284
-            'ee-data-optin-js',
285
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-data-optin.js',
286
-            array('jquery'),
287
-            EVENT_ESPRESSO_VERSION,
288
-            true
289
-        );
290
-        wp_register_style(
291
-            'ee-data-optin-css',
292
-            EE_GLOBAL_ASSETS_URL . 'css/ee-data-optin.css',
293
-            array(),
294
-            EVENT_ESPRESSO_VERSION
295
-        );
296
-
297
-        wp_enqueue_script('ee-data-optin-js');
298
-        wp_enqueue_style('ee-data-optin-css');
299
-    }
300
-
301
-
302
-    /**
303
-     * This just handles the setting of the selected option for data optin via ajax
304
-     *
305
-     * @return void
306
-     * @throws InvalidArgumentException
307
-     * @throws InvalidDataTypeException
308
-     * @throws InvalidInterfaceException
309
-     */
310
-    public function espresso_data_optin_ajax_handler()
311
-    {
312
-
313
-        //verify nonce
314
-        if (isset($_POST['nonce']) && ! wp_verify_nonce($_POST['nonce'], 'ee-data-optin')) {
315
-            exit();
316
-        }
317
-
318
-        //update_option('ee_ueip_optin', $ueip_optin);
319
-        EE_Registry::instance()->CFG->core->ee_ueip_has_notified = 1;
320
-        EE_Registry::instance()->CFG->update_espresso_config(false, false);
321
-        exit();
322
-    }
323
-
324
-
325
-    /**
326
-     * This is a handy helper method for retrieving whether there is an update available for the given plugin.
327
-     *
328
-     * @param  string $basename Use the equivalent result from plugin_basename() for this param as WP uses that to
329
-     *                          identify plugins. Defaults to core update
330
-     * @return boolean           True if update available, false if not.
331
-     */
332
-    public static function is_update_available($basename = '')
333
-    {
334
-
335
-        $basename = ! empty($basename) ? $basename : EE_PLUGIN_BASENAME;
336
-
337
-        $update = false;
338
-
339
-        // should take "event-espresso-core/espresso.php" and change to "/event-espresso-core"
340
-        $folder = DS . dirname($basename);
341
-
342
-        $plugins = get_plugins($folder);
343
-        $current = get_site_transient('update_plugins');
344
-
345
-        foreach ((array)$plugins as $plugin_file => $plugin_data) {
346
-            if (isset($current->response['plugin_file'])) {
347
-                $update = true;
348
-            }
349
-        }
350
-
351
-        //it's possible that there is an update but an invalid site-license-key is in use
352
-        if (get_site_option('pue_json_error_' . $basename)) {
353
-            $update = true;
354
-        }
355
-
356
-        return $update;
357
-    }
358
-
359
-
360
-    /**
361
-     * UXIP TRACKING *******
362
-     */
363
-
364
-
365
-    /**
366
-     * This method contains all the hooks into EE for gathering stats that will be reported with the PUE uxip system
367
-     *
368
-     * @public
369
-     * @return void
370
-     */
371
-    public function _uxip_hooks()
372
-    {
373
-        if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
374
-            add_action('admin_init', array($this, 'track_active_theme'));
375
-            add_action('admin_init', array($this, 'track_event_info'));
376
-        }
377
-    }
378
-
379
-
380
-    public function track_active_theme()
381
-    {
382
-        //we only check this once a month.
383
-        if (false === ($transient = get_transient('ee_active_theme_check'))) {
384
-            $theme = wp_get_theme();
385
-            update_option('uxip_ee_active_theme', $theme->get('Name'));
386
-            set_transient('ee_active_theme_check', 1, MONTH_IN_SECONDS);
387
-        }
388
-    }
389
-
390
-
391
-    public function track_event_info()
392
-    {
393
-        //we only check this once every couple weeks.
394
-        if (false === ($transient = get_transient('ee4_event_info_check'))) {
395
-            //first let's get the number for ALL events
396
-            /** @var EEM_Event $EVT */
397
-            $EVT   = EE_Registry::instance()->load_model('Event');
398
-            $DTT   = EE_Registry::instance()->load_model('Datetime');
399
-            $TKT   = EE_Registry::instance()->load_model('Ticket');
400
-            $count = $EVT->count();
401
-            if ($count > 0) {
402
-                update_option('uxip_ee4_all_events_count', $count);
403
-            }
404
-
405
-            //next let's just get the number of ACTIVE events
406
-            $count_active = $EVT->get_active_events(array(), true);
407
-            if ($count_active > 0) {
408
-                update_option('uxip_ee4_active_events_count', $count_active);
409
-            }
410
-
411
-            //datetimes!
412
-            $dtt_count = $DTT->count();
413
-            if ($dtt_count > 0) {
414
-                update_option('uxip_ee_all_dtts_count', $dtt_count);
415
-            }
416
-
417
-
418
-            //dttsold
419
-            $dtt_sold = $DTT->sum(array(), 'DTT_sold');
420
-            if ($dtt_sold > 0) {
421
-                update_option('uxip_ee_dtt_sold', $dtt_sold);
422
-            }
423
-
424
-            //allticketcount
425
-            $all_tkt_count = $TKT->count();
426
-            if ($all_tkt_count > 0) {
427
-                update_option('uxip_ee_all_tkt_count', $all_tkt_count);
428
-            }
429
-
430
-            //freetktcount
431
-            $_where         = array('TKT_price' => 0);
432
-            $free_tkt_count = $TKT->count(array($_where));
433
-            if ($free_tkt_count > 0) {
434
-                update_option('uxip_ee_free_tkt_count', $free_tkt_count);
435
-            }
436
-
437
-            //paidtktcount
438
-            $_where         = array('TKT_price' => array('>', 0));
439
-            $paid_tkt_count = $TKT->count(array($_where));
440
-            if ($paid_tkt_count > 0) {
441
-                update_option('uxip_ee_paid_tkt_count', $paid_tkt_count);
442
-            }
443
-
444
-            //tktsold
445
-            $tkt_sold = $TKT->sum(array(), 'TKT_sold');
446
-            if ($tkt_sold > 0) {
447
-                update_option('uxip_ee_tkt_sold', $tkt_sold);
448
-            }
449
-
450
-
451
-            set_transient('ee4_event_info_check', 1, WEEK_IN_SECONDS * 2);
452
-        }
453
-    }
273
+	}
274
+
275
+
276
+	/**
277
+	 * enqueue scripts/styles needed for data collection optin
278
+	 *
279
+	 * @return void
280
+	 */
281
+	public function espresso_data_collection_enqueue_scripts()
282
+	{
283
+		wp_register_script(
284
+			'ee-data-optin-js',
285
+			EE_GLOBAL_ASSETS_URL . 'scripts/ee-data-optin.js',
286
+			array('jquery'),
287
+			EVENT_ESPRESSO_VERSION,
288
+			true
289
+		);
290
+		wp_register_style(
291
+			'ee-data-optin-css',
292
+			EE_GLOBAL_ASSETS_URL . 'css/ee-data-optin.css',
293
+			array(),
294
+			EVENT_ESPRESSO_VERSION
295
+		);
296
+
297
+		wp_enqueue_script('ee-data-optin-js');
298
+		wp_enqueue_style('ee-data-optin-css');
299
+	}
300
+
301
+
302
+	/**
303
+	 * This just handles the setting of the selected option for data optin via ajax
304
+	 *
305
+	 * @return void
306
+	 * @throws InvalidArgumentException
307
+	 * @throws InvalidDataTypeException
308
+	 * @throws InvalidInterfaceException
309
+	 */
310
+	public function espresso_data_optin_ajax_handler()
311
+	{
312
+
313
+		//verify nonce
314
+		if (isset($_POST['nonce']) && ! wp_verify_nonce($_POST['nonce'], 'ee-data-optin')) {
315
+			exit();
316
+		}
317
+
318
+		//update_option('ee_ueip_optin', $ueip_optin);
319
+		EE_Registry::instance()->CFG->core->ee_ueip_has_notified = 1;
320
+		EE_Registry::instance()->CFG->update_espresso_config(false, false);
321
+		exit();
322
+	}
323
+
324
+
325
+	/**
326
+	 * This is a handy helper method for retrieving whether there is an update available for the given plugin.
327
+	 *
328
+	 * @param  string $basename Use the equivalent result from plugin_basename() for this param as WP uses that to
329
+	 *                          identify plugins. Defaults to core update
330
+	 * @return boolean           True if update available, false if not.
331
+	 */
332
+	public static function is_update_available($basename = '')
333
+	{
334
+
335
+		$basename = ! empty($basename) ? $basename : EE_PLUGIN_BASENAME;
336
+
337
+		$update = false;
338
+
339
+		// should take "event-espresso-core/espresso.php" and change to "/event-espresso-core"
340
+		$folder = DS . dirname($basename);
341
+
342
+		$plugins = get_plugins($folder);
343
+		$current = get_site_transient('update_plugins');
344
+
345
+		foreach ((array)$plugins as $plugin_file => $plugin_data) {
346
+			if (isset($current->response['plugin_file'])) {
347
+				$update = true;
348
+			}
349
+		}
350
+
351
+		//it's possible that there is an update but an invalid site-license-key is in use
352
+		if (get_site_option('pue_json_error_' . $basename)) {
353
+			$update = true;
354
+		}
355
+
356
+		return $update;
357
+	}
358
+
359
+
360
+	/**
361
+	 * UXIP TRACKING *******
362
+	 */
363
+
364
+
365
+	/**
366
+	 * This method contains all the hooks into EE for gathering stats that will be reported with the PUE uxip system
367
+	 *
368
+	 * @public
369
+	 * @return void
370
+	 */
371
+	public function _uxip_hooks()
372
+	{
373
+		if (EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance) {
374
+			add_action('admin_init', array($this, 'track_active_theme'));
375
+			add_action('admin_init', array($this, 'track_event_info'));
376
+		}
377
+	}
378
+
379
+
380
+	public function track_active_theme()
381
+	{
382
+		//we only check this once a month.
383
+		if (false === ($transient = get_transient('ee_active_theme_check'))) {
384
+			$theme = wp_get_theme();
385
+			update_option('uxip_ee_active_theme', $theme->get('Name'));
386
+			set_transient('ee_active_theme_check', 1, MONTH_IN_SECONDS);
387
+		}
388
+	}
389
+
390
+
391
+	public function track_event_info()
392
+	{
393
+		//we only check this once every couple weeks.
394
+		if (false === ($transient = get_transient('ee4_event_info_check'))) {
395
+			//first let's get the number for ALL events
396
+			/** @var EEM_Event $EVT */
397
+			$EVT   = EE_Registry::instance()->load_model('Event');
398
+			$DTT   = EE_Registry::instance()->load_model('Datetime');
399
+			$TKT   = EE_Registry::instance()->load_model('Ticket');
400
+			$count = $EVT->count();
401
+			if ($count > 0) {
402
+				update_option('uxip_ee4_all_events_count', $count);
403
+			}
404
+
405
+			//next let's just get the number of ACTIVE events
406
+			$count_active = $EVT->get_active_events(array(), true);
407
+			if ($count_active > 0) {
408
+				update_option('uxip_ee4_active_events_count', $count_active);
409
+			}
410
+
411
+			//datetimes!
412
+			$dtt_count = $DTT->count();
413
+			if ($dtt_count > 0) {
414
+				update_option('uxip_ee_all_dtts_count', $dtt_count);
415
+			}
416
+
417
+
418
+			//dttsold
419
+			$dtt_sold = $DTT->sum(array(), 'DTT_sold');
420
+			if ($dtt_sold > 0) {
421
+				update_option('uxip_ee_dtt_sold', $dtt_sold);
422
+			}
423
+
424
+			//allticketcount
425
+			$all_tkt_count = $TKT->count();
426
+			if ($all_tkt_count > 0) {
427
+				update_option('uxip_ee_all_tkt_count', $all_tkt_count);
428
+			}
429
+
430
+			//freetktcount
431
+			$_where         = array('TKT_price' => 0);
432
+			$free_tkt_count = $TKT->count(array($_where));
433
+			if ($free_tkt_count > 0) {
434
+				update_option('uxip_ee_free_tkt_count', $free_tkt_count);
435
+			}
436
+
437
+			//paidtktcount
438
+			$_where         = array('TKT_price' => array('>', 0));
439
+			$paid_tkt_count = $TKT->count(array($_where));
440
+			if ($paid_tkt_count > 0) {
441
+				update_option('uxip_ee_paid_tkt_count', $paid_tkt_count);
442
+			}
443
+
444
+			//tktsold
445
+			$tkt_sold = $TKT->sum(array(), 'TKT_sold');
446
+			if ($tkt_sold > 0) {
447
+				update_option('uxip_ee_tkt_sold', $tkt_sold);
448
+			}
449
+
450
+
451
+			set_transient('ee4_event_info_check', 1, WEEK_IN_SECONDS * 2);
452
+		}
453
+	}
454 454
 
455 455
 }
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@  discard block
 block discarded – undo
29 29
         do_action('AHEE_log', __CLASS__, __FUNCTION__);
30 30
 
31 31
         //wp have no MONTH_IN_SECONDS constant.  So we approximate our own assuming all months are 4 weeks long.
32
-        if (! defined('MONTH_IN_SECONDS')) {
32
+        if ( ! defined('MONTH_IN_SECONDS')) {
33 33
             define('MONTH_IN_SECONDS', WEEK_IN_SECONDS * 4);
34 34
         }
35 35
 
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
         $extra_stats = array();
59 59
 
60 60
         //only collect extra stats if the plugin user has opted in and transient is expired.
61
-        if (! empty($espresso_data_optin) && $espresso_data_optin == 'yes') {
61
+        if ( ! empty($espresso_data_optin) && $espresso_data_optin == 'yes') {
62 62
             if (false === ($transient = get_transient('ee_extra_data'))
63 63
                 && EE_Maintenance_Mode::instance()->level() != EE_Maintenance_Mode::level_2_complete_maintenance
64 64
             ) {
@@ -68,15 +68,15 @@  discard block
 block discarded – undo
68 68
                     ? trim(
69 69
                         preg_replace('/\b\w\S\w\b/', '', $current_site->domain),
70 70
                         '.'
71
-                    ) . '_'
71
+                    ).'_'
72 72
                     : '';
73 73
 
74 74
 
75 75
                 //active gateways
76 76
                 $active_gateways = get_option('event_espresso_active_gateways');
77
-                if (! empty($active_gateways)) {
78
-                    foreach ((array)$active_gateways as $gateway => $ignore) {
79
-                        $extra_stats[$site_pre . $gateway . '_gateway_active'] = 1;
77
+                if ( ! empty($active_gateways)) {
78
+                    foreach ((array) $active_gateways as $gateway => $ignore) {
79
+                        $extra_stats[$site_pre.$gateway.'_gateway_active'] = 1;
80 80
                     }
81 81
                 }
82 82
 
@@ -86,50 +86,50 @@  discard block
 block discarded – undo
86 86
 
87 87
                 //what is the current active theme?
88 88
                 $active_theme = get_option('uxip_ee_active_theme');
89
-                if (! empty($active_theme)) {
90
-                    $extra_stats[$site_pre . 'active_theme'] = $active_theme;
89
+                if ( ! empty($active_theme)) {
90
+                    $extra_stats[$site_pre.'active_theme'] = $active_theme;
91 91
                 }
92 92
 
93 93
                 //event info regarding an all event count and all "active" event count
94 94
                 $all_events_count = get_option('uxip_ee4_all_events_count');
95
-                if (! empty($all_events_count)) {
96
-                    $extra_stats[$site_pre . 'ee4_all_events_count'] = $all_events_count;
95
+                if ( ! empty($all_events_count)) {
96
+                    $extra_stats[$site_pre.'ee4_all_events_count'] = $all_events_count;
97 97
                 }
98 98
                 $active_events_count = get_option('uxip_ee4_active_events_count');
99
-                if (! empty($active_events_count)) {
100
-                    $extra_stats[$site_pre . 'ee4_active_events_count'] = $active_events_count;
99
+                if ( ! empty($active_events_count)) {
100
+                    $extra_stats[$site_pre.'ee4_active_events_count'] = $active_events_count;
101 101
                 }
102 102
 
103 103
                 //datetime stuff
104 104
                 $dtt_count = get_option('uxip_ee_all_dtts_count');
105
-                if (! empty($dtt_count)) {
106
-                    $extra_stats[$site_pre . 'all_dtts_count'] = $dtt_count;
105
+                if ( ! empty($dtt_count)) {
106
+                    $extra_stats[$site_pre.'all_dtts_count'] = $dtt_count;
107 107
                 }
108 108
 
109 109
                 $dtt_sold = get_option('uxip_ee_dtt_sold');
110
-                if (! empty($dtt_sold)) {
111
-                    $extra_stats[$site_pre . 'dtt_sold'] = $dtt_sold;
110
+                if ( ! empty($dtt_sold)) {
111
+                    $extra_stats[$site_pre.'dtt_sold'] = $dtt_sold;
112 112
                 }
113 113
 
114 114
                 //ticket stuff
115 115
                 $all_tkt_count = get_option('uxip_ee_all_tkt_count');
116
-                if (! empty($all_tkt_count)) {
117
-                    $extra_stats[$site_pre . 'all_tkt_count'] = $all_tkt_count;
116
+                if ( ! empty($all_tkt_count)) {
117
+                    $extra_stats[$site_pre.'all_tkt_count'] = $all_tkt_count;
118 118
                 }
119 119
 
120 120
                 $free_tkt_count = get_option('uxip_ee_free_tkt_count');
121
-                if (! empty($free_tkt_count)) {
122
-                    $extra_stats[$site_pre . 'free_tkt_count'] = $free_tkt_count;
121
+                if ( ! empty($free_tkt_count)) {
122
+                    $extra_stats[$site_pre.'free_tkt_count'] = $free_tkt_count;
123 123
                 }
124 124
 
125 125
                 $paid_tkt_count = get_option('uxip_ee_paid_tkt_count');
126
-                if (! empty($paid_tkt_count)) {
127
-                    $extra_stats[$site_pre . 'paid_tkt_count'] = $paid_tkt_count;
126
+                if ( ! empty($paid_tkt_count)) {
127
+                    $extra_stats[$site_pre.'paid_tkt_count'] = $paid_tkt_count;
128 128
                 }
129 129
 
130 130
                 $tkt_sold = get_option('uxip_ee_tkt_sold');
131
-                if (! empty($tkt_sold)) {
132
-                    $extra_stats[$site_pre . 'tkt_sold'] = $tkt_sold;
131
+                if ( ! empty($tkt_sold)) {
132
+                    $extra_stats[$site_pre.'tkt_sold'] = $tkt_sold;
133 133
                 }
134 134
 
135 135
                 //phpversion checking
@@ -142,10 +142,10 @@  discard block
 block discarded – undo
142 142
 
143 143
 
144 144
         // PUE Auto Upgrades stuff
145
-        if (is_readable(EE_THIRD_PARTY . 'pue/pue-client.php')) { //include the file
146
-            require_once(EE_THIRD_PARTY . 'pue/pue-client.php');
145
+        if (is_readable(EE_THIRD_PARTY.'pue/pue-client.php')) { //include the file
146
+            require_once(EE_THIRD_PARTY.'pue/pue-client.php');
147 147
 
148
-            $api_key         = isset(EE_Registry::instance()->NET_CFG->core->site_license_key)
148
+            $api_key = isset(EE_Registry::instance()->NET_CFG->core->site_license_key)
149 149
                 ? EE_Registry::instance()->NET_CFG->core->site_license_key
150 150
                 : '';
151 151
             //this needs to be the host server where plugin update engine is installed. Note, if you leave this blank
@@ -208,9 +208,9 @@  discard block
 block discarded – undo
208 208
      */
209 209
     public static function espresso_data_collection_optin_text($extra = true)
210 210
     {
211
-        if (! $extra) {
211
+        if ( ! $extra) {
212 212
             echo '<h2 class="ee-admin-settings-hdr" '
213
-                 . (! $extra ? 'id="UXIP_settings"' : '')
213
+                 . ( ! $extra ? 'id="UXIP_settings"' : '')
214 214
                  . '>'
215 215
                  . esc_html__('User eXperience Improvement Program (UXIP)', 'event_espresso')
216 216
                  . EEH_Template::get_help_tab_link('organization_logo_info')
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
                 ),
242 242
                 '<a href="https://eventespresso.com/about/user-experience-improvement-program-uxip/" target="_blank">',
243 243
                 '</a>',
244
-                '<a href="' . $settings_url . '" target="_blank">',
244
+                '<a href="'.$settings_url.'" target="_blank">',
245 245
                 '</a>'
246 246
             );
247 247
         }
@@ -282,14 +282,14 @@  discard block
 block discarded – undo
282 282
     {
283 283
         wp_register_script(
284 284
             'ee-data-optin-js',
285
-            EE_GLOBAL_ASSETS_URL . 'scripts/ee-data-optin.js',
285
+            EE_GLOBAL_ASSETS_URL.'scripts/ee-data-optin.js',
286 286
             array('jquery'),
287 287
             EVENT_ESPRESSO_VERSION,
288 288
             true
289 289
         );
290 290
         wp_register_style(
291 291
             'ee-data-optin-css',
292
-            EE_GLOBAL_ASSETS_URL . 'css/ee-data-optin.css',
292
+            EE_GLOBAL_ASSETS_URL.'css/ee-data-optin.css',
293 293
             array(),
294 294
             EVENT_ESPRESSO_VERSION
295 295
         );
@@ -337,19 +337,19 @@  discard block
 block discarded – undo
337 337
         $update = false;
338 338
 
339 339
         // should take "event-espresso-core/espresso.php" and change to "/event-espresso-core"
340
-        $folder = DS . dirname($basename);
340
+        $folder = DS.dirname($basename);
341 341
 
342 342
         $plugins = get_plugins($folder);
343 343
         $current = get_site_transient('update_plugins');
344 344
 
345
-        foreach ((array)$plugins as $plugin_file => $plugin_data) {
345
+        foreach ((array) $plugins as $plugin_file => $plugin_data) {
346 346
             if (isset($current->response['plugin_file'])) {
347 347
                 $update = true;
348 348
             }
349 349
         }
350 350
 
351 351
         //it's possible that there is an update but an invalid site-license-key is in use
352
-        if (get_site_option('pue_json_error_' . $basename)) {
352
+        if (get_site_option('pue_json_error_'.$basename)) {
353 353
             $update = true;
354 354
         }
355 355
 
Please login to merge, or discard this patch.
core/services/cache/TransientCacheStorage.php 2 patches
Indentation   +367 added lines, -367 removed lines patch added patch discarded remove patch
@@ -19,373 +19,373 @@
 block discarded – undo
19 19
 class TransientCacheStorage implements CacheStorageInterface
20 20
 {
21 21
 
22
-    /**
23
-     * wp-option option_name for tracking transients
24
-     *
25
-     * @type string
26
-     */
27
-    const TRANSIENT_SCHEDULE_OPTIONS_KEY = 'ee_transient_schedule';
28
-
29
-    /**
30
-     * @var int $current_time
31
-     */
32
-    private $current_time;
33
-
34
-    /**
35
-     * how often to perform transient cleanup
36
-     *
37
-     * @var string $transient_cleanup_frequency
38
-     */
39
-    private $transient_cleanup_frequency;
40
-
41
-    /**
42
-     * options for how often to perform transient cleanup
43
-     *
44
-     * @var array $transient_cleanup_frequency_options
45
-     */
46
-    private $transient_cleanup_frequency_options = array();
47
-
48
-    /**
49
-     * @var array $transients
50
-     */
51
-    private $transients;
52
-
53
-
54
-
55
-    /**
56
-     * TransientCacheStorage constructor.
57
-     */
58
-    public function __construct()
59
-    {
60
-        $this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
61
-        // round current time down to closest 5 minutes to simplify scheduling
62
-        $this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
63
-        $this->transients = (array)get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
64
-        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
65
-            add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
66
-        }
67
-    }
68
-
69
-
70
-
71
-    /**
72
-     * Sets how often transient cleanup occurs
73
-     *
74
-     * @return string
75
-     */
76
-    private function setTransientCleanupFrequency()
77
-    {
78
-        // sets how often transients are cleaned up
79
-        $this->transient_cleanup_frequency_options = apply_filters(
80
-            'FHEE__TransientCacheStorage__transient_cleanup_schedule_options',
81
-            array(
82
-                'off',
83
-                '15-minutes',
84
-                'hour',
85
-                '12-hours',
86
-                'day',
87
-            )
88
-        );
89
-        $transient_cleanup_frequency = apply_filters(
90
-            'FHEE__TransientCacheStorage__transient_cleanup_schedule',
91
-            'hour'
92
-        );
93
-        return in_array(
94
-            $transient_cleanup_frequency,
95
-            $this->transient_cleanup_frequency_options,
96
-            true
97
-        )
98
-            ? $transient_cleanup_frequency
99
-            : 'hour';
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     * we need to be able to round timestamps off to match the set transient cleanup frequency
106
-     * so if a transient is set to expire at 1:17 pm for example, and our cleanup schedule is every hour,
107
-     * then that timestamp needs to be rounded up to 2:00 pm so that it is removed
108
-     * during the next scheduled cleanup after its expiration.
109
-     * We also round off the current time timestamp to the closest 5 minutes
110
-     * just to make the timestamps a little easier to round which helps with debugging.
111
-     *
112
-     * @param int    $timestamp [required]
113
-     * @param string $cleanup_frequency
114
-     * @param bool   $round_up
115
-     * @return int
116
-     */
117
-    private function roundTimestamp($timestamp, $cleanup_frequency = 'hour', $round_up = true)
118
-    {
119
-        $cleanup_frequency = $cleanup_frequency ? $cleanup_frequency : $this->transient_cleanup_frequency;
120
-        // in order to round the time to the closest xx minutes (or hours),
121
-        // we take the minutes (or hours) portion of the timestamp and divide it by xx,
122
-        // round down to a whole number, then multiply by xx to bring us almost back up to where we were
123
-        // why round down ? so the minutes (or hours) don't go over 60 (or 24)
124
-        // and bump the hour, which could bump the day, which could bump the month, etc,
125
-        // which would be bad because we don't always want to round up,
126
-        // but when we do we can easily achieve that by simply adding the desired offset,
127
-        $minutes = '00';
128
-        $hours = 'H';
129
-        switch ($cleanup_frequency) {
130
-            case '5-minutes' :
131
-                $minutes = floor((int)date('i', $timestamp) / 5) * 5;
132
-                $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
133
-                $offset = MINUTE_IN_SECONDS * 5;
134
-                break;
135
-            case '15-minutes' :
136
-                $minutes = floor((int)date('i', $timestamp) / 15) * 15;
137
-                $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
138
-                $offset = MINUTE_IN_SECONDS * 15;
139
-                break;
140
-            case '12-hours' :
141
-                $hours = floor((int)date('H', $timestamp) / 12) * 12;
142
-                $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
143
-                $offset = HOUR_IN_SECONDS * 12;
144
-                break;
145
-            case 'day' :
146
-                $hours = '03'; // run cleanup at 3:00 am (or first site hit after that)
147
-                $offset = DAY_IN_SECONDS;
148
-                break;
149
-            case 'hour' :
150
-            default :
151
-                $offset = HOUR_IN_SECONDS;
152
-                break;
153
-        }
154
-        $rounded_timestamp = (int) strtotime(date("Y-m-d {$hours}:{$minutes}:00", $timestamp));
155
-        $rounded_timestamp += $round_up ? $offset : 0;
156
-        return apply_filters(
157
-            'FHEE__TransientCacheStorage__roundTimestamp__timestamp',
158
-            $rounded_timestamp,
159
-            $timestamp,
160
-            $cleanup_frequency,
161
-            $round_up
162
-        );
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * Saves supplied data to a transient
169
-     * if an expiration is set, then it automatically schedules the transient for cleanup
170
-     *
171
-     * @param string $transient_key [required]
172
-     * @param string $data          [required]
173
-     * @param int    $expiration    number of seconds until the cache expires
174
-     * @return bool
175
-     */
176
-    public function add($transient_key, $data, $expiration = 0)
177
-    {
178
-        $expiration = (int)abs($expiration);
179
-        $saved = set_transient($transient_key, $data, $expiration);
180
-        if ($saved && $expiration) {
181
-            $this->scheduleTransientCleanup($transient_key, $expiration);
182
-        }
183
-        return $saved;
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * retrieves transient data
190
-     * automatically triggers early cache refresh for standard cache items
191
-     * in order to avoid cache stampedes on busy sites.
192
-     * For non-standard cache items like PHP Session data where early refreshing is not wanted,
193
-     * the $standard_cache parameter should be set to false when retrieving data
194
-     *
195
-     * @param string $transient_key [required]
196
-     * @param bool   $standard_cache
197
-     * @return mixed|null
198
-     */
199
-    public function get($transient_key, $standard_cache = true)
200
-    {
201
-        // to avoid cache stampedes (AKA:dogpiles) for standard cache items,
202
-        // check if known cache expires within the next minute,
203
-        // and if so, remove it from our tracking and and return nothing.
204
-        // this should trigger the cache content to be regenerated during this request,
205
-        // while allowing any following requests to still access the existing cache
206
-        // until it gets replaced with the refreshed content
207
-        if (
208
-            $standard_cache
209
-            && isset($this->transients[$transient_key])
210
-            && $this->transients[$transient_key] - time() <= MINUTE_IN_SECONDS
211
-        ) {
212
-            unset($this->transients[$transient_key]);
213
-            $this->updateTransients();
214
-            return null;
215
-        }
216
-        $content = get_transient($transient_key);
217
-        return $content !== false ? $content : null;
218
-    }
219
-
220
-
221
-
222
-    /**
223
-     * delete a single transient and remove tracking
224
-     *
225
-     * @param string $transient_key [required] full or partial transient key to be deleted
226
-     */
227
-    public function delete($transient_key)
228
-    {
229
-        $this->deleteMany(array($transient_key));
230
-    }
231
-
232
-
233
-
234
-    /**
235
-     * delete multiple transients and remove tracking
236
-     *
237
-     * @param array $transient_keys [required] array of full or partial transient keys to be deleted
238
-     * @param bool  $force_delete   [optional] if true, then will not check incoming keys against those being tracked
239
-     *                              and proceed directly to deleting those entries from the cache storage
240
-     */
241
-    public function deleteMany(array $transient_keys, $force_delete = false)
242
-    {
243
-        $full_transient_keys = $force_delete ? $transient_keys : array();
244
-        if(empty($full_transient_keys)){
245
-            foreach ($this->transients as $transient_key => $expiration) {
246
-                foreach ($transient_keys as $transient_key_to_delete) {
247
-                    if (strpos($transient_key, $transient_key_to_delete) !== false) {
248
-                        $full_transient_keys[] = $transient_key;
249
-                    }
250
-                }
251
-            }
252
-        }
253
-        if ($this->deleteTransientKeys($full_transient_keys)) {
254
-            $this->updateTransients();
255
-        }
256
-    }
257
-
258
-
259
-
260
-    /**
261
-     * sorts transients numerically by timestamp
262
-     * then saves the transient schedule to a WP option
263
-     */
264
-    private function updateTransients()
265
-    {
266
-        asort($this->transients, SORT_NUMERIC);
267
-        update_option(
268
-            TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY,
269
-            $this->transients
270
-        );
271
-    }
272
-
273
-
274
-
275
-    /**
276
-     * schedules a transient for cleanup by adding it to the transient tracking
277
-     *
278
-     * @param string $transient_key [required]
279
-     * @param int    $expiration    [required]
280
-     */
281
-    private function scheduleTransientCleanup($transient_key, $expiration)
282
-    {
283
-        // make sure a valid future timestamp is set
284
-        $expiration += $expiration < time() ? time() : 0;
285
-        // and round to the closest 15 minutes
286
-        $expiration = $this->roundTimestamp($expiration);
287
-        // save transients to clear using their ID as the key to avoid duplicates
288
-        $this->transients[$transient_key] = $expiration;
289
-        $this->updateTransients();
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * Since our tracked transients are sorted by their timestamps
296
-     * we can grab the first transient and see when it is scheduled for cleanup.
297
-     * If that timestamp is less than or equal to the current time,
298
-     * then cleanup is triggered
299
-     */
300
-    public function checkTransientCleanupSchedule()
301
-    {
302
-        if (empty($this->transients)) {
303
-            return;
304
-        }
305
-        // when do we run the next cleanup job?
306
-        reset($this->transients);
307
-        $next_scheduled_cleanup = current($this->transients);
308
-        // if the next cleanup job is scheduled for the current hour
309
-        if ($next_scheduled_cleanup <= $this->current_time) {
310
-            if ($this->cleanupExpiredTransients()) {
311
-                $this->updateTransients();
312
-            }
313
-        }
314
-    }
315
-
316
-
317
-
318
-    /**
319
-     * loops through the array of tracked transients,
320
-     * compiles a list of those that have expired, and sends that list off for deletion.
321
-     * Also removes any bad records from the transients array
322
-     *
323
-     * @return bool
324
-     */
325
-    private function cleanupExpiredTransients()
326
-    {
327
-        $update = false;
328
-        // filter the query limit. Set to 0 to turn off garbage collection
329
-        $limit = (int)abs(
330
-            apply_filters(
331
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
332
-                50
333
-            )
334
-        );
335
-        // non-zero LIMIT means take out the trash
336
-        if ($limit) {
337
-            $transient_keys = array();
338
-            foreach ($this->transients as $transient_key => $expiration) {
339
-                if ($expiration > $this->current_time) {
340
-                    continue;
341
-                }
342
-                if ( ! $expiration || ! $transient_key) {
343
-                    unset($this->transients[$transient_key]);
344
-                    $update = true;
345
-                    continue;
346
-                }
347
-                $transient_keys[] = $transient_key;
348
-            }
349
-            // delete expired keys, but maintain value of $update if nothing is deleted
350
-            $update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
351
-            do_action( 'FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
352
-        }
353
-        return $update;
354
-    }
355
-
356
-
357
-
358
-    /**
359
-     * calls delete_transient() on each transient key provided, up to the specified limit
360
-     *
361
-     * @param array $transient_keys [required]
362
-     * @param int   $limit
363
-     * @return bool
364
-     */
365
-    private function deleteTransientKeys(array $transient_keys, $limit = 50)
366
-    {
367
-        if (empty($transient_keys)) {
368
-            return false;
369
-        }
370
-        $counter = 0;
371
-        foreach ($transient_keys as $transient_key) {
372
-            if($counter === $limit){
373
-                break;
374
-            }
375
-            // remove any transient prefixes
376
-            $transient_key = strpos($transient_key,  '_transient_timeout_') === 0
377
-                ? str_replace('_transient_timeout_', '', $transient_key)
378
-                : $transient_key;
379
-            $transient_key = strpos($transient_key,  '_transient_') === 0
380
-                ? str_replace('_transient_', '', $transient_key)
381
-                : $transient_key;
382
-            if(delete_transient($transient_key)){
383
-                unset($this->transients[$transient_key]);
384
-                $counter++;
385
-            }
386
-        }
387
-        return $counter > 0;
388
-    }
22
+	/**
23
+	 * wp-option option_name for tracking transients
24
+	 *
25
+	 * @type string
26
+	 */
27
+	const TRANSIENT_SCHEDULE_OPTIONS_KEY = 'ee_transient_schedule';
28
+
29
+	/**
30
+	 * @var int $current_time
31
+	 */
32
+	private $current_time;
33
+
34
+	/**
35
+	 * how often to perform transient cleanup
36
+	 *
37
+	 * @var string $transient_cleanup_frequency
38
+	 */
39
+	private $transient_cleanup_frequency;
40
+
41
+	/**
42
+	 * options for how often to perform transient cleanup
43
+	 *
44
+	 * @var array $transient_cleanup_frequency_options
45
+	 */
46
+	private $transient_cleanup_frequency_options = array();
47
+
48
+	/**
49
+	 * @var array $transients
50
+	 */
51
+	private $transients;
52
+
53
+
54
+
55
+	/**
56
+	 * TransientCacheStorage constructor.
57
+	 */
58
+	public function __construct()
59
+	{
60
+		$this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
61
+		// round current time down to closest 5 minutes to simplify scheduling
62
+		$this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
63
+		$this->transients = (array)get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
64
+		if ( ! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
65
+			add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
66
+		}
67
+	}
68
+
69
+
70
+
71
+	/**
72
+	 * Sets how often transient cleanup occurs
73
+	 *
74
+	 * @return string
75
+	 */
76
+	private function setTransientCleanupFrequency()
77
+	{
78
+		// sets how often transients are cleaned up
79
+		$this->transient_cleanup_frequency_options = apply_filters(
80
+			'FHEE__TransientCacheStorage__transient_cleanup_schedule_options',
81
+			array(
82
+				'off',
83
+				'15-minutes',
84
+				'hour',
85
+				'12-hours',
86
+				'day',
87
+			)
88
+		);
89
+		$transient_cleanup_frequency = apply_filters(
90
+			'FHEE__TransientCacheStorage__transient_cleanup_schedule',
91
+			'hour'
92
+		);
93
+		return in_array(
94
+			$transient_cleanup_frequency,
95
+			$this->transient_cleanup_frequency_options,
96
+			true
97
+		)
98
+			? $transient_cleanup_frequency
99
+			: 'hour';
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 * we need to be able to round timestamps off to match the set transient cleanup frequency
106
+	 * so if a transient is set to expire at 1:17 pm for example, and our cleanup schedule is every hour,
107
+	 * then that timestamp needs to be rounded up to 2:00 pm so that it is removed
108
+	 * during the next scheduled cleanup after its expiration.
109
+	 * We also round off the current time timestamp to the closest 5 minutes
110
+	 * just to make the timestamps a little easier to round which helps with debugging.
111
+	 *
112
+	 * @param int    $timestamp [required]
113
+	 * @param string $cleanup_frequency
114
+	 * @param bool   $round_up
115
+	 * @return int
116
+	 */
117
+	private function roundTimestamp($timestamp, $cleanup_frequency = 'hour', $round_up = true)
118
+	{
119
+		$cleanup_frequency = $cleanup_frequency ? $cleanup_frequency : $this->transient_cleanup_frequency;
120
+		// in order to round the time to the closest xx minutes (or hours),
121
+		// we take the minutes (or hours) portion of the timestamp and divide it by xx,
122
+		// round down to a whole number, then multiply by xx to bring us almost back up to where we were
123
+		// why round down ? so the minutes (or hours) don't go over 60 (or 24)
124
+		// and bump the hour, which could bump the day, which could bump the month, etc,
125
+		// which would be bad because we don't always want to round up,
126
+		// but when we do we can easily achieve that by simply adding the desired offset,
127
+		$minutes = '00';
128
+		$hours = 'H';
129
+		switch ($cleanup_frequency) {
130
+			case '5-minutes' :
131
+				$minutes = floor((int)date('i', $timestamp) / 5) * 5;
132
+				$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
133
+				$offset = MINUTE_IN_SECONDS * 5;
134
+				break;
135
+			case '15-minutes' :
136
+				$minutes = floor((int)date('i', $timestamp) / 15) * 15;
137
+				$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
138
+				$offset = MINUTE_IN_SECONDS * 15;
139
+				break;
140
+			case '12-hours' :
141
+				$hours = floor((int)date('H', $timestamp) / 12) * 12;
142
+				$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
143
+				$offset = HOUR_IN_SECONDS * 12;
144
+				break;
145
+			case 'day' :
146
+				$hours = '03'; // run cleanup at 3:00 am (or first site hit after that)
147
+				$offset = DAY_IN_SECONDS;
148
+				break;
149
+			case 'hour' :
150
+			default :
151
+				$offset = HOUR_IN_SECONDS;
152
+				break;
153
+		}
154
+		$rounded_timestamp = (int) strtotime(date("Y-m-d {$hours}:{$minutes}:00", $timestamp));
155
+		$rounded_timestamp += $round_up ? $offset : 0;
156
+		return apply_filters(
157
+			'FHEE__TransientCacheStorage__roundTimestamp__timestamp',
158
+			$rounded_timestamp,
159
+			$timestamp,
160
+			$cleanup_frequency,
161
+			$round_up
162
+		);
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * Saves supplied data to a transient
169
+	 * if an expiration is set, then it automatically schedules the transient for cleanup
170
+	 *
171
+	 * @param string $transient_key [required]
172
+	 * @param string $data          [required]
173
+	 * @param int    $expiration    number of seconds until the cache expires
174
+	 * @return bool
175
+	 */
176
+	public function add($transient_key, $data, $expiration = 0)
177
+	{
178
+		$expiration = (int)abs($expiration);
179
+		$saved = set_transient($transient_key, $data, $expiration);
180
+		if ($saved && $expiration) {
181
+			$this->scheduleTransientCleanup($transient_key, $expiration);
182
+		}
183
+		return $saved;
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * retrieves transient data
190
+	 * automatically triggers early cache refresh for standard cache items
191
+	 * in order to avoid cache stampedes on busy sites.
192
+	 * For non-standard cache items like PHP Session data where early refreshing is not wanted,
193
+	 * the $standard_cache parameter should be set to false when retrieving data
194
+	 *
195
+	 * @param string $transient_key [required]
196
+	 * @param bool   $standard_cache
197
+	 * @return mixed|null
198
+	 */
199
+	public function get($transient_key, $standard_cache = true)
200
+	{
201
+		// to avoid cache stampedes (AKA:dogpiles) for standard cache items,
202
+		// check if known cache expires within the next minute,
203
+		// and if so, remove it from our tracking and and return nothing.
204
+		// this should trigger the cache content to be regenerated during this request,
205
+		// while allowing any following requests to still access the existing cache
206
+		// until it gets replaced with the refreshed content
207
+		if (
208
+			$standard_cache
209
+			&& isset($this->transients[$transient_key])
210
+			&& $this->transients[$transient_key] - time() <= MINUTE_IN_SECONDS
211
+		) {
212
+			unset($this->transients[$transient_key]);
213
+			$this->updateTransients();
214
+			return null;
215
+		}
216
+		$content = get_transient($transient_key);
217
+		return $content !== false ? $content : null;
218
+	}
219
+
220
+
221
+
222
+	/**
223
+	 * delete a single transient and remove tracking
224
+	 *
225
+	 * @param string $transient_key [required] full or partial transient key to be deleted
226
+	 */
227
+	public function delete($transient_key)
228
+	{
229
+		$this->deleteMany(array($transient_key));
230
+	}
231
+
232
+
233
+
234
+	/**
235
+	 * delete multiple transients and remove tracking
236
+	 *
237
+	 * @param array $transient_keys [required] array of full or partial transient keys to be deleted
238
+	 * @param bool  $force_delete   [optional] if true, then will not check incoming keys against those being tracked
239
+	 *                              and proceed directly to deleting those entries from the cache storage
240
+	 */
241
+	public function deleteMany(array $transient_keys, $force_delete = false)
242
+	{
243
+		$full_transient_keys = $force_delete ? $transient_keys : array();
244
+		if(empty($full_transient_keys)){
245
+			foreach ($this->transients as $transient_key => $expiration) {
246
+				foreach ($transient_keys as $transient_key_to_delete) {
247
+					if (strpos($transient_key, $transient_key_to_delete) !== false) {
248
+						$full_transient_keys[] = $transient_key;
249
+					}
250
+				}
251
+			}
252
+		}
253
+		if ($this->deleteTransientKeys($full_transient_keys)) {
254
+			$this->updateTransients();
255
+		}
256
+	}
257
+
258
+
259
+
260
+	/**
261
+	 * sorts transients numerically by timestamp
262
+	 * then saves the transient schedule to a WP option
263
+	 */
264
+	private function updateTransients()
265
+	{
266
+		asort($this->transients, SORT_NUMERIC);
267
+		update_option(
268
+			TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY,
269
+			$this->transients
270
+		);
271
+	}
272
+
273
+
274
+
275
+	/**
276
+	 * schedules a transient for cleanup by adding it to the transient tracking
277
+	 *
278
+	 * @param string $transient_key [required]
279
+	 * @param int    $expiration    [required]
280
+	 */
281
+	private function scheduleTransientCleanup($transient_key, $expiration)
282
+	{
283
+		// make sure a valid future timestamp is set
284
+		$expiration += $expiration < time() ? time() : 0;
285
+		// and round to the closest 15 minutes
286
+		$expiration = $this->roundTimestamp($expiration);
287
+		// save transients to clear using their ID as the key to avoid duplicates
288
+		$this->transients[$transient_key] = $expiration;
289
+		$this->updateTransients();
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * Since our tracked transients are sorted by their timestamps
296
+	 * we can grab the first transient and see when it is scheduled for cleanup.
297
+	 * If that timestamp is less than or equal to the current time,
298
+	 * then cleanup is triggered
299
+	 */
300
+	public function checkTransientCleanupSchedule()
301
+	{
302
+		if (empty($this->transients)) {
303
+			return;
304
+		}
305
+		// when do we run the next cleanup job?
306
+		reset($this->transients);
307
+		$next_scheduled_cleanup = current($this->transients);
308
+		// if the next cleanup job is scheduled for the current hour
309
+		if ($next_scheduled_cleanup <= $this->current_time) {
310
+			if ($this->cleanupExpiredTransients()) {
311
+				$this->updateTransients();
312
+			}
313
+		}
314
+	}
315
+
316
+
317
+
318
+	/**
319
+	 * loops through the array of tracked transients,
320
+	 * compiles a list of those that have expired, and sends that list off for deletion.
321
+	 * Also removes any bad records from the transients array
322
+	 *
323
+	 * @return bool
324
+	 */
325
+	private function cleanupExpiredTransients()
326
+	{
327
+		$update = false;
328
+		// filter the query limit. Set to 0 to turn off garbage collection
329
+		$limit = (int)abs(
330
+			apply_filters(
331
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
332
+				50
333
+			)
334
+		);
335
+		// non-zero LIMIT means take out the trash
336
+		if ($limit) {
337
+			$transient_keys = array();
338
+			foreach ($this->transients as $transient_key => $expiration) {
339
+				if ($expiration > $this->current_time) {
340
+					continue;
341
+				}
342
+				if ( ! $expiration || ! $transient_key) {
343
+					unset($this->transients[$transient_key]);
344
+					$update = true;
345
+					continue;
346
+				}
347
+				$transient_keys[] = $transient_key;
348
+			}
349
+			// delete expired keys, but maintain value of $update if nothing is deleted
350
+			$update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
351
+			do_action( 'FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
352
+		}
353
+		return $update;
354
+	}
355
+
356
+
357
+
358
+	/**
359
+	 * calls delete_transient() on each transient key provided, up to the specified limit
360
+	 *
361
+	 * @param array $transient_keys [required]
362
+	 * @param int   $limit
363
+	 * @return bool
364
+	 */
365
+	private function deleteTransientKeys(array $transient_keys, $limit = 50)
366
+	{
367
+		if (empty($transient_keys)) {
368
+			return false;
369
+		}
370
+		$counter = 0;
371
+		foreach ($transient_keys as $transient_key) {
372
+			if($counter === $limit){
373
+				break;
374
+			}
375
+			// remove any transient prefixes
376
+			$transient_key = strpos($transient_key,  '_transient_timeout_') === 0
377
+				? str_replace('_transient_timeout_', '', $transient_key)
378
+				: $transient_key;
379
+			$transient_key = strpos($transient_key,  '_transient_') === 0
380
+				? str_replace('_transient_', '', $transient_key)
381
+				: $transient_key;
382
+			if(delete_transient($transient_key)){
383
+				unset($this->transients[$transient_key]);
384
+				$counter++;
385
+			}
386
+		}
387
+		return $counter > 0;
388
+	}
389 389
 
390 390
 
391 391
 
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
         $this->transient_cleanup_frequency = $this->setTransientCleanupFrequency();
61 61
         // round current time down to closest 5 minutes to simplify scheduling
62 62
         $this->current_time = $this->roundTimestamp(time(), '5-minutes', false);
63
-        $this->transients = (array)get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
63
+        $this->transients = (array) get_option(TransientCacheStorage::TRANSIENT_SCHEDULE_OPTIONS_KEY, array());
64 64
         if ( ! (defined('DOING_AJAX') && DOING_AJAX) && $this->transient_cleanup_frequency !== 'off') {
65 65
             add_action('shutdown', array($this, 'checkTransientCleanupSchedule'), 999);
66 66
         }
@@ -128,17 +128,17 @@  discard block
 block discarded – undo
128 128
         $hours = 'H';
129 129
         switch ($cleanup_frequency) {
130 130
             case '5-minutes' :
131
-                $minutes = floor((int)date('i', $timestamp) / 5) * 5;
131
+                $minutes = floor((int) date('i', $timestamp) / 5) * 5;
132 132
                 $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
133 133
                 $offset = MINUTE_IN_SECONDS * 5;
134 134
                 break;
135 135
             case '15-minutes' :
136
-                $minutes = floor((int)date('i', $timestamp) / 15) * 15;
136
+                $minutes = floor((int) date('i', $timestamp) / 15) * 15;
137 137
                 $minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
138 138
                 $offset = MINUTE_IN_SECONDS * 15;
139 139
                 break;
140 140
             case '12-hours' :
141
-                $hours = floor((int)date('H', $timestamp) / 12) * 12;
141
+                $hours = floor((int) date('H', $timestamp) / 12) * 12;
142 142
                 $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
143 143
                 $offset = HOUR_IN_SECONDS * 12;
144 144
                 break;
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
      */
176 176
     public function add($transient_key, $data, $expiration = 0)
177 177
     {
178
-        $expiration = (int)abs($expiration);
178
+        $expiration = (int) abs($expiration);
179 179
         $saved = set_transient($transient_key, $data, $expiration);
180 180
         if ($saved && $expiration) {
181 181
             $this->scheduleTransientCleanup($transient_key, $expiration);
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
     public function deleteMany(array $transient_keys, $force_delete = false)
242 242
     {
243 243
         $full_transient_keys = $force_delete ? $transient_keys : array();
244
-        if(empty($full_transient_keys)){
244
+        if (empty($full_transient_keys)) {
245 245
             foreach ($this->transients as $transient_key => $expiration) {
246 246
                 foreach ($transient_keys as $transient_key_to_delete) {
247 247
                     if (strpos($transient_key, $transient_key_to_delete) !== false) {
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
     {
327 327
         $update = false;
328 328
         // filter the query limit. Set to 0 to turn off garbage collection
329
-        $limit = (int)abs(
329
+        $limit = (int) abs(
330 330
             apply_filters(
331 331
                 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
332 332
                 50
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
             }
349 349
             // delete expired keys, but maintain value of $update if nothing is deleted
350 350
             $update = $this->deleteTransientKeys($transient_keys, $limit) ? true : $update;
351
-            do_action( 'FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
351
+            do_action('FHEE__TransientCacheStorage__clearExpiredTransients__end', $this);
352 352
         }
353 353
         return $update;
354 354
     }
@@ -369,17 +369,17 @@  discard block
 block discarded – undo
369 369
         }
370 370
         $counter = 0;
371 371
         foreach ($transient_keys as $transient_key) {
372
-            if($counter === $limit){
372
+            if ($counter === $limit) {
373 373
                 break;
374 374
             }
375 375
             // remove any transient prefixes
376
-            $transient_key = strpos($transient_key,  '_transient_timeout_') === 0
376
+            $transient_key = strpos($transient_key, '_transient_timeout_') === 0
377 377
                 ? str_replace('_transient_timeout_', '', $transient_key)
378 378
                 : $transient_key;
379
-            $transient_key = strpos($transient_key,  '_transient_') === 0
379
+            $transient_key = strpos($transient_key, '_transient_') === 0
380 380
                 ? str_replace('_transient_', '', $transient_key)
381 381
                 : $transient_key;
382
-            if(delete_transient($transient_key)){
382
+            if (delete_transient($transient_key)) {
383 383
                 unset($this->transients[$transient_key]);
384 384
                 $counter++;
385 385
             }
Please login to merge, or discard this patch.
core/services/cache/CacheStorageInterface.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -15,52 +15,52 @@
 block discarded – undo
15 15
 interface CacheStorageInterface
16 16
 {
17 17
 
18
-    /**
19
-     * Saves supplied data
20
-     * if an expiration is set, then it automatically schedules the cache for deletion
21
-     *
22
-     * @param string $key        [required]
23
-     * @param string $data       [required]
24
-     * @param int    $expiration number of seconds until the cache expires
25
-     * @return bool
26
-     */
27
-    public function add($key, $data, $expiration = 0);
18
+	/**
19
+	 * Saves supplied data
20
+	 * if an expiration is set, then it automatically schedules the cache for deletion
21
+	 *
22
+	 * @param string $key        [required]
23
+	 * @param string $data       [required]
24
+	 * @param int    $expiration number of seconds until the cache expires
25
+	 * @return bool
26
+	 */
27
+	public function add($key, $data, $expiration = 0);
28 28
 
29 29
 
30 30
 
31
-    /**
32
-     * retrieves cache data
33
-     * should automatically trigger early cache refresh for standard cache items
34
-     * in order to avoid cache stampedes on busy sites.
35
-     * For non-standard cache items like PHP Session data where early refreshing is not wanted,
36
-     * the $standard_cache parameter should be set to false when retrieving data
37
-     *
38
-     * @param string $key [required]
39
-     * @param bool   $standard_cache
40
-     * @return mixed
41
-     */
42
-    public function get($key, $standard_cache = true);
31
+	/**
32
+	 * retrieves cache data
33
+	 * should automatically trigger early cache refresh for standard cache items
34
+	 * in order to avoid cache stampedes on busy sites.
35
+	 * For non-standard cache items like PHP Session data where early refreshing is not wanted,
36
+	 * the $standard_cache parameter should be set to false when retrieving data
37
+	 *
38
+	 * @param string $key [required]
39
+	 * @param bool   $standard_cache
40
+	 * @return mixed
41
+	 */
42
+	public function get($key, $standard_cache = true);
43 43
 
44 44
 
45 45
 
46
-    /**
47
-     * delete a single cached item
48
-     *
49
-     * @param string $key [required] full or partial cache key to be deleted
50
-     */
51
-    public function delete($key);
46
+	/**
47
+	 * delete a single cached item
48
+	 *
49
+	 * @param string $key [required] full or partial cache key to be deleted
50
+	 */
51
+	public function delete($key);
52 52
 
53 53
 
54 54
 
55
-    /**
56
-     * delete multiple cached items
57
-     *
58
-     * @param array $keys           [required] array of full or partial cache keys to be deleted
59
-     * @param bool  $force_delete   [optional] if true, then will not check incoming keys against those being tracked
60
-     *                              and proceed directly to deleting those entries from the cache storage
61
-     * @return
62
-     */
63
-    public function deleteMany(array $keys, $force_delete = false);
55
+	/**
56
+	 * delete multiple cached items
57
+	 *
58
+	 * @param array $keys           [required] array of full or partial cache keys to be deleted
59
+	 * @param bool  $force_delete   [optional] if true, then will not check incoming keys against those being tracked
60
+	 *                              and proceed directly to deleting those entries from the cache storage
61
+	 * @return
62
+	 */
63
+	public function deleteMany(array $keys, $force_delete = false);
64 64
 
65 65
 }
66 66
 // End of file CacheStorageInterface.php
Please login to merge, or discard this patch.
core/EE_Session.core.php 3 patches
Doc Comments   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
      *
485 485
      * @access    public
486 486
      * @param    array $data
487
-     * @return    TRUE on success, FALSE on fail
487
+     * @return    boolean on success, FALSE on fail
488 488
      */
489 489
     public function set_session_data($data)
490 490
     {
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
     /**
512 512
      * @initiate session
513 513
      * @access   private
514
-     * @return TRUE on success, FALSE on fail
514
+     * @return boolean on success, FALSE on fail
515 515
      * @throws EE_Error
516 516
      * @throws InvalidArgumentException
517 517
      * @throws InvalidDataTypeException
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
      * @update session data  prior to saving to the db
747 747
      * @access public
748 748
      * @param bool $new_session
749
-     * @return TRUE on success, FALSE on fail
749
+     * @return boolean on success, FALSE on fail
750 750
      * @throws EE_Error
751 751
      * @throws InvalidArgumentException
752 752
      * @throws InvalidDataTypeException
@@ -847,7 +847,7 @@  discard block
 block discarded – undo
847 847
      * _save_session_to_db
848 848
      *
849 849
      * @access public
850
-     * @return string
850
+     * @return boolean
851 851
      * @throws EE_Error
852 852
      * @throws InvalidArgumentException
853 853
      * @throws InvalidDataTypeException
@@ -1023,7 +1023,7 @@  discard block
 block discarded – undo
1023 1023
      * @access public
1024 1024
      * @param array|mixed $data_to_reset
1025 1025
      * @param bool        $show_all_notices
1026
-     * @return TRUE on success, FALSE on fail
1026
+     * @return boolean on success, FALSE on fail
1027 1027
      */
1028 1028
     public function reset_data($data_to_reset = array(), $show_all_notices = false)
1029 1029
     {
Please login to merge, or discard this patch.
Indentation   +1219 added lines, -1219 removed lines patch added patch discarded remove patch
@@ -20,1225 +20,1225 @@  discard block
 block discarded – undo
20 20
 class EE_Session implements SessionIdentifierInterface
21 21
 {
22 22
 
23
-    const session_id_prefix    = 'ee_ssn_';
24
-
25
-    const hash_check_prefix    = 'ee_shc_';
26
-
27
-    const OPTION_NAME_SETTINGS = 'ee_session_settings';
28
-
29
-    /**
30
-     * instance of the EE_Session object
31
-     *
32
-     * @var EE_Session
33
-     */
34
-    private static $_instance;
35
-
36
-    /**
37
-     * @var CacheStorageInterface $cache_storage
38
-     */
39
-    protected $cache_storage;
40
-
41
-    /**
42
-     * EE_Encryption object
43
-     *
44
-     * @var EE_Encryption
45
-     */
46
-    protected $encryption;
47
-
48
-    /**
49
-     * the session id
50
-     *
51
-     * @var string
52
-     */
53
-    private $_sid;
54
-
55
-    /**
56
-     * session id salt
57
-     *
58
-     * @var string
59
-     */
60
-    private $_sid_salt;
61
-
62
-    /**
63
-     * session data
64
-     *
65
-     * @var array
66
-     */
67
-    private $_session_data = array();
68
-
69
-    /**
70
-     * how long an EE session lasts
71
-     * default session lifespan of 2 hours (for not so instant IPNs)
72
-     *
73
-     * @var int
74
-     */
75
-    private $_lifespan;
76
-
77
-    /**
78
-     * session expiration time as Unix timestamp in GMT
79
-     *
80
-     * @var int
81
-     */
82
-    private $_expiration;
83
-
84
-    /**
85
-     * whether or not session has expired at some point
86
-     *
87
-     * @var boolean
88
-     */
89
-    private $_expired = false;
90
-
91
-    /**
92
-     * current time as Unix timestamp in GMT
93
-     *
94
-     * @var int
95
-     */
96
-    private $_time;
97
-
98
-    /**
99
-     * whether to encrypt session data
100
-     *
101
-     * @var bool
102
-     */
103
-    private $_use_encryption;
104
-
105
-    /**
106
-     * well... according to the server...
107
-     *
108
-     * @var null
109
-     */
110
-    private $_user_agent;
111
-
112
-    /**
113
-     * do you really trust the server ?
114
-     *
115
-     * @var null
116
-     */
117
-    private $_ip_address;
118
-
119
-    /**
120
-     * current WP user_id
121
-     *
122
-     * @var null
123
-     */
124
-    private $_wp_user_id;
125
-
126
-    /**
127
-     * array for defining default session vars
128
-     *
129
-     * @var array
130
-     */
131
-    private $_default_session_vars = array(
132
-        'id'            => null,
133
-        'user_id'       => null,
134
-        'ip_address'    => null,
135
-        'user_agent'    => null,
136
-        'init_access'   => null,
137
-        'last_access'   => null,
138
-        'expiration'    => null,
139
-        'pages_visited' => array(),
140
-    );
141
-
142
-    /**
143
-     * timestamp for when last garbage collection cycle was performed
144
-     *
145
-     * @var int $_last_gc
146
-     */
147
-    private $_last_gc;
148
-
149
-
150
-
151
-    /**
152
-     * @singleton method used to instantiate class object
153
-     * @param CacheStorageInterface $cache_storage
154
-     * @param EE_Encryption         $encryption
155
-     * @return EE_Session
156
-     * @throws InvalidArgumentException
157
-     * @throws InvalidDataTypeException
158
-     * @throws InvalidInterfaceException
159
-     */
160
-    public static function instance(
161
-        CacheStorageInterface $cache_storage = null,
162
-        EE_Encryption $encryption = null
163
-    ) {
164
-        // check if class object is instantiated
165
-        // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
166
-        // add_filter( 'FHEE_load_EE_Session', '__return_false' );
167
-        if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
168
-            self::$_instance = new self($cache_storage, $encryption);
169
-        }
170
-        return self::$_instance;
171
-    }
172
-
173
-
174
-
175
-    /**
176
-     * protected constructor to prevent direct creation
177
-     *
178
-     * @param CacheStorageInterface $cache_storage
179
-     * @param EE_Encryption         $encryption
180
-     * @throws InvalidArgumentException
181
-     * @throws InvalidDataTypeException
182
-     * @throws InvalidInterfaceException
183
-     */
184
-    protected function __construct(CacheStorageInterface $cache_storage, EE_Encryption $encryption = null)
185
-    {
186
-
187
-        // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
188
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
189
-            return;
190
-        }
191
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
192
-        if (! defined('ESPRESSO_SESSION')) {
193
-            define('ESPRESSO_SESSION', true);
194
-        }
195
-        // default session lifespan in seconds
196
-        $this->_lifespan = apply_filters(
197
-                               'FHEE__EE_Session__construct___lifespan',
198
-                               60 * MINUTE_IN_SECONDS
199
-                           ) + 1;
200
-        /*
23
+	const session_id_prefix    = 'ee_ssn_';
24
+
25
+	const hash_check_prefix    = 'ee_shc_';
26
+
27
+	const OPTION_NAME_SETTINGS = 'ee_session_settings';
28
+
29
+	/**
30
+	 * instance of the EE_Session object
31
+	 *
32
+	 * @var EE_Session
33
+	 */
34
+	private static $_instance;
35
+
36
+	/**
37
+	 * @var CacheStorageInterface $cache_storage
38
+	 */
39
+	protected $cache_storage;
40
+
41
+	/**
42
+	 * EE_Encryption object
43
+	 *
44
+	 * @var EE_Encryption
45
+	 */
46
+	protected $encryption;
47
+
48
+	/**
49
+	 * the session id
50
+	 *
51
+	 * @var string
52
+	 */
53
+	private $_sid;
54
+
55
+	/**
56
+	 * session id salt
57
+	 *
58
+	 * @var string
59
+	 */
60
+	private $_sid_salt;
61
+
62
+	/**
63
+	 * session data
64
+	 *
65
+	 * @var array
66
+	 */
67
+	private $_session_data = array();
68
+
69
+	/**
70
+	 * how long an EE session lasts
71
+	 * default session lifespan of 2 hours (for not so instant IPNs)
72
+	 *
73
+	 * @var int
74
+	 */
75
+	private $_lifespan;
76
+
77
+	/**
78
+	 * session expiration time as Unix timestamp in GMT
79
+	 *
80
+	 * @var int
81
+	 */
82
+	private $_expiration;
83
+
84
+	/**
85
+	 * whether or not session has expired at some point
86
+	 *
87
+	 * @var boolean
88
+	 */
89
+	private $_expired = false;
90
+
91
+	/**
92
+	 * current time as Unix timestamp in GMT
93
+	 *
94
+	 * @var int
95
+	 */
96
+	private $_time;
97
+
98
+	/**
99
+	 * whether to encrypt session data
100
+	 *
101
+	 * @var bool
102
+	 */
103
+	private $_use_encryption;
104
+
105
+	/**
106
+	 * well... according to the server...
107
+	 *
108
+	 * @var null
109
+	 */
110
+	private $_user_agent;
111
+
112
+	/**
113
+	 * do you really trust the server ?
114
+	 *
115
+	 * @var null
116
+	 */
117
+	private $_ip_address;
118
+
119
+	/**
120
+	 * current WP user_id
121
+	 *
122
+	 * @var null
123
+	 */
124
+	private $_wp_user_id;
125
+
126
+	/**
127
+	 * array for defining default session vars
128
+	 *
129
+	 * @var array
130
+	 */
131
+	private $_default_session_vars = array(
132
+		'id'            => null,
133
+		'user_id'       => null,
134
+		'ip_address'    => null,
135
+		'user_agent'    => null,
136
+		'init_access'   => null,
137
+		'last_access'   => null,
138
+		'expiration'    => null,
139
+		'pages_visited' => array(),
140
+	);
141
+
142
+	/**
143
+	 * timestamp for when last garbage collection cycle was performed
144
+	 *
145
+	 * @var int $_last_gc
146
+	 */
147
+	private $_last_gc;
148
+
149
+
150
+
151
+	/**
152
+	 * @singleton method used to instantiate class object
153
+	 * @param CacheStorageInterface $cache_storage
154
+	 * @param EE_Encryption         $encryption
155
+	 * @return EE_Session
156
+	 * @throws InvalidArgumentException
157
+	 * @throws InvalidDataTypeException
158
+	 * @throws InvalidInterfaceException
159
+	 */
160
+	public static function instance(
161
+		CacheStorageInterface $cache_storage = null,
162
+		EE_Encryption $encryption = null
163
+	) {
164
+		// check if class object is instantiated
165
+		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
166
+		// add_filter( 'FHEE_load_EE_Session', '__return_false' );
167
+		if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
168
+			self::$_instance = new self($cache_storage, $encryption);
169
+		}
170
+		return self::$_instance;
171
+	}
172
+
173
+
174
+
175
+	/**
176
+	 * protected constructor to prevent direct creation
177
+	 *
178
+	 * @param CacheStorageInterface $cache_storage
179
+	 * @param EE_Encryption         $encryption
180
+	 * @throws InvalidArgumentException
181
+	 * @throws InvalidDataTypeException
182
+	 * @throws InvalidInterfaceException
183
+	 */
184
+	protected function __construct(CacheStorageInterface $cache_storage, EE_Encryption $encryption = null)
185
+	{
186
+
187
+		// session loading is turned ON by default, but prior to the init hook, can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
188
+		if (! apply_filters('FHEE_load_EE_Session', true)) {
189
+			return;
190
+		}
191
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
192
+		if (! defined('ESPRESSO_SESSION')) {
193
+			define('ESPRESSO_SESSION', true);
194
+		}
195
+		// default session lifespan in seconds
196
+		$this->_lifespan = apply_filters(
197
+							   'FHEE__EE_Session__construct___lifespan',
198
+							   60 * MINUTE_IN_SECONDS
199
+						   ) + 1;
200
+		/*
201 201
          * do something like the following to adjust the session lifespan:
202 202
          * 		public static function session_lifespan() {
203 203
          * 			return 15 * MINUTE_IN_SECONDS;
204 204
          * 		}
205 205
          */
206
-        // retrieve session options from db
207
-        $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
208
-        if (! empty($session_settings)) {
209
-            // cycle though existing session options
210
-            foreach ($session_settings as $var_name => $session_setting) {
211
-                // set values for class properties
212
-                $var_name          = '_' . $var_name;
213
-                $this->{$var_name} = $session_setting;
214
-            }
215
-        }
216
-        $this->cache_storage = $cache_storage;
217
-        // are we using encryption?
218
-        $this->_use_encryption = $encryption instanceof EE_Encryption
219
-                                 && EE_Registry::instance()->CFG->admin->encode_session_data();
220
-        // \EEH_Debug_Tools::printr($this->_use_encryption, '$this->_use_encryption', __FILE__, __LINE__);
221
-        // encrypt data via: $this->encryption->encrypt();
222
-        $this->encryption = $encryption;
223
-        // filter hook allows outside functions/classes/plugins to change default empty cart
224
-        $extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
225
-        array_merge($this->_default_session_vars, $extra_default_session_vars);
226
-        // apply default session vars
227
-        $this->_set_defaults();
228
-        add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
229
-        // check request for 'clear_session' param
230
-        add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
231
-        // once everything is all said and done,
232
-        add_action('shutdown', array($this, 'update'), 100);
233
-        add_action('shutdown', array($this, 'garbageCollection'), 1000);
234
-        $this->configure_garbage_collection_filters();
235
-    }
236
-
237
-
238
-
239
-    /**
240
-     * @return void
241
-     * @throws EE_Error
242
-     * @throws InvalidArgumentException
243
-     * @throws InvalidDataTypeException
244
-     * @throws InvalidInterfaceException
245
-     * @throws InvalidSessionDataException
246
-     */
247
-    public function open_session()
248
-    {
249
-        // check for existing session and retrieve it from db
250
-        if (! $this->_espresso_session()) {
251
-            // or just start a new one
252
-            $this->_create_espresso_session();
253
-        }
254
-    }
255
-
256
-
257
-
258
-    /**
259
-     * @return bool
260
-     */
261
-    public function expired()
262
-    {
263
-        return $this->_expired;
264
-    }
265
-
266
-
267
-
268
-    /**
269
-     * @return void
270
-     */
271
-    public function reset_expired()
272
-    {
273
-        $this->_expired = false;
274
-    }
275
-
276
-
277
-    /**
278
-     * @return int
279
-     */
280
-    public function expiration()
281
-    {
282
-        return $this->_expiration;
283
-    }
284
-
285
-
286
-
287
-    /**
288
-     * @return int
289
-     */
290
-    public function extension()
291
-    {
292
-        return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
293
-    }
294
-
295
-
296
-
297
-    /**
298
-     * @param int $time number of seconds to add to session expiration
299
-     */
300
-    public function extend_expiration($time = 0)
301
-    {
302
-        $time              = $time ? $time : $this->extension();
303
-        $this->_expiration += absint($time);
304
-    }
305
-
306
-
307
-
308
-    /**
309
-     * @return int
310
-     */
311
-    public function lifespan()
312
-    {
313
-        return $this->_lifespan;
314
-    }
315
-
316
-
317
-
318
-    /**
319
-     * This just sets some defaults for the _session data property
320
-     *
321
-     * @access private
322
-     * @return void
323
-     */
324
-    private function _set_defaults()
325
-    {
326
-        // set some defaults
327
-        foreach ($this->_default_session_vars as $key => $default_var) {
328
-            if (is_array($default_var)) {
329
-                $this->_session_data[ $key ] = array();
330
-            } else {
331
-                $this->_session_data[ $key ] = '';
332
-            }
333
-        }
334
-    }
206
+		// retrieve session options from db
207
+		$session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
208
+		if (! empty($session_settings)) {
209
+			// cycle though existing session options
210
+			foreach ($session_settings as $var_name => $session_setting) {
211
+				// set values for class properties
212
+				$var_name          = '_' . $var_name;
213
+				$this->{$var_name} = $session_setting;
214
+			}
215
+		}
216
+		$this->cache_storage = $cache_storage;
217
+		// are we using encryption?
218
+		$this->_use_encryption = $encryption instanceof EE_Encryption
219
+								 && EE_Registry::instance()->CFG->admin->encode_session_data();
220
+		// \EEH_Debug_Tools::printr($this->_use_encryption, '$this->_use_encryption', __FILE__, __LINE__);
221
+		// encrypt data via: $this->encryption->encrypt();
222
+		$this->encryption = $encryption;
223
+		// filter hook allows outside functions/classes/plugins to change default empty cart
224
+		$extra_default_session_vars = apply_filters('FHEE__EE_Session__construct__extra_default_session_vars', array());
225
+		array_merge($this->_default_session_vars, $extra_default_session_vars);
226
+		// apply default session vars
227
+		$this->_set_defaults();
228
+		add_action('AHEE__EE_System__initialize', array($this, 'open_session'));
229
+		// check request for 'clear_session' param
230
+		add_action('AHEE__EE_Request_Handler__construct__complete', array($this, 'wp_loaded'));
231
+		// once everything is all said and done,
232
+		add_action('shutdown', array($this, 'update'), 100);
233
+		add_action('shutdown', array($this, 'garbageCollection'), 1000);
234
+		$this->configure_garbage_collection_filters();
235
+	}
236
+
237
+
238
+
239
+	/**
240
+	 * @return void
241
+	 * @throws EE_Error
242
+	 * @throws InvalidArgumentException
243
+	 * @throws InvalidDataTypeException
244
+	 * @throws InvalidInterfaceException
245
+	 * @throws InvalidSessionDataException
246
+	 */
247
+	public function open_session()
248
+	{
249
+		// check for existing session and retrieve it from db
250
+		if (! $this->_espresso_session()) {
251
+			// or just start a new one
252
+			$this->_create_espresso_session();
253
+		}
254
+	}
255
+
256
+
257
+
258
+	/**
259
+	 * @return bool
260
+	 */
261
+	public function expired()
262
+	{
263
+		return $this->_expired;
264
+	}
265
+
266
+
267
+
268
+	/**
269
+	 * @return void
270
+	 */
271
+	public function reset_expired()
272
+	{
273
+		$this->_expired = false;
274
+	}
275
+
276
+
277
+	/**
278
+	 * @return int
279
+	 */
280
+	public function expiration()
281
+	{
282
+		return $this->_expiration;
283
+	}
284
+
285
+
286
+
287
+	/**
288
+	 * @return int
289
+	 */
290
+	public function extension()
291
+	{
292
+		return apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS);
293
+	}
294
+
295
+
296
+
297
+	/**
298
+	 * @param int $time number of seconds to add to session expiration
299
+	 */
300
+	public function extend_expiration($time = 0)
301
+	{
302
+		$time              = $time ? $time : $this->extension();
303
+		$this->_expiration += absint($time);
304
+	}
305
+
306
+
307
+
308
+	/**
309
+	 * @return int
310
+	 */
311
+	public function lifespan()
312
+	{
313
+		return $this->_lifespan;
314
+	}
315
+
316
+
317
+
318
+	/**
319
+	 * This just sets some defaults for the _session data property
320
+	 *
321
+	 * @access private
322
+	 * @return void
323
+	 */
324
+	private function _set_defaults()
325
+	{
326
+		// set some defaults
327
+		foreach ($this->_default_session_vars as $key => $default_var) {
328
+			if (is_array($default_var)) {
329
+				$this->_session_data[ $key ] = array();
330
+			} else {
331
+				$this->_session_data[ $key ] = '';
332
+			}
333
+		}
334
+	}
335 335
 
336 336
 
337
-
338
-    /**
339
-     * @retrieve  session data
340
-     * @access    public
341
-     * @return    string
342
-     */
343
-    public function id()
344
-    {
345
-        return $this->_sid;
346
-    }
337
+
338
+	/**
339
+	 * @retrieve  session data
340
+	 * @access    public
341
+	 * @return    string
342
+	 */
343
+	public function id()
344
+	{
345
+		return $this->_sid;
346
+	}
347 347
 
348 348
 
349 349
 
350
-    /**
351
-     * @param \EE_Cart $cart
352
-     * @return bool
353
-     */
354
-    public function set_cart(EE_Cart $cart)
355
-    {
356
-        $this->_session_data['cart'] = $cart;
357
-        return true;
358
-    }
350
+	/**
351
+	 * @param \EE_Cart $cart
352
+	 * @return bool
353
+	 */
354
+	public function set_cart(EE_Cart $cart)
355
+	{
356
+		$this->_session_data['cart'] = $cart;
357
+		return true;
358
+	}
359 359
 
360 360
 
361 361
 
362
-    /**
363
-     * reset_cart
364
-     */
365
-    public function reset_cart()
366
-    {
367
-        do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
368
-        $this->_session_data['cart'] = null;
369
-    }
370
-
371
-
372
-
373
-    /**
374
-     * @return \EE_Cart
375
-     */
376
-    public function cart()
377
-    {
378
-        return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
379
-            ? $this->_session_data['cart']
380
-            : null;
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * @param \EE_Checkout $checkout
387
-     * @return bool
388
-     */
389
-    public function set_checkout(EE_Checkout $checkout)
390
-    {
391
-        $this->_session_data['checkout'] = $checkout;
392
-        return true;
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     * reset_checkout
399
-     */
400
-    public function reset_checkout()
401
-    {
402
-        do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
403
-        $this->_session_data['checkout'] = null;
404
-    }
405
-
406
-
407
-
408
-    /**
409
-     * @return \EE_Checkout
410
-     */
411
-    public function checkout()
412
-    {
413
-        return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
414
-            ? $this->_session_data['checkout']
415
-            : null;
416
-    }
417
-
418
-
419
-
420
-    /**
421
-     * @param \EE_Transaction $transaction
422
-     * @return bool
423
-     * @throws EE_Error
424
-     */
425
-    public function set_transaction(EE_Transaction $transaction)
426
-    {
427
-        // first remove the session from the transaction before we save the transaction in the session
428
-        $transaction->set_txn_session_data(null);
429
-        $this->_session_data['transaction'] = $transaction;
430
-        return true;
431
-    }
432
-
433
-
434
-
435
-    /**
436
-     * reset_transaction
437
-     */
438
-    public function reset_transaction()
439
-    {
440
-        do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
441
-        $this->_session_data['transaction'] = null;
442
-    }
443
-
444
-
445
-
446
-    /**
447
-     * @return \EE_Transaction
448
-     */
449
-    public function transaction()
450
-    {
451
-        return isset($this->_session_data['transaction'])
452
-               && $this->_session_data['transaction'] instanceof EE_Transaction
453
-            ? $this->_session_data['transaction']
454
-            : null;
455
-    }
456
-
457
-
458
-
459
-    /**
460
-     * retrieve session data
461
-     *
462
-     * @access    public
463
-     * @param null $key
464
-     * @param bool $reset_cache
465
-     * @return    array
466
-     */
467
-    public function get_session_data($key = null, $reset_cache = false)
468
-    {
469
-        if ($reset_cache) {
470
-            $this->reset_cart();
471
-            $this->reset_checkout();
472
-            $this->reset_transaction();
473
-        }
474
-        if (! empty($key)) {
475
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
476
-        }
477
-        return $this->_session_data;
478
-    }
479
-
480
-
481
-
482
-    /**
483
-     * set session data
484
-     *
485
-     * @access    public
486
-     * @param    array $data
487
-     * @return    TRUE on success, FALSE on fail
488
-     */
489
-    public function set_session_data($data)
490
-    {
491
-
492
-        // nothing ??? bad data ??? go home!
493
-        if (empty($data) || ! is_array($data)) {
494
-            EE_Error::add_error(__('No session data or invalid session data was provided.', 'event_espresso'), __FILE__,
495
-                __FUNCTION__, __LINE__);
496
-            return false;
497
-        }
498
-        foreach ($data as $key => $value) {
499
-            if (isset($this->_default_session_vars[ $key ])) {
500
-                EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
501
-                    'event_espresso'), $key), __FILE__, __FUNCTION__, __LINE__);
502
-                return false;
503
-            }
504
-            $this->_session_data[ $key ] = $value;
505
-        }
506
-        return true;
507
-    }
508
-
509
-
510
-
511
-    /**
512
-     * @initiate session
513
-     * @access   private
514
-     * @return TRUE on success, FALSE on fail
515
-     * @throws EE_Error
516
-     * @throws InvalidArgumentException
517
-     * @throws InvalidDataTypeException
518
-     * @throws InvalidInterfaceException
519
-     * @throws InvalidSessionDataException
520
-     */
521
-    private function _espresso_session()
522
-    {
523
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
-        // check that session has started
525
-        if (session_id() === '') {
526
-            //starts a new session if one doesn't already exist, or re-initiates an existing one
527
-            session_start();
528
-        }
529
-        // get our modified session ID
530
-        $this->_sid = $this->_generate_session_id();
531
-        // and the visitors IP
532
-        $this->_ip_address = $this->_visitor_ip();
533
-        // set the "user agent"
534
-        $this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr($_SERVER['HTTP_USER_AGENT']) : false;
535
-        // now let's retrieve what's in the db
536
-        $session_data = $this->_retrieve_session_data();
537
-        if (! empty($session_data)) {
538
-            // get the current time in UTC
539
-            $this->_time = $this->_time !== null ? $this->_time : time();
540
-            // and reset the session expiration
541
-            $this->_expiration = isset($session_data['expiration'])
542
-                ? $session_data['expiration']
543
-                : $this->_time + $this->_lifespan;
544
-        } else {
545
-            // set initial site access time and the session expiration
546
-            $this->_set_init_access_and_expiration();
547
-            // set referer
548
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
549
-                ? esc_attr($_SERVER['HTTP_REFERER'])
550
-                : '';
551
-            // no previous session = go back and create one (on top of the data above)
552
-            return false;
553
-        }
554
-        // now the user agent
555
-        if ($session_data['user_agent'] !== $this->_user_agent) {
556
-            return false;
557
-        }
558
-        // wait a minute... how old are you?
559
-        if ($this->_time > $this->_expiration) {
560
-            // yer too old fer me!
561
-            $this->_expired = true;
562
-            // wipe out everything that isn't a default session datum
563
-            $this->clear_session(__CLASS__, __FUNCTION__);
564
-        }
565
-        // make event espresso session data available to plugin
566
-        $this->_session_data = array_merge($this->_session_data, $session_data);
567
-        return true;
568
-    }
569
-
570
-
571
-
572
-    /**
573
-     * _get_session_data
574
-     * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
575
-     * databases
576
-     *
577
-     * @return array
578
-     * @throws EE_Error
579
-     * @throws InvalidArgumentException
580
-     * @throws InvalidSessionDataException
581
-     * @throws InvalidDataTypeException
582
-     * @throws InvalidInterfaceException
583
-     */
584
-    protected function _retrieve_session_data()
585
-    {
586
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
587
-        try {
588
-            // we're using WP's Transient API to store session data using the PHP session ID as the option name
589
-            $session_data = $this->cache_storage->get($ssn_key, false);
590
-            if (empty($session_data)) {
591
-                return array();
592
-            }
593
-            if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
594
-                $hash_check = $this->cache_storage->get(
595
-                    EE_Session::hash_check_prefix . $this->_sid,
596
-                    false
597
-                );
598
-                if ($hash_check && $hash_check !== md5($session_data)) {
599
-                    EE_Error::add_error(
600
-                        sprintf(
601
-                            __(
602
-                                'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
603
-                                'event_espresso'
604
-                            ),
605
-                            EE_Session::session_id_prefix . $this->_sid
606
-                        ),
607
-                        __FILE__, __FUNCTION__, __LINE__
608
-                    );
609
-                }
610
-            }
611
-        } catch (Exception $e) {
612
-            // let's just eat that error for now and attempt to correct any corrupted data
613
-            global $wpdb;
614
-            $row          = $wpdb->get_row(
615
-                $wpdb->prepare(
616
-                    "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
617
-                    '_transient_' . $ssn_key
618
-                )
619
-            );
620
-            $session_data = is_object($row) ? $row->option_value : null;
621
-            if ($session_data) {
622
-                $session_data = preg_replace_callback(
623
-                    '!s:(d+):"(.*?)";!',
624
-                    function ($match)
625
-                    {
626
-                        return $match[1] === strlen($match[2])
627
-                            ? $match[0]
628
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
629
-                    },
630
-                    $session_data
631
-                );
632
-            }
633
-            $session_data = maybe_unserialize($session_data);
634
-        }
635
-        // in case the data is encoded... try to decode it
636
-        $session_data = $this->encryption instanceof EE_Encryption
637
-            ? $this->encryption->base64_string_decode($session_data)
638
-            : $session_data;
639
-        if (! is_array($session_data)) {
640
-            try {
641
-                $session_data = maybe_unserialize($session_data);
642
-            } catch (Exception $e) {
643
-                $msg = esc_html__(
644
-                    'An error occurred while attempting to unserialize the session data.',
645
-                    'event_espresso'
646
-                );
647
-                $msg .= WP_DEBUG
648
-                    ? '<br><pre>'
649
-                      . print_r($session_data, true)
650
-                      . '</pre><br>'
651
-                      . $this->find_serialize_error($session_data)
652
-                    : '';
653
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
654
-                throw new InvalidSessionDataException($msg, 0, $e);
655
-            }
656
-        }
657
-        // just a check to make sure the session array is indeed an array
658
-        if (! is_array($session_data)) {
659
-            // no?!?! then something is wrong
660
-            $msg = esc_html__(
661
-                'The session data is missing, invalid, or corrupted.',
662
-                'event_espresso'
663
-            );
664
-            $msg .= WP_DEBUG
665
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
666
-                : '';
667
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
668
-            throw new InvalidSessionDataException($msg);
669
-        }
670
-        if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
671
-            $session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
672
-                $session_data['transaction']
673
-            );
674
-        }
675
-        return $session_data;
676
-    }
677
-
678
-
679
-
680
-    /**
681
-     * _generate_session_id
682
-     * Retrieves the PHP session id either directly from the PHP session,
683
-     * or from the $_REQUEST array if it was passed in from an AJAX request.
684
-     * The session id is then salted and hashed (mmm sounds tasty)
685
-     * so that it can be safely used as a $_REQUEST param
686
-     *
687
-     * @return string
688
-     */
689
-    protected function _generate_session_id()
690
-    {
691
-        // check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
692
-        if (isset($_REQUEST['EESID'])) {
693
-            $session_id = sanitize_text_field($_REQUEST['EESID']);
694
-        } else {
695
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
696
-        }
697
-        return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
698
-    }
699
-
700
-
701
-
702
-    /**
703
-     * _get_sid_salt
704
-     *
705
-     * @return string
706
-     */
707
-    protected function _get_sid_salt()
708
-    {
709
-        // was session id salt already saved to db ?
710
-        if (empty($this->_sid_salt)) {
711
-            // no?  then maybe use WP defined constant
712
-            if (defined('AUTH_SALT')) {
713
-                $this->_sid_salt = AUTH_SALT;
714
-            }
715
-            // if salt doesn't exist or is too short
716
-            if (strlen($this->_sid_salt) < 32) {
717
-                // create a new one
718
-                $this->_sid_salt = wp_generate_password(64);
719
-            }
720
-            // and save it as a permanent session setting
721
-            $this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
722
-        }
723
-        return $this->_sid_salt;
724
-    }
725
-
726
-
727
-
728
-    /**
729
-     * _set_init_access_and_expiration
730
-     *
731
-     * @return void
732
-     */
733
-    protected function _set_init_access_and_expiration()
734
-    {
735
-        $this->_time       = time();
736
-        $this->_expiration = $this->_time + $this->_lifespan;
737
-        // set initial site access time
738
-        $this->_session_data['init_access'] = $this->_time;
739
-        // and the session expiration
740
-        $this->_session_data['expiration'] = $this->_expiration;
741
-    }
742
-
743
-
744
-
745
-    /**
746
-     * @update session data  prior to saving to the db
747
-     * @access public
748
-     * @param bool $new_session
749
-     * @return TRUE on success, FALSE on fail
750
-     * @throws EE_Error
751
-     * @throws InvalidArgumentException
752
-     * @throws InvalidDataTypeException
753
-     * @throws InvalidInterfaceException
754
-     */
755
-    public function update($new_session = false)
756
-    {
757
-        $this->_session_data = $this->_session_data !== null
758
-                               && is_array($this->_session_data)
759
-                               && isset($this->_session_data['id'])
760
-            ? $this->_session_data
761
-            : array();
762
-        if (empty($this->_session_data)) {
763
-            $this->_set_defaults();
764
-        }
765
-        $session_data = array();
766
-        foreach ($this->_session_data as $key => $value) {
767
-
768
-            switch ($key) {
769
-
770
-                case 'id' :
771
-                    // session ID
772
-                    $session_data['id'] = $this->_sid;
773
-                    break;
774
-                case 'ip_address' :
775
-                    // visitor ip address
776
-                    $session_data['ip_address'] = $this->_visitor_ip();
777
-                    break;
778
-                case 'user_agent' :
779
-                    // visitor user_agent
780
-                    $session_data['user_agent'] = $this->_user_agent;
781
-                    break;
782
-                case 'init_access' :
783
-                    $session_data['init_access'] = absint($value);
784
-                    break;
785
-                case 'last_access' :
786
-                    // current access time
787
-                    $session_data['last_access'] = $this->_time;
788
-                    break;
789
-                case 'expiration' :
790
-                    // when the session expires
791
-                    $session_data['expiration'] = ! empty($this->_expiration)
792
-                        ? $this->_expiration
793
-                        : $session_data['init_access'] + $this->_lifespan;
794
-                    break;
795
-                case 'user_id' :
796
-                    // current user if logged in
797
-                    $session_data['user_id'] = $this->_wp_user_id();
798
-                    break;
799
-                case 'pages_visited' :
800
-                    $page_visit = $this->_get_page_visit();
801
-                    if ($page_visit) {
802
-                        // set pages visited where the first will be the http referrer
803
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
804
-                        // we'll only save the last 10 page visits.
805
-                        $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
806
-                    }
807
-                    break;
808
-                default :
809
-                    // carry any other data over
810
-                    $session_data[ $key ] = $this->_session_data[ $key ];
811
-            }
812
-        }
813
-        $this->_session_data = $session_data;
814
-        // creating a new session does not require saving to the db just yet
815
-        if (! $new_session) {
816
-            // ready? let's save
817
-            if ($this->_save_session_to_db()) {
818
-                return true;
819
-            }
820
-            return false;
821
-        }
822
-        // meh, why not?
823
-        return true;
824
-    }
825
-
826
-
827
-
828
-    /**
829
-     * @create session data array
830
-     * @access public
831
-     * @return bool
832
-     * @throws EE_Error
833
-     * @throws InvalidArgumentException
834
-     * @throws InvalidDataTypeException
835
-     * @throws InvalidInterfaceException
836
-     */
837
-    private function _create_espresso_session()
838
-    {
839
-        do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
840
-        // use the update function for now with $new_session arg set to TRUE
841
-        return $this->update(true) ? true : false;
842
-    }
843
-
844
-
845
-
846
-    /**
847
-     * _save_session_to_db
848
-     *
849
-     * @access public
850
-     * @return string
851
-     * @throws EE_Error
852
-     * @throws InvalidArgumentException
853
-     * @throws InvalidDataTypeException
854
-     * @throws InvalidInterfaceException
855
-     */
856
-    private function _save_session_to_db()
857
-    {
858
-        if (
859
-            // if the current request is NOT one of the following
860
-        ! (
861
-            // an an AJAX request from the frontend
862
-            EE_Registry::instance()->REQ->front_ajax
863
-            || (
864
-                // OR an admin request that is NOT AJAX
865
-                ! (defined('DOING_AJAX') && DOING_AJAX)
866
-                && is_admin()
867
-            )
868
-            || (
869
-                // OR an espresso page
870
-                EE_Registry::instance()->REQ instanceof EE_Request_Handler
871
-                && EE_Registry::instance()->REQ->is_espresso_page()
872
-            )
873
-        )
874
-        ) {
875
-            return false;
876
-        }
877
-        $transaction = $this->transaction();
878
-        if ($transaction instanceof EE_Transaction) {
879
-            if (! $transaction->ID()) {
880
-                $transaction->save();
881
-            }
882
-            $this->_session_data['transaction'] = $transaction->ID();
883
-        }
884
-        // then serialize all of our session data
885
-        $session_data = serialize($this->_session_data);
886
-        // do we need to also encode it to avoid corrupted data when saved to the db?
887
-        $session_data = $this->_use_encryption
888
-            ? $this->encryption->base64_string_encode($session_data)
889
-            : $session_data;
890
-        // maybe save hash check
891
-        if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
892
-            $this->cache_storage->add(
893
-                EE_Session::hash_check_prefix . $this->_sid,
894
-                md5($session_data),
895
-                $this->_lifespan
896
-            );
897
-        }
898
-        // we're using the Transient API for storing session data,
899
-        return $this->cache_storage->add(
900
-            EE_Session::session_id_prefix . $this->_sid,
901
-            $session_data,
902
-            $this->_lifespan
903
-        );
904
-    }
905
-
906
-
907
-
908
-    /**
909
-     * _visitor_ip
910
-     *    attempt to get IP address of current visitor from server
911
-     * plz see: http://stackoverflow.com/a/2031935/1475279
912
-     *
913
-     * @access public
914
-     * @return string
915
-     */
916
-    private function _visitor_ip()
917
-    {
918
-        $visitor_ip  = '0.0.0.0';
919
-        $server_keys = array(
920
-            'HTTP_CLIENT_IP',
921
-            'HTTP_X_FORWARDED_FOR',
922
-            'HTTP_X_FORWARDED',
923
-            'HTTP_X_CLUSTER_CLIENT_IP',
924
-            'HTTP_FORWARDED_FOR',
925
-            'HTTP_FORWARDED',
926
-            'REMOTE_ADDR',
927
-        );
928
-        foreach ($server_keys as $key) {
929
-            if (isset($_SERVER[ $key ])) {
930
-                foreach (array_map('trim', explode(',', $_SERVER[ $key ])) as $ip) {
931
-                    if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
932
-                        $visitor_ip = $ip;
933
-                    }
934
-                }
935
-            }
936
-        }
937
-        return $visitor_ip;
938
-    }
939
-
940
-
941
-
942
-    /**
943
-     * @get    the full page request the visitor is accessing
944
-     * @access public
945
-     * @return string
946
-     */
947
-    public function _get_page_visit()
948
-    {
949
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
950
-        // check for request url
951
-        if (isset($_SERVER['REQUEST_URI'])) {
952
-            $http_host   = '';
953
-            $page_id     = '?';
954
-            $e_reg       = '';
955
-            $request_uri = esc_url($_SERVER['REQUEST_URI']);
956
-            $ru_bits     = explode('?', $request_uri);
957
-            $request_uri = $ru_bits[0];
958
-            // check for and grab host as well
959
-            if (isset($_SERVER['HTTP_HOST'])) {
960
-                $http_host = esc_url($_SERVER['HTTP_HOST']);
961
-            }
962
-            // check for page_id in SERVER REQUEST
963
-            if (isset($_REQUEST['page_id'])) {
964
-                // rebuild $e_reg without any of the extra parameters
965
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
966
-            }
967
-            // check for $e_reg in SERVER REQUEST
968
-            if (isset($_REQUEST['ee'])) {
969
-                // rebuild $e_reg without any of the extra parameters
970
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
971
-            }
972
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
973
-        }
974
-        return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
975
-    }
976
-
977
-
978
-
979
-    /**
980
-     * @the    current wp user id
981
-     * @access public
982
-     * @return int
983
-     */
984
-    public function _wp_user_id()
985
-    {
986
-        // if I need to explain the following lines of code, then you shouldn't be looking at this!
987
-        $this->_wp_user_id = get_current_user_id();
988
-        return $this->_wp_user_id;
989
-    }
990
-
991
-
992
-
993
-    /**
994
-     * Clear EE_Session data
995
-     *
996
-     * @access public
997
-     * @param string $class
998
-     * @param string $function
999
-     * @return void
1000
-     * @throws EE_Error
1001
-     * @throws InvalidArgumentException
1002
-     * @throws InvalidDataTypeException
1003
-     * @throws InvalidInterfaceException
1004
-     */
1005
-    public function clear_session($class = '', $function = '')
1006
-    {
1007
-        //echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
1008
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1009
-        $this->reset_cart();
1010
-        $this->reset_checkout();
1011
-        $this->reset_transaction();
1012
-        // wipe out everything that isn't a default session datum
1013
-        $this->reset_data(array_keys($this->_session_data));
1014
-        // reset initial site access time and the session expiration
1015
-        $this->_set_init_access_and_expiration();
1016
-        $this->_save_session_to_db();
1017
-    }
1018
-
1019
-
1020
-
1021
-    /**
1022
-     * @resets all non-default session vars
1023
-     * @access public
1024
-     * @param array|mixed $data_to_reset
1025
-     * @param bool        $show_all_notices
1026
-     * @return TRUE on success, FALSE on fail
1027
-     */
1028
-    public function reset_data($data_to_reset = array(), $show_all_notices = false)
1029
-    {
1030
-        // if $data_to_reset is not in an array, then put it in one
1031
-        if (! is_array($data_to_reset)) {
1032
-            $data_to_reset = array($data_to_reset);
1033
-        }
1034
-        // nothing ??? go home!
1035
-        if (empty($data_to_reset)) {
1036
-            EE_Error::add_error(__('No session data could be reset, because no session var name was provided.',
1037
-                'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1038
-            return false;
1039
-        }
1040
-        $return_value = true;
1041
-        // since $data_to_reset is an array, cycle through the values
1042
-        foreach ($data_to_reset as $reset) {
1043
-
1044
-            // first check to make sure it is a valid session var
1045
-            if (isset($this->_session_data[ $reset ])) {
1046
-                // then check to make sure it is not a default var
1047
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1048
-                    // remove session var
1049
-                    unset($this->_session_data[ $reset ]);
1050
-                    if ($show_all_notices) {
1051
-                        EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1052
-                            $reset), __FILE__, __FUNCTION__, __LINE__);
1053
-                    }
1054
-                } else {
1055
-                    // yeeeeeeeeerrrrrrrrrrr OUT !!!!
1056
-                    if ($show_all_notices) {
1057
-                        EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
1058
-                            'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1059
-                    }
1060
-                    $return_value = false;
1061
-                }
1062
-            } elseif ($show_all_notices) {
1063
-                // oops! that session var does not exist!
1064
-                EE_Error::add_error(sprintf(__('The session item provided, %s, is invalid or does not exist.',
1065
-                    'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1066
-                $return_value = false;
1067
-            }
1068
-        } // end of foreach
1069
-        return $return_value;
1070
-    }
1071
-
1072
-
1073
-
1074
-    /**
1075
-     *   wp_loaded
1076
-     *
1077
-     * @access public
1078
-     * @throws EE_Error
1079
-     * @throws InvalidDataTypeException
1080
-     * @throws InvalidInterfaceException
1081
-     * @throws InvalidArgumentException
1082
-     */
1083
-    public function wp_loaded()
1084
-    {
1085
-        if (
1086
-            EE_Registry::instance()->REQ instanceof EE_Request_Handler
1087
-            && EE_Registry::instance()->REQ->is_set('clear_session')
1088
-        ) {
1089
-            $this->clear_session(__CLASS__, __FUNCTION__);
1090
-        }
1091
-    }
1092
-
1093
-
1094
-
1095
-    /**
1096
-     * Used to reset the entire object (for tests).
1097
-     *
1098
-     * @since 4.3.0
1099
-     * @throws EE_Error
1100
-     * @throws InvalidDataTypeException
1101
-     * @throws InvalidInterfaceException
1102
-     * @throws InvalidArgumentException
1103
-     */
1104
-    public function reset_instance()
1105
-    {
1106
-        $this->clear_session();
1107
-        self::$_instance = null;
1108
-    }
1109
-
1110
-
1111
-
1112
-    public function configure_garbage_collection_filters()
1113
-    {
1114
-        // run old filter we had for controlling session cleanup
1115
-        $expired_session_transient_delete_query_limit = absint(
1116
-            apply_filters(
1117
-                'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1118
-                50
1119
-            )
1120
-        );
1121
-        // is there a value? or one that is different than the default 50 records?
1122
-        if ($expired_session_transient_delete_query_limit === 0) {
1123
-            // hook into TransientCacheStorage in case Session cleanup was turned off
1124
-            add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1125
-        } elseif ($expired_session_transient_delete_query_limit !== 50) {
1126
-            // or use that for the new transient cleanup query limit
1127
-            add_filter(
1128
-                'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1129
-                function () use ($expired_session_transient_delete_query_limit)
1130
-                {
1131
-                    return $expired_session_transient_delete_query_limit;
1132
-                }
1133
-            );
1134
-        }
1135
-    }
1136
-
1137
-
1138
-
1139
-    /**
1140
-     * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1141
-     * @param $data1
1142
-     * @return string
1143
-     */
1144
-    private function find_serialize_error($data1)
1145
-    {
1146
-        $error = '<pre>';
1147
-        $data2 = preg_replace_callback(
1148
-            '!s:(\d+):"(.*?)";!',
1149
-            function ($match)
1150
-            {
1151
-                return ($match[1] === strlen($match[2]))
1152
-                    ? $match[0]
1153
-                    : 's:'
1154
-                      . strlen($match[2])
1155
-                      . ':"'
1156
-                      . $match[2]
1157
-                      . '";';
1158
-            },
1159
-            $data1
1160
-        );
1161
-        $max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1162
-        $error .= $data1 . PHP_EOL;
1163
-        $error .= $data2 . PHP_EOL;
1164
-        for ($i = 0; $i < $max; $i++) {
1165
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1166
-                $error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1167
-                $error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1168
-                $error  .= "\t-> Line Number = $i" . PHP_EOL;
1169
-                $start  = ($i - 20);
1170
-                $start  = ($start < 0) ? 0 : $start;
1171
-                $length = 40;
1172
-                $point  = $max - $i;
1173
-                if ($point < 20) {
1174
-                    $rlength = 1;
1175
-                    $rpoint  = -$point;
1176
-                } else {
1177
-                    $rpoint  = $length - 20;
1178
-                    $rlength = 1;
1179
-                }
1180
-                $error .= "\t-> Section Data1  = ";
1181
-                $error .= substr_replace(
1182
-                    substr($data1, $start, $length),
1183
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1184
-                    $rpoint,
1185
-                    $rlength
1186
-                );
1187
-                $error .= PHP_EOL;
1188
-                $error .= "\t-> Section Data2  = ";
1189
-                $error .= substr_replace(
1190
-                    substr($data2, $start, $length),
1191
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1192
-                    $rpoint,
1193
-                    $rlength
1194
-                );
1195
-                $error .= PHP_EOL;
1196
-            }
1197
-        }
1198
-        $error .= '</pre>';
1199
-        return $error;
1200
-    }
1201
-
1202
-
1203
-    /**
1204
-     * Saves an  array of settings used for configuring aspects of session behaviour
1205
-     *
1206
-     * @param array $updated_settings
1207
-     */
1208
-    private function updateSessionSettings(array $updated_settings = array())
1209
-    {
1210
-        // add existing settings, but only if not included in incoming $updated_settings array
1211
-        $updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1212
-        update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1213
-    }
1214
-
1215
-
1216
-    /**
1217
-     * garbage_collection
1218
-     */
1219
-    public function garbageCollection()
1220
-    {
1221
-        // only perform during regular requests if last garbage collection was over an hour ago
1222
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1223
-            $this->_last_gc = time();
1224
-            $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1225
-            /** @type WPDB $wpdb */
1226
-            global $wpdb;
1227
-            // filter the query limit. Set to 0 to turn off garbage collection
1228
-            $expired_session_transient_delete_query_limit = absint(
1229
-                apply_filters(
1230
-                    'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1231
-                    50
1232
-                )
1233
-            );
1234
-            // non-zero LIMIT means take out the trash
1235
-            if ($expired_session_transient_delete_query_limit) {
1236
-                $session_key    = str_replace('_', '\_', EE_Session::session_id_prefix);
1237
-                $hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1238
-                // since transient expiration timestamps are set in the future, we can compare against NOW
1239
-                // but we only want to pick up any trash that's been around for more than a day
1240
-                $expiration = time() - DAY_IN_SECONDS;
1241
-                $SQL        = "
362
+	/**
363
+	 * reset_cart
364
+	 */
365
+	public function reset_cart()
366
+	{
367
+		do_action('AHEE__EE_Session__reset_cart__before_reset', $this);
368
+		$this->_session_data['cart'] = null;
369
+	}
370
+
371
+
372
+
373
+	/**
374
+	 * @return \EE_Cart
375
+	 */
376
+	public function cart()
377
+	{
378
+		return isset($this->_session_data['cart']) && $this->_session_data['cart'] instanceof EE_Cart
379
+			? $this->_session_data['cart']
380
+			: null;
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * @param \EE_Checkout $checkout
387
+	 * @return bool
388
+	 */
389
+	public function set_checkout(EE_Checkout $checkout)
390
+	{
391
+		$this->_session_data['checkout'] = $checkout;
392
+		return true;
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 * reset_checkout
399
+	 */
400
+	public function reset_checkout()
401
+	{
402
+		do_action('AHEE__EE_Session__reset_checkout__before_reset', $this);
403
+		$this->_session_data['checkout'] = null;
404
+	}
405
+
406
+
407
+
408
+	/**
409
+	 * @return \EE_Checkout
410
+	 */
411
+	public function checkout()
412
+	{
413
+		return isset($this->_session_data['checkout']) && $this->_session_data['checkout'] instanceof EE_Checkout
414
+			? $this->_session_data['checkout']
415
+			: null;
416
+	}
417
+
418
+
419
+
420
+	/**
421
+	 * @param \EE_Transaction $transaction
422
+	 * @return bool
423
+	 * @throws EE_Error
424
+	 */
425
+	public function set_transaction(EE_Transaction $transaction)
426
+	{
427
+		// first remove the session from the transaction before we save the transaction in the session
428
+		$transaction->set_txn_session_data(null);
429
+		$this->_session_data['transaction'] = $transaction;
430
+		return true;
431
+	}
432
+
433
+
434
+
435
+	/**
436
+	 * reset_transaction
437
+	 */
438
+	public function reset_transaction()
439
+	{
440
+		do_action('AHEE__EE_Session__reset_transaction__before_reset', $this);
441
+		$this->_session_data['transaction'] = null;
442
+	}
443
+
444
+
445
+
446
+	/**
447
+	 * @return \EE_Transaction
448
+	 */
449
+	public function transaction()
450
+	{
451
+		return isset($this->_session_data['transaction'])
452
+			   && $this->_session_data['transaction'] instanceof EE_Transaction
453
+			? $this->_session_data['transaction']
454
+			: null;
455
+	}
456
+
457
+
458
+
459
+	/**
460
+	 * retrieve session data
461
+	 *
462
+	 * @access    public
463
+	 * @param null $key
464
+	 * @param bool $reset_cache
465
+	 * @return    array
466
+	 */
467
+	public function get_session_data($key = null, $reset_cache = false)
468
+	{
469
+		if ($reset_cache) {
470
+			$this->reset_cart();
471
+			$this->reset_checkout();
472
+			$this->reset_transaction();
473
+		}
474
+		if (! empty($key)) {
475
+			return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
476
+		}
477
+		return $this->_session_data;
478
+	}
479
+
480
+
481
+
482
+	/**
483
+	 * set session data
484
+	 *
485
+	 * @access    public
486
+	 * @param    array $data
487
+	 * @return    TRUE on success, FALSE on fail
488
+	 */
489
+	public function set_session_data($data)
490
+	{
491
+
492
+		// nothing ??? bad data ??? go home!
493
+		if (empty($data) || ! is_array($data)) {
494
+			EE_Error::add_error(__('No session data or invalid session data was provided.', 'event_espresso'), __FILE__,
495
+				__FUNCTION__, __LINE__);
496
+			return false;
497
+		}
498
+		foreach ($data as $key => $value) {
499
+			if (isset($this->_default_session_vars[ $key ])) {
500
+				EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
501
+					'event_espresso'), $key), __FILE__, __FUNCTION__, __LINE__);
502
+				return false;
503
+			}
504
+			$this->_session_data[ $key ] = $value;
505
+		}
506
+		return true;
507
+	}
508
+
509
+
510
+
511
+	/**
512
+	 * @initiate session
513
+	 * @access   private
514
+	 * @return TRUE on success, FALSE on fail
515
+	 * @throws EE_Error
516
+	 * @throws InvalidArgumentException
517
+	 * @throws InvalidDataTypeException
518
+	 * @throws InvalidInterfaceException
519
+	 * @throws InvalidSessionDataException
520
+	 */
521
+	private function _espresso_session()
522
+	{
523
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
524
+		// check that session has started
525
+		if (session_id() === '') {
526
+			//starts a new session if one doesn't already exist, or re-initiates an existing one
527
+			session_start();
528
+		}
529
+		// get our modified session ID
530
+		$this->_sid = $this->_generate_session_id();
531
+		// and the visitors IP
532
+		$this->_ip_address = $this->_visitor_ip();
533
+		// set the "user agent"
534
+		$this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr($_SERVER['HTTP_USER_AGENT']) : false;
535
+		// now let's retrieve what's in the db
536
+		$session_data = $this->_retrieve_session_data();
537
+		if (! empty($session_data)) {
538
+			// get the current time in UTC
539
+			$this->_time = $this->_time !== null ? $this->_time : time();
540
+			// and reset the session expiration
541
+			$this->_expiration = isset($session_data['expiration'])
542
+				? $session_data['expiration']
543
+				: $this->_time + $this->_lifespan;
544
+		} else {
545
+			// set initial site access time and the session expiration
546
+			$this->_set_init_access_and_expiration();
547
+			// set referer
548
+			$this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
549
+				? esc_attr($_SERVER['HTTP_REFERER'])
550
+				: '';
551
+			// no previous session = go back and create one (on top of the data above)
552
+			return false;
553
+		}
554
+		// now the user agent
555
+		if ($session_data['user_agent'] !== $this->_user_agent) {
556
+			return false;
557
+		}
558
+		// wait a minute... how old are you?
559
+		if ($this->_time > $this->_expiration) {
560
+			// yer too old fer me!
561
+			$this->_expired = true;
562
+			// wipe out everything that isn't a default session datum
563
+			$this->clear_session(__CLASS__, __FUNCTION__);
564
+		}
565
+		// make event espresso session data available to plugin
566
+		$this->_session_data = array_merge($this->_session_data, $session_data);
567
+		return true;
568
+	}
569
+
570
+
571
+
572
+	/**
573
+	 * _get_session_data
574
+	 * Retrieves the session data, and attempts to correct any encoding issues that can occur due to improperly setup
575
+	 * databases
576
+	 *
577
+	 * @return array
578
+	 * @throws EE_Error
579
+	 * @throws InvalidArgumentException
580
+	 * @throws InvalidSessionDataException
581
+	 * @throws InvalidDataTypeException
582
+	 * @throws InvalidInterfaceException
583
+	 */
584
+	protected function _retrieve_session_data()
585
+	{
586
+		$ssn_key = EE_Session::session_id_prefix . $this->_sid;
587
+		try {
588
+			// we're using WP's Transient API to store session data using the PHP session ID as the option name
589
+			$session_data = $this->cache_storage->get($ssn_key, false);
590
+			if (empty($session_data)) {
591
+				return array();
592
+			}
593
+			if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
594
+				$hash_check = $this->cache_storage->get(
595
+					EE_Session::hash_check_prefix . $this->_sid,
596
+					false
597
+				);
598
+				if ($hash_check && $hash_check !== md5($session_data)) {
599
+					EE_Error::add_error(
600
+						sprintf(
601
+							__(
602
+								'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
603
+								'event_espresso'
604
+							),
605
+							EE_Session::session_id_prefix . $this->_sid
606
+						),
607
+						__FILE__, __FUNCTION__, __LINE__
608
+					);
609
+				}
610
+			}
611
+		} catch (Exception $e) {
612
+			// let's just eat that error for now and attempt to correct any corrupted data
613
+			global $wpdb;
614
+			$row          = $wpdb->get_row(
615
+				$wpdb->prepare(
616
+					"SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
617
+					'_transient_' . $ssn_key
618
+				)
619
+			);
620
+			$session_data = is_object($row) ? $row->option_value : null;
621
+			if ($session_data) {
622
+				$session_data = preg_replace_callback(
623
+					'!s:(d+):"(.*?)";!',
624
+					function ($match)
625
+					{
626
+						return $match[1] === strlen($match[2])
627
+							? $match[0]
628
+							: 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
629
+					},
630
+					$session_data
631
+				);
632
+			}
633
+			$session_data = maybe_unserialize($session_data);
634
+		}
635
+		// in case the data is encoded... try to decode it
636
+		$session_data = $this->encryption instanceof EE_Encryption
637
+			? $this->encryption->base64_string_decode($session_data)
638
+			: $session_data;
639
+		if (! is_array($session_data)) {
640
+			try {
641
+				$session_data = maybe_unserialize($session_data);
642
+			} catch (Exception $e) {
643
+				$msg = esc_html__(
644
+					'An error occurred while attempting to unserialize the session data.',
645
+					'event_espresso'
646
+				);
647
+				$msg .= WP_DEBUG
648
+					? '<br><pre>'
649
+					  . print_r($session_data, true)
650
+					  . '</pre><br>'
651
+					  . $this->find_serialize_error($session_data)
652
+					: '';
653
+				$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
654
+				throw new InvalidSessionDataException($msg, 0, $e);
655
+			}
656
+		}
657
+		// just a check to make sure the session array is indeed an array
658
+		if (! is_array($session_data)) {
659
+			// no?!?! then something is wrong
660
+			$msg = esc_html__(
661
+				'The session data is missing, invalid, or corrupted.',
662
+				'event_espresso'
663
+			);
664
+			$msg .= WP_DEBUG
665
+				? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
666
+				: '';
667
+			$this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
668
+			throw new InvalidSessionDataException($msg);
669
+		}
670
+		if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
671
+			$session_data['transaction'] = EEM_Transaction::instance()->get_one_by_ID(
672
+				$session_data['transaction']
673
+			);
674
+		}
675
+		return $session_data;
676
+	}
677
+
678
+
679
+
680
+	/**
681
+	 * _generate_session_id
682
+	 * Retrieves the PHP session id either directly from the PHP session,
683
+	 * or from the $_REQUEST array if it was passed in from an AJAX request.
684
+	 * The session id is then salted and hashed (mmm sounds tasty)
685
+	 * so that it can be safely used as a $_REQUEST param
686
+	 *
687
+	 * @return string
688
+	 */
689
+	protected function _generate_session_id()
690
+	{
691
+		// check if the SID was passed explicitly, otherwise get from session, then add salt and hash it to reduce length
692
+		if (isset($_REQUEST['EESID'])) {
693
+			$session_id = sanitize_text_field($_REQUEST['EESID']);
694
+		} else {
695
+			$session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
696
+		}
697
+		return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
698
+	}
699
+
700
+
701
+
702
+	/**
703
+	 * _get_sid_salt
704
+	 *
705
+	 * @return string
706
+	 */
707
+	protected function _get_sid_salt()
708
+	{
709
+		// was session id salt already saved to db ?
710
+		if (empty($this->_sid_salt)) {
711
+			// no?  then maybe use WP defined constant
712
+			if (defined('AUTH_SALT')) {
713
+				$this->_sid_salt = AUTH_SALT;
714
+			}
715
+			// if salt doesn't exist or is too short
716
+			if (strlen($this->_sid_salt) < 32) {
717
+				// create a new one
718
+				$this->_sid_salt = wp_generate_password(64);
719
+			}
720
+			// and save it as a permanent session setting
721
+			$this->updateSessionSettings(array('sid_salt' => $this->_sid_salt));
722
+		}
723
+		return $this->_sid_salt;
724
+	}
725
+
726
+
727
+
728
+	/**
729
+	 * _set_init_access_and_expiration
730
+	 *
731
+	 * @return void
732
+	 */
733
+	protected function _set_init_access_and_expiration()
734
+	{
735
+		$this->_time       = time();
736
+		$this->_expiration = $this->_time + $this->_lifespan;
737
+		// set initial site access time
738
+		$this->_session_data['init_access'] = $this->_time;
739
+		// and the session expiration
740
+		$this->_session_data['expiration'] = $this->_expiration;
741
+	}
742
+
743
+
744
+
745
+	/**
746
+	 * @update session data  prior to saving to the db
747
+	 * @access public
748
+	 * @param bool $new_session
749
+	 * @return TRUE on success, FALSE on fail
750
+	 * @throws EE_Error
751
+	 * @throws InvalidArgumentException
752
+	 * @throws InvalidDataTypeException
753
+	 * @throws InvalidInterfaceException
754
+	 */
755
+	public function update($new_session = false)
756
+	{
757
+		$this->_session_data = $this->_session_data !== null
758
+							   && is_array($this->_session_data)
759
+							   && isset($this->_session_data['id'])
760
+			? $this->_session_data
761
+			: array();
762
+		if (empty($this->_session_data)) {
763
+			$this->_set_defaults();
764
+		}
765
+		$session_data = array();
766
+		foreach ($this->_session_data as $key => $value) {
767
+
768
+			switch ($key) {
769
+
770
+				case 'id' :
771
+					// session ID
772
+					$session_data['id'] = $this->_sid;
773
+					break;
774
+				case 'ip_address' :
775
+					// visitor ip address
776
+					$session_data['ip_address'] = $this->_visitor_ip();
777
+					break;
778
+				case 'user_agent' :
779
+					// visitor user_agent
780
+					$session_data['user_agent'] = $this->_user_agent;
781
+					break;
782
+				case 'init_access' :
783
+					$session_data['init_access'] = absint($value);
784
+					break;
785
+				case 'last_access' :
786
+					// current access time
787
+					$session_data['last_access'] = $this->_time;
788
+					break;
789
+				case 'expiration' :
790
+					// when the session expires
791
+					$session_data['expiration'] = ! empty($this->_expiration)
792
+						? $this->_expiration
793
+						: $session_data['init_access'] + $this->_lifespan;
794
+					break;
795
+				case 'user_id' :
796
+					// current user if logged in
797
+					$session_data['user_id'] = $this->_wp_user_id();
798
+					break;
799
+				case 'pages_visited' :
800
+					$page_visit = $this->_get_page_visit();
801
+					if ($page_visit) {
802
+						// set pages visited where the first will be the http referrer
803
+						$this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
804
+						// we'll only save the last 10 page visits.
805
+						$session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
806
+					}
807
+					break;
808
+				default :
809
+					// carry any other data over
810
+					$session_data[ $key ] = $this->_session_data[ $key ];
811
+			}
812
+		}
813
+		$this->_session_data = $session_data;
814
+		// creating a new session does not require saving to the db just yet
815
+		if (! $new_session) {
816
+			// ready? let's save
817
+			if ($this->_save_session_to_db()) {
818
+				return true;
819
+			}
820
+			return false;
821
+		}
822
+		// meh, why not?
823
+		return true;
824
+	}
825
+
826
+
827
+
828
+	/**
829
+	 * @create session data array
830
+	 * @access public
831
+	 * @return bool
832
+	 * @throws EE_Error
833
+	 * @throws InvalidArgumentException
834
+	 * @throws InvalidDataTypeException
835
+	 * @throws InvalidInterfaceException
836
+	 */
837
+	private function _create_espresso_session()
838
+	{
839
+		do_action('AHEE_log', __CLASS__, __FUNCTION__, '');
840
+		// use the update function for now with $new_session arg set to TRUE
841
+		return $this->update(true) ? true : false;
842
+	}
843
+
844
+
845
+
846
+	/**
847
+	 * _save_session_to_db
848
+	 *
849
+	 * @access public
850
+	 * @return string
851
+	 * @throws EE_Error
852
+	 * @throws InvalidArgumentException
853
+	 * @throws InvalidDataTypeException
854
+	 * @throws InvalidInterfaceException
855
+	 */
856
+	private function _save_session_to_db()
857
+	{
858
+		if (
859
+			// if the current request is NOT one of the following
860
+		! (
861
+			// an an AJAX request from the frontend
862
+			EE_Registry::instance()->REQ->front_ajax
863
+			|| (
864
+				// OR an admin request that is NOT AJAX
865
+				! (defined('DOING_AJAX') && DOING_AJAX)
866
+				&& is_admin()
867
+			)
868
+			|| (
869
+				// OR an espresso page
870
+				EE_Registry::instance()->REQ instanceof EE_Request_Handler
871
+				&& EE_Registry::instance()->REQ->is_espresso_page()
872
+			)
873
+		)
874
+		) {
875
+			return false;
876
+		}
877
+		$transaction = $this->transaction();
878
+		if ($transaction instanceof EE_Transaction) {
879
+			if (! $transaction->ID()) {
880
+				$transaction->save();
881
+			}
882
+			$this->_session_data['transaction'] = $transaction->ID();
883
+		}
884
+		// then serialize all of our session data
885
+		$session_data = serialize($this->_session_data);
886
+		// do we need to also encode it to avoid corrupted data when saved to the db?
887
+		$session_data = $this->_use_encryption
888
+			? $this->encryption->base64_string_encode($session_data)
889
+			: $session_data;
890
+		// maybe save hash check
891
+		if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
892
+			$this->cache_storage->add(
893
+				EE_Session::hash_check_prefix . $this->_sid,
894
+				md5($session_data),
895
+				$this->_lifespan
896
+			);
897
+		}
898
+		// we're using the Transient API for storing session data,
899
+		return $this->cache_storage->add(
900
+			EE_Session::session_id_prefix . $this->_sid,
901
+			$session_data,
902
+			$this->_lifespan
903
+		);
904
+	}
905
+
906
+
907
+
908
+	/**
909
+	 * _visitor_ip
910
+	 *    attempt to get IP address of current visitor from server
911
+	 * plz see: http://stackoverflow.com/a/2031935/1475279
912
+	 *
913
+	 * @access public
914
+	 * @return string
915
+	 */
916
+	private function _visitor_ip()
917
+	{
918
+		$visitor_ip  = '0.0.0.0';
919
+		$server_keys = array(
920
+			'HTTP_CLIENT_IP',
921
+			'HTTP_X_FORWARDED_FOR',
922
+			'HTTP_X_FORWARDED',
923
+			'HTTP_X_CLUSTER_CLIENT_IP',
924
+			'HTTP_FORWARDED_FOR',
925
+			'HTTP_FORWARDED',
926
+			'REMOTE_ADDR',
927
+		);
928
+		foreach ($server_keys as $key) {
929
+			if (isset($_SERVER[ $key ])) {
930
+				foreach (array_map('trim', explode(',', $_SERVER[ $key ])) as $ip) {
931
+					if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
932
+						$visitor_ip = $ip;
933
+					}
934
+				}
935
+			}
936
+		}
937
+		return $visitor_ip;
938
+	}
939
+
940
+
941
+
942
+	/**
943
+	 * @get    the full page request the visitor is accessing
944
+	 * @access public
945
+	 * @return string
946
+	 */
947
+	public function _get_page_visit()
948
+	{
949
+		$page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
950
+		// check for request url
951
+		if (isset($_SERVER['REQUEST_URI'])) {
952
+			$http_host   = '';
953
+			$page_id     = '?';
954
+			$e_reg       = '';
955
+			$request_uri = esc_url($_SERVER['REQUEST_URI']);
956
+			$ru_bits     = explode('?', $request_uri);
957
+			$request_uri = $ru_bits[0];
958
+			// check for and grab host as well
959
+			if (isset($_SERVER['HTTP_HOST'])) {
960
+				$http_host = esc_url($_SERVER['HTTP_HOST']);
961
+			}
962
+			// check for page_id in SERVER REQUEST
963
+			if (isset($_REQUEST['page_id'])) {
964
+				// rebuild $e_reg without any of the extra parameters
965
+				$page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
966
+			}
967
+			// check for $e_reg in SERVER REQUEST
968
+			if (isset($_REQUEST['ee'])) {
969
+				// rebuild $e_reg without any of the extra parameters
970
+				$e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
971
+			}
972
+			$page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
973
+		}
974
+		return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
975
+	}
976
+
977
+
978
+
979
+	/**
980
+	 * @the    current wp user id
981
+	 * @access public
982
+	 * @return int
983
+	 */
984
+	public function _wp_user_id()
985
+	{
986
+		// if I need to explain the following lines of code, then you shouldn't be looking at this!
987
+		$this->_wp_user_id = get_current_user_id();
988
+		return $this->_wp_user_id;
989
+	}
990
+
991
+
992
+
993
+	/**
994
+	 * Clear EE_Session data
995
+	 *
996
+	 * @access public
997
+	 * @param string $class
998
+	 * @param string $function
999
+	 * @return void
1000
+	 * @throws EE_Error
1001
+	 * @throws InvalidArgumentException
1002
+	 * @throws InvalidDataTypeException
1003
+	 * @throws InvalidInterfaceException
1004
+	 */
1005
+	public function clear_session($class = '', $function = '')
1006
+	{
1007
+		//echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
1008
+		do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1009
+		$this->reset_cart();
1010
+		$this->reset_checkout();
1011
+		$this->reset_transaction();
1012
+		// wipe out everything that isn't a default session datum
1013
+		$this->reset_data(array_keys($this->_session_data));
1014
+		// reset initial site access time and the session expiration
1015
+		$this->_set_init_access_and_expiration();
1016
+		$this->_save_session_to_db();
1017
+	}
1018
+
1019
+
1020
+
1021
+	/**
1022
+	 * @resets all non-default session vars
1023
+	 * @access public
1024
+	 * @param array|mixed $data_to_reset
1025
+	 * @param bool        $show_all_notices
1026
+	 * @return TRUE on success, FALSE on fail
1027
+	 */
1028
+	public function reset_data($data_to_reset = array(), $show_all_notices = false)
1029
+	{
1030
+		// if $data_to_reset is not in an array, then put it in one
1031
+		if (! is_array($data_to_reset)) {
1032
+			$data_to_reset = array($data_to_reset);
1033
+		}
1034
+		// nothing ??? go home!
1035
+		if (empty($data_to_reset)) {
1036
+			EE_Error::add_error(__('No session data could be reset, because no session var name was provided.',
1037
+				'event_espresso'), __FILE__, __FUNCTION__, __LINE__);
1038
+			return false;
1039
+		}
1040
+		$return_value = true;
1041
+		// since $data_to_reset is an array, cycle through the values
1042
+		foreach ($data_to_reset as $reset) {
1043
+
1044
+			// first check to make sure it is a valid session var
1045
+			if (isset($this->_session_data[ $reset ])) {
1046
+				// then check to make sure it is not a default var
1047
+				if (! array_key_exists($reset, $this->_default_session_vars)) {
1048
+					// remove session var
1049
+					unset($this->_session_data[ $reset ]);
1050
+					if ($show_all_notices) {
1051
+						EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1052
+							$reset), __FILE__, __FUNCTION__, __LINE__);
1053
+					}
1054
+				} else {
1055
+					// yeeeeeeeeerrrrrrrrrrr OUT !!!!
1056
+					if ($show_all_notices) {
1057
+						EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
1058
+							'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1059
+					}
1060
+					$return_value = false;
1061
+				}
1062
+			} elseif ($show_all_notices) {
1063
+				// oops! that session var does not exist!
1064
+				EE_Error::add_error(sprintf(__('The session item provided, %s, is invalid or does not exist.',
1065
+					'event_espresso'), $reset), __FILE__, __FUNCTION__, __LINE__);
1066
+				$return_value = false;
1067
+			}
1068
+		} // end of foreach
1069
+		return $return_value;
1070
+	}
1071
+
1072
+
1073
+
1074
+	/**
1075
+	 *   wp_loaded
1076
+	 *
1077
+	 * @access public
1078
+	 * @throws EE_Error
1079
+	 * @throws InvalidDataTypeException
1080
+	 * @throws InvalidInterfaceException
1081
+	 * @throws InvalidArgumentException
1082
+	 */
1083
+	public function wp_loaded()
1084
+	{
1085
+		if (
1086
+			EE_Registry::instance()->REQ instanceof EE_Request_Handler
1087
+			&& EE_Registry::instance()->REQ->is_set('clear_session')
1088
+		) {
1089
+			$this->clear_session(__CLASS__, __FUNCTION__);
1090
+		}
1091
+	}
1092
+
1093
+
1094
+
1095
+	/**
1096
+	 * Used to reset the entire object (for tests).
1097
+	 *
1098
+	 * @since 4.3.0
1099
+	 * @throws EE_Error
1100
+	 * @throws InvalidDataTypeException
1101
+	 * @throws InvalidInterfaceException
1102
+	 * @throws InvalidArgumentException
1103
+	 */
1104
+	public function reset_instance()
1105
+	{
1106
+		$this->clear_session();
1107
+		self::$_instance = null;
1108
+	}
1109
+
1110
+
1111
+
1112
+	public function configure_garbage_collection_filters()
1113
+	{
1114
+		// run old filter we had for controlling session cleanup
1115
+		$expired_session_transient_delete_query_limit = absint(
1116
+			apply_filters(
1117
+				'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1118
+				50
1119
+			)
1120
+		);
1121
+		// is there a value? or one that is different than the default 50 records?
1122
+		if ($expired_session_transient_delete_query_limit === 0) {
1123
+			// hook into TransientCacheStorage in case Session cleanup was turned off
1124
+			add_filter('FHEE__TransientCacheStorage__transient_cleanup_schedule', '__return_zero');
1125
+		} elseif ($expired_session_transient_delete_query_limit !== 50) {
1126
+			// or use that for the new transient cleanup query limit
1127
+			add_filter(
1128
+				'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1129
+				function () use ($expired_session_transient_delete_query_limit)
1130
+				{
1131
+					return $expired_session_transient_delete_query_limit;
1132
+				}
1133
+			);
1134
+		}
1135
+	}
1136
+
1137
+
1138
+
1139
+	/**
1140
+	 * @see http://stackoverflow.com/questions/10152904/unserialize-function-unserialize-error-at-offset/21389439#10152996
1141
+	 * @param $data1
1142
+	 * @return string
1143
+	 */
1144
+	private function find_serialize_error($data1)
1145
+	{
1146
+		$error = '<pre>';
1147
+		$data2 = preg_replace_callback(
1148
+			'!s:(\d+):"(.*?)";!',
1149
+			function ($match)
1150
+			{
1151
+				return ($match[1] === strlen($match[2]))
1152
+					? $match[0]
1153
+					: 's:'
1154
+					  . strlen($match[2])
1155
+					  . ':"'
1156
+					  . $match[2]
1157
+					  . '";';
1158
+			},
1159
+			$data1
1160
+		);
1161
+		$max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1162
+		$error .= $data1 . PHP_EOL;
1163
+		$error .= $data2 . PHP_EOL;
1164
+		for ($i = 0; $i < $max; $i++) {
1165
+			if (@$data1[ $i ] !== @$data2[ $i ]) {
1166
+				$error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1167
+				$error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1168
+				$error  .= "\t-> Line Number = $i" . PHP_EOL;
1169
+				$start  = ($i - 20);
1170
+				$start  = ($start < 0) ? 0 : $start;
1171
+				$length = 40;
1172
+				$point  = $max - $i;
1173
+				if ($point < 20) {
1174
+					$rlength = 1;
1175
+					$rpoint  = -$point;
1176
+				} else {
1177
+					$rpoint  = $length - 20;
1178
+					$rlength = 1;
1179
+				}
1180
+				$error .= "\t-> Section Data1  = ";
1181
+				$error .= substr_replace(
1182
+					substr($data1, $start, $length),
1183
+					"<b style=\"color:green\">{$data1[ $i ]}</b>",
1184
+					$rpoint,
1185
+					$rlength
1186
+				);
1187
+				$error .= PHP_EOL;
1188
+				$error .= "\t-> Section Data2  = ";
1189
+				$error .= substr_replace(
1190
+					substr($data2, $start, $length),
1191
+					"<b style=\"color:red\">{$data2[ $i ]}</b>",
1192
+					$rpoint,
1193
+					$rlength
1194
+				);
1195
+				$error .= PHP_EOL;
1196
+			}
1197
+		}
1198
+		$error .= '</pre>';
1199
+		return $error;
1200
+	}
1201
+
1202
+
1203
+	/**
1204
+	 * Saves an  array of settings used for configuring aspects of session behaviour
1205
+	 *
1206
+	 * @param array $updated_settings
1207
+	 */
1208
+	private function updateSessionSettings(array $updated_settings = array())
1209
+	{
1210
+		// add existing settings, but only if not included in incoming $updated_settings array
1211
+		$updated_settings += get_option(EE_Session::OPTION_NAME_SETTINGS, array());
1212
+		update_option(EE_Session::OPTION_NAME_SETTINGS, $updated_settings);
1213
+	}
1214
+
1215
+
1216
+	/**
1217
+	 * garbage_collection
1218
+	 */
1219
+	public function garbageCollection()
1220
+	{
1221
+		// only perform during regular requests if last garbage collection was over an hour ago
1222
+		if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1223
+			$this->_last_gc = time();
1224
+			$this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1225
+			/** @type WPDB $wpdb */
1226
+			global $wpdb;
1227
+			// filter the query limit. Set to 0 to turn off garbage collection
1228
+			$expired_session_transient_delete_query_limit = absint(
1229
+				apply_filters(
1230
+					'FHEE__EE_Session__garbage_collection___expired_session_transient_delete_query_limit',
1231
+					50
1232
+				)
1233
+			);
1234
+			// non-zero LIMIT means take out the trash
1235
+			if ($expired_session_transient_delete_query_limit) {
1236
+				$session_key    = str_replace('_', '\_', EE_Session::session_id_prefix);
1237
+				$hash_check_key = str_replace('_', '\_', EE_Session::hash_check_prefix);
1238
+				// since transient expiration timestamps are set in the future, we can compare against NOW
1239
+				// but we only want to pick up any trash that's been around for more than a day
1240
+				$expiration = time() - DAY_IN_SECONDS;
1241
+				$SQL        = "
1242 1242
                     SELECT option_name
1243 1243
                     FROM {$wpdb->options}
1244 1244
                     WHERE
@@ -1247,19 +1247,19 @@  discard block
 block discarded – undo
1247 1247
                     AND option_value < {$expiration}
1248 1248
                     LIMIT {$expired_session_transient_delete_query_limit}
1249 1249
                 ";
1250
-                // produces something like:
1251
-                // SELECT option_name FROM wp_options
1252
-                // WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1253
-                // OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1254
-                // AND option_value < 1508368198 LIMIT 50
1255
-                $expired_sessions = $wpdb->get_col($SQL);
1256
-                // valid results?
1257
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1258
-                    $this->cache_storage->deleteMany($expired_sessions, true);
1259
-                }
1260
-            }
1261
-        }
1262
-    }
1250
+				// produces something like:
1251
+				// SELECT option_name FROM wp_options
1252
+				// WHERE ( option_name LIKE '\_transient\_timeout\_ee\_ssn\_%'
1253
+				// OR option_name LIKE '\_transient\_timeout\_ee\_shc\_%' )
1254
+				// AND option_value < 1508368198 LIMIT 50
1255
+				$expired_sessions = $wpdb->get_col($SQL);
1256
+				// valid results?
1257
+				if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1258
+					$this->cache_storage->deleteMany($expired_sessions, true);
1259
+				}
1260
+			}
1261
+		}
1262
+	}
1263 1263
 
1264 1264
 
1265 1265
 
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
         // check if class object is instantiated
165 165
         // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via:
166 166
         // add_filter( 'FHEE_load_EE_Session', '__return_false' );
167
-        if (! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
167
+        if ( ! self::$_instance instanceof EE_Session && apply_filters('FHEE_load_EE_Session', true)) {
168 168
             self::$_instance = new self($cache_storage, $encryption);
169 169
         }
170 170
         return self::$_instance;
@@ -185,11 +185,11 @@  discard block
 block discarded – undo
185 185
     {
186 186
 
187 187
         // session loading is turned ON by default, but prior to the init hook, can be turned back OFF via: add_filter( 'FHEE_load_EE_Session', '__return_false' );
188
-        if (! apply_filters('FHEE_load_EE_Session', true)) {
188
+        if ( ! apply_filters('FHEE_load_EE_Session', true)) {
189 189
             return;
190 190
         }
191 191
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
192
-        if (! defined('ESPRESSO_SESSION')) {
192
+        if ( ! defined('ESPRESSO_SESSION')) {
193 193
             define('ESPRESSO_SESSION', true);
194 194
         }
195 195
         // default session lifespan in seconds
@@ -205,11 +205,11 @@  discard block
 block discarded – undo
205 205
          */
206 206
         // retrieve session options from db
207 207
         $session_settings = (array) get_option(EE_Session::OPTION_NAME_SETTINGS, array());
208
-        if (! empty($session_settings)) {
208
+        if ( ! empty($session_settings)) {
209 209
             // cycle though existing session options
210 210
             foreach ($session_settings as $var_name => $session_setting) {
211 211
                 // set values for class properties
212
-                $var_name          = '_' . $var_name;
212
+                $var_name          = '_'.$var_name;
213 213
                 $this->{$var_name} = $session_setting;
214 214
             }
215 215
         }
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
     public function open_session()
248 248
     {
249 249
         // check for existing session and retrieve it from db
250
-        if (! $this->_espresso_session()) {
250
+        if ( ! $this->_espresso_session()) {
251 251
             // or just start a new one
252 252
             $this->_create_espresso_session();
253 253
         }
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
      */
300 300
     public function extend_expiration($time = 0)
301 301
     {
302
-        $time              = $time ? $time : $this->extension();
302
+        $time = $time ? $time : $this->extension();
303 303
         $this->_expiration += absint($time);
304 304
     }
305 305
 
@@ -326,9 +326,9 @@  discard block
 block discarded – undo
326 326
         // set some defaults
327 327
         foreach ($this->_default_session_vars as $key => $default_var) {
328 328
             if (is_array($default_var)) {
329
-                $this->_session_data[ $key ] = array();
329
+                $this->_session_data[$key] = array();
330 330
             } else {
331
-                $this->_session_data[ $key ] = '';
331
+                $this->_session_data[$key] = '';
332 332
             }
333 333
         }
334 334
     }
@@ -471,8 +471,8 @@  discard block
 block discarded – undo
471 471
             $this->reset_checkout();
472 472
             $this->reset_transaction();
473 473
         }
474
-        if (! empty($key)) {
475
-            return isset($this->_session_data[ $key ]) ? $this->_session_data[ $key ] : null;
474
+        if ( ! empty($key)) {
475
+            return isset($this->_session_data[$key]) ? $this->_session_data[$key] : null;
476 476
         }
477 477
         return $this->_session_data;
478 478
     }
@@ -496,12 +496,12 @@  discard block
 block discarded – undo
496 496
             return false;
497 497
         }
498 498
         foreach ($data as $key => $value) {
499
-            if (isset($this->_default_session_vars[ $key ])) {
499
+            if (isset($this->_default_session_vars[$key])) {
500 500
                 EE_Error::add_error(sprintf(__('Sorry! %s is a default session datum and can not be reset.',
501 501
                     'event_espresso'), $key), __FILE__, __FUNCTION__, __LINE__);
502 502
                 return false;
503 503
             }
504
-            $this->_session_data[ $key ] = $value;
504
+            $this->_session_data[$key] = $value;
505 505
         }
506 506
         return true;
507 507
     }
@@ -534,7 +534,7 @@  discard block
 block discarded – undo
534 534
         $this->_user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? esc_attr($_SERVER['HTTP_USER_AGENT']) : false;
535 535
         // now let's retrieve what's in the db
536 536
         $session_data = $this->_retrieve_session_data();
537
-        if (! empty($session_data)) {
537
+        if ( ! empty($session_data)) {
538 538
             // get the current time in UTC
539 539
             $this->_time = $this->_time !== null ? $this->_time : time();
540 540
             // and reset the session expiration
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
             // set initial site access time and the session expiration
546 546
             $this->_set_init_access_and_expiration();
547 547
             // set referer
548
-            $this->_session_data['pages_visited'][ $this->_session_data['init_access'] ] = isset($_SERVER['HTTP_REFERER'])
548
+            $this->_session_data['pages_visited'][$this->_session_data['init_access']] = isset($_SERVER['HTTP_REFERER'])
549 549
                 ? esc_attr($_SERVER['HTTP_REFERER'])
550 550
                 : '';
551 551
             // no previous session = go back and create one (on top of the data above)
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
      */
584 584
     protected function _retrieve_session_data()
585 585
     {
586
-        $ssn_key = EE_Session::session_id_prefix . $this->_sid;
586
+        $ssn_key = EE_Session::session_id_prefix.$this->_sid;
587 587
         try {
588 588
             // we're using WP's Transient API to store session data using the PHP session ID as the option name
589 589
             $session_data = $this->cache_storage->get($ssn_key, false);
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
             }
593 593
             if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
594 594
                 $hash_check = $this->cache_storage->get(
595
-                    EE_Session::hash_check_prefix . $this->_sid,
595
+                    EE_Session::hash_check_prefix.$this->_sid,
596 596
                     false
597 597
                 );
598 598
                 if ($hash_check && $hash_check !== md5($session_data)) {
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
                                 'The stored data for session %1$s failed to pass a hash check and therefore appears to be invalid.',
603 603
                                 'event_espresso'
604 604
                             ),
605
-                            EE_Session::session_id_prefix . $this->_sid
605
+                            EE_Session::session_id_prefix.$this->_sid
606 606
                         ),
607 607
                         __FILE__, __FUNCTION__, __LINE__
608 608
                     );
@@ -611,21 +611,21 @@  discard block
 block discarded – undo
611 611
         } catch (Exception $e) {
612 612
             // let's just eat that error for now and attempt to correct any corrupted data
613 613
             global $wpdb;
614
-            $row          = $wpdb->get_row(
614
+            $row = $wpdb->get_row(
615 615
                 $wpdb->prepare(
616 616
                     "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s LIMIT 1",
617
-                    '_transient_' . $ssn_key
617
+                    '_transient_'.$ssn_key
618 618
                 )
619 619
             );
620 620
             $session_data = is_object($row) ? $row->option_value : null;
621 621
             if ($session_data) {
622 622
                 $session_data = preg_replace_callback(
623 623
                     '!s:(d+):"(.*?)";!',
624
-                    function ($match)
624
+                    function($match)
625 625
                     {
626 626
                         return $match[1] === strlen($match[2])
627 627
                             ? $match[0]
628
-                            : 's:' . strlen($match[2]) . ':"' . $match[2] . '";';
628
+                            : 's:'.strlen($match[2]).':"'.$match[2].'";';
629 629
                     },
630 630
                     $session_data
631 631
                 );
@@ -636,7 +636,7 @@  discard block
 block discarded – undo
636 636
         $session_data = $this->encryption instanceof EE_Encryption
637 637
             ? $this->encryption->base64_string_decode($session_data)
638 638
             : $session_data;
639
-        if (! is_array($session_data)) {
639
+        if ( ! is_array($session_data)) {
640 640
             try {
641 641
                 $session_data = maybe_unserialize($session_data);
642 642
             } catch (Exception $e) {
@@ -650,21 +650,21 @@  discard block
 block discarded – undo
650 650
                       . '</pre><br>'
651 651
                       . $this->find_serialize_error($session_data)
652 652
                     : '';
653
-                $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
653
+                $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
654 654
                 throw new InvalidSessionDataException($msg, 0, $e);
655 655
             }
656 656
         }
657 657
         // just a check to make sure the session array is indeed an array
658
-        if (! is_array($session_data)) {
658
+        if ( ! is_array($session_data)) {
659 659
             // no?!?! then something is wrong
660 660
             $msg = esc_html__(
661 661
                 'The session data is missing, invalid, or corrupted.',
662 662
                 'event_espresso'
663 663
             );
664 664
             $msg .= WP_DEBUG
665
-                ? '<br><pre>' . print_r($session_data, true) . '</pre><br>' . $this->find_serialize_error($session_data)
665
+                ? '<br><pre>'.print_r($session_data, true).'</pre><br>'.$this->find_serialize_error($session_data)
666 666
                 : '';
667
-            $this->cache_storage->delete(EE_Session::session_id_prefix . $this->_sid);
667
+            $this->cache_storage->delete(EE_Session::session_id_prefix.$this->_sid);
668 668
             throw new InvalidSessionDataException($msg);
669 669
         }
670 670
         if (isset($session_data['transaction']) && absint($session_data['transaction']) !== 0) {
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
         if (isset($_REQUEST['EESID'])) {
693 693
             $session_id = sanitize_text_field($_REQUEST['EESID']);
694 694
         } else {
695
-            $session_id = md5(session_id() . get_current_blog_id() . $this->_get_sid_salt());
695
+            $session_id = md5(session_id().get_current_blog_id().$this->_get_sid_salt());
696 696
         }
697 697
         return apply_filters('FHEE__EE_Session___generate_session_id__session_id', $session_id);
698 698
     }
@@ -800,19 +800,19 @@  discard block
 block discarded – undo
800 800
                     $page_visit = $this->_get_page_visit();
801 801
                     if ($page_visit) {
802 802
                         // set pages visited where the first will be the http referrer
803
-                        $this->_session_data['pages_visited'][ $this->_time ] = $page_visit;
803
+                        $this->_session_data['pages_visited'][$this->_time] = $page_visit;
804 804
                         // we'll only save the last 10 page visits.
805 805
                         $session_data['pages_visited'] = array_slice($this->_session_data['pages_visited'], -10);
806 806
                     }
807 807
                     break;
808 808
                 default :
809 809
                     // carry any other data over
810
-                    $session_data[ $key ] = $this->_session_data[ $key ];
810
+                    $session_data[$key] = $this->_session_data[$key];
811 811
             }
812 812
         }
813 813
         $this->_session_data = $session_data;
814 814
         // creating a new session does not require saving to the db just yet
815
-        if (! $new_session) {
815
+        if ( ! $new_session) {
816 816
             // ready? let's save
817 817
             if ($this->_save_session_to_db()) {
818 818
                 return true;
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
         }
877 877
         $transaction = $this->transaction();
878 878
         if ($transaction instanceof EE_Transaction) {
879
-            if (! $transaction->ID()) {
879
+            if ( ! $transaction->ID()) {
880 880
                 $transaction->save();
881 881
             }
882 882
             $this->_session_data['transaction'] = $transaction->ID();
@@ -890,14 +890,14 @@  discard block
 block discarded – undo
890 890
         // maybe save hash check
891 891
         if (apply_filters('FHEE__EE_Session___perform_session_id_hash_check', WP_DEBUG)) {
892 892
             $this->cache_storage->add(
893
-                EE_Session::hash_check_prefix . $this->_sid,
893
+                EE_Session::hash_check_prefix.$this->_sid,
894 894
                 md5($session_data),
895 895
                 $this->_lifespan
896 896
             );
897 897
         }
898 898
         // we're using the Transient API for storing session data,
899 899
         return $this->cache_storage->add(
900
-            EE_Session::session_id_prefix . $this->_sid,
900
+            EE_Session::session_id_prefix.$this->_sid,
901 901
             $session_data,
902 902
             $this->_lifespan
903 903
         );
@@ -926,8 +926,8 @@  discard block
 block discarded – undo
926 926
             'REMOTE_ADDR',
927 927
         );
928 928
         foreach ($server_keys as $key) {
929
-            if (isset($_SERVER[ $key ])) {
930
-                foreach (array_map('trim', explode(',', $_SERVER[ $key ])) as $ip) {
929
+            if (isset($_SERVER[$key])) {
930
+                foreach (array_map('trim', explode(',', $_SERVER[$key])) as $ip) {
931 931
                     if ($ip === '127.0.0.1' || filter_var($ip, FILTER_VALIDATE_IP) !== false) {
932 932
                         $visitor_ip = $ip;
933 933
                     }
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
      */
947 947
     public function _get_page_visit()
948 948
     {
949
-        $page_visit = home_url('/') . 'wp-admin/admin-ajax.php';
949
+        $page_visit = home_url('/').'wp-admin/admin-ajax.php';
950 950
         // check for request url
951 951
         if (isset($_SERVER['REQUEST_URI'])) {
952 952
             $http_host   = '';
@@ -962,14 +962,14 @@  discard block
 block discarded – undo
962 962
             // check for page_id in SERVER REQUEST
963 963
             if (isset($_REQUEST['page_id'])) {
964 964
                 // rebuild $e_reg without any of the extra parameters
965
-                $page_id = '?page_id=' . esc_attr($_REQUEST['page_id']) . '&amp;';
965
+                $page_id = '?page_id='.esc_attr($_REQUEST['page_id']).'&amp;';
966 966
             }
967 967
             // check for $e_reg in SERVER REQUEST
968 968
             if (isset($_REQUEST['ee'])) {
969 969
                 // rebuild $e_reg without any of the extra parameters
970
-                $e_reg = 'ee=' . esc_attr($_REQUEST['ee']);
970
+                $e_reg = 'ee='.esc_attr($_REQUEST['ee']);
971 971
             }
972
-            $page_visit = rtrim($http_host . $request_uri . $page_id . $e_reg, '?');
972
+            $page_visit = rtrim($http_host.$request_uri.$page_id.$e_reg, '?');
973 973
         }
974 974
         return $page_visit !== home_url('/wp-admin/admin-ajax.php') ? $page_visit : '';
975 975
     }
@@ -1005,7 +1005,7 @@  discard block
 block discarded – undo
1005 1005
     public function clear_session($class = '', $function = '')
1006 1006
     {
1007 1007
         //echo '<h3 style="color:#999;line-height:.9em;"><span style="color:#2EA2CC">' . __CLASS__ . '</span>::<span style="color:#E76700">' . __FUNCTION__ . '( ' . $class . '::' . $function . '() )</span><br/><span style="font-size:9px;font-weight:normal;">' . __FILE__ . '</span>    <b style="font-size:10px;">  ' . __LINE__ . ' </b></h3>';
1008
-        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : ' . $class . '::' . $function . '()');
1008
+        do_action('AHEE_log', __FILE__, __FUNCTION__, 'session cleared by : '.$class.'::'.$function.'()');
1009 1009
         $this->reset_cart();
1010 1010
         $this->reset_checkout();
1011 1011
         $this->reset_transaction();
@@ -1028,7 +1028,7 @@  discard block
 block discarded – undo
1028 1028
     public function reset_data($data_to_reset = array(), $show_all_notices = false)
1029 1029
     {
1030 1030
         // if $data_to_reset is not in an array, then put it in one
1031
-        if (! is_array($data_to_reset)) {
1031
+        if ( ! is_array($data_to_reset)) {
1032 1032
             $data_to_reset = array($data_to_reset);
1033 1033
         }
1034 1034
         // nothing ??? go home!
@@ -1042,11 +1042,11 @@  discard block
 block discarded – undo
1042 1042
         foreach ($data_to_reset as $reset) {
1043 1043
 
1044 1044
             // first check to make sure it is a valid session var
1045
-            if (isset($this->_session_data[ $reset ])) {
1045
+            if (isset($this->_session_data[$reset])) {
1046 1046
                 // then check to make sure it is not a default var
1047
-                if (! array_key_exists($reset, $this->_default_session_vars)) {
1047
+                if ( ! array_key_exists($reset, $this->_default_session_vars)) {
1048 1048
                     // remove session var
1049
-                    unset($this->_session_data[ $reset ]);
1049
+                    unset($this->_session_data[$reset]);
1050 1050
                     if ($show_all_notices) {
1051 1051
                         EE_Error::add_success(sprintf(__('The session variable %s was removed.', 'event_espresso'),
1052 1052
                             $reset), __FILE__, __FUNCTION__, __LINE__);
@@ -1126,7 +1126,7 @@  discard block
 block discarded – undo
1126 1126
             // or use that for the new transient cleanup query limit
1127 1127
             add_filter(
1128 1128
                 'FHEE__TransientCacheStorage__clearExpiredTransients__limit',
1129
-                function () use ($expired_session_transient_delete_query_limit)
1129
+                function() use ($expired_session_transient_delete_query_limit)
1130 1130
                 {
1131 1131
                     return $expired_session_transient_delete_query_limit;
1132 1132
                 }
@@ -1146,7 +1146,7 @@  discard block
 block discarded – undo
1146 1146
         $error = '<pre>';
1147 1147
         $data2 = preg_replace_callback(
1148 1148
             '!s:(\d+):"(.*?)";!',
1149
-            function ($match)
1149
+            function($match)
1150 1150
             {
1151 1151
                 return ($match[1] === strlen($match[2]))
1152 1152
                     ? $match[0]
@@ -1158,14 +1158,14 @@  discard block
 block discarded – undo
1158 1158
             },
1159 1159
             $data1
1160 1160
         );
1161
-        $max   = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1162
-        $error .= $data1 . PHP_EOL;
1163
-        $error .= $data2 . PHP_EOL;
1161
+        $max = (strlen($data1) > strlen($data2)) ? strlen($data1) : strlen($data2);
1162
+        $error .= $data1.PHP_EOL;
1163
+        $error .= $data2.PHP_EOL;
1164 1164
         for ($i = 0; $i < $max; $i++) {
1165
-            if (@$data1[ $i ] !== @$data2[ $i ]) {
1166
-                $error  .= 'Difference ' . @$data1[ $i ] . ' != ' . @$data2[ $i ] . PHP_EOL;
1167
-                $error  .= "\t-> ORD number " . ord(@$data1[ $i ]) . ' != ' . ord(@$data2[ $i ]) . PHP_EOL;
1168
-                $error  .= "\t-> Line Number = $i" . PHP_EOL;
1165
+            if (@$data1[$i] !== @$data2[$i]) {
1166
+                $error  .= 'Difference '.@$data1[$i].' != '.@$data2[$i].PHP_EOL;
1167
+                $error  .= "\t-> ORD number ".ord(@$data1[$i]).' != '.ord(@$data2[$i]).PHP_EOL;
1168
+                $error  .= "\t-> Line Number = $i".PHP_EOL;
1169 1169
                 $start  = ($i - 20);
1170 1170
                 $start  = ($start < 0) ? 0 : $start;
1171 1171
                 $length = 40;
@@ -1180,7 +1180,7 @@  discard block
 block discarded – undo
1180 1180
                 $error .= "\t-> Section Data1  = ";
1181 1181
                 $error .= substr_replace(
1182 1182
                     substr($data1, $start, $length),
1183
-                    "<b style=\"color:green\">{$data1[ $i ]}</b>",
1183
+                    "<b style=\"color:green\">{$data1[$i]}</b>",
1184 1184
                     $rpoint,
1185 1185
                     $rlength
1186 1186
                 );
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
                 $error .= "\t-> Section Data2  = ";
1189 1189
                 $error .= substr_replace(
1190 1190
                     substr($data2, $start, $length),
1191
-                    "<b style=\"color:red\">{$data2[ $i ]}</b>",
1191
+                    "<b style=\"color:red\">{$data2[$i]}</b>",
1192 1192
                     $rpoint,
1193 1193
                     $rlength
1194 1194
                 );
@@ -1219,7 +1219,7 @@  discard block
 block discarded – undo
1219 1219
     public function garbageCollection()
1220 1220
     {
1221 1221
         // only perform during regular requests if last garbage collection was over an hour ago
1222
-        if (! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1222
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX) && (time() - HOUR_IN_SECONDS) >= $this->_last_gc) {
1223 1223
             $this->_last_gc = time();
1224 1224
             $this->updateSessionSettings(array('last_gc' => $this->_last_gc));
1225 1225
             /** @type WPDB $wpdb */
@@ -1254,7 +1254,7 @@  discard block
 block discarded – undo
1254 1254
                 // AND option_value < 1508368198 LIMIT 50
1255 1255
                 $expired_sessions = $wpdb->get_col($SQL);
1256 1256
                 // valid results?
1257
-                if (! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1257
+                if ( ! $expired_sessions instanceof WP_Error && ! empty($expired_sessions)) {
1258 1258
                     $this->cache_storage->deleteMany($expired_sessions, true);
1259 1259
                 }
1260 1260
             }
Please login to merge, or discard this patch.
admin_pages/maintenance/Maintenance_Admin_Page.core.php 2 patches
Indentation   +749 added lines, -749 removed lines patch added patch discarded remove patch
@@ -28,765 +28,765 @@
 block discarded – undo
28 28
 {
29 29
 
30 30
 
31
-    /**
32
-     * @var EE_Datetime_Offset_Fix_Form
33
-     */
34
-    protected $datetime_fix_offset_form;
35
-
36
-
37
-
38
-    protected function _init_page_props()
39
-    {
40
-        $this->page_slug = EE_MAINTENANCE_PG_SLUG;
41
-        $this->page_label = EE_MAINTENANCE_LABEL;
42
-        $this->_admin_base_url = EE_MAINTENANCE_ADMIN_URL;
43
-        $this->_admin_base_path = EE_MAINTENANCE_ADMIN;
44
-    }
45
-
46
-
47
-
48
-    protected function _ajax_hooks()
49
-    {
50
-        add_action('wp_ajax_migration_step', array($this, 'migration_step'));
51
-        add_action('wp_ajax_add_error_to_migrations_ran', array($this, 'add_error_to_migrations_ran'));
52
-    }
53
-
54
-
55
-
56
-    protected function _define_page_props()
57
-    {
58
-        $this->_admin_page_title = EE_MAINTENANCE_LABEL;
59
-        $this->_labels = array(
60
-            'buttons' => array(
61
-                'reset_reservations' => esc_html__('Reset Ticket and Datetime Reserved Counts', 'event_espresso'),
62
-                'reset_capabilities' => esc_html__('Reset Event Espresso Capabilities', 'event_espresso'),
63
-            ),
64
-        );
65
-    }
66
-
67
-
68
-
69
-    protected function _set_page_routes()
70
-    {
71
-        $this->_page_routes = array(
72
-            'default'                             => array(
73
-                'func'       => '_maintenance',
74
-                'capability' => 'manage_options',
75
-            ),
76
-            'change_maintenance_level'            => array(
77
-                'func'       => '_change_maintenance_level',
78
-                'capability' => 'manage_options',
79
-                'noheader'   => true,
80
-            ),
81
-            'system_status'                       => array(
82
-                'func'       => '_system_status',
83
-                'capability' => 'manage_options',
84
-            ),
85
-            'download_system_status' => array(
86
-                'func'       => '_download_system_status',
87
-                'capability' => 'manage_options',
88
-                'noheader'   => true,
89
-            ),
90
-            'send_migration_crash_report'         => array(
91
-                'func'       => '_send_migration_crash_report',
92
-                'capability' => 'manage_options',
93
-                'noheader'   => true,
94
-            ),
95
-            'confirm_migration_crash_report_sent' => array(
96
-                'func'       => '_confirm_migration_crash_report_sent',
97
-                'capability' => 'manage_options',
98
-            ),
99
-            'data_reset'                          => array(
100
-                'func'       => '_data_reset_and_delete',
101
-                'capability' => 'manage_options',
102
-            ),
103
-            'reset_db'                            => array(
104
-                'func'       => '_reset_db',
105
-                'capability' => 'manage_options',
106
-                'noheader'   => true,
107
-                'args'       => array('nuke_old_ee4_data' => true),
108
-            ),
109
-            'start_with_fresh_ee4_db'             => array(
110
-                'func'       => '_reset_db',
111
-                'capability' => 'manage_options',
112
-                'noheader'   => true,
113
-                'args'       => array('nuke_old_ee4_data' => false),
114
-            ),
115
-            'delete_db'                           => array(
116
-                'func'       => '_delete_db',
117
-                'capability' => 'manage_options',
118
-                'noheader'   => true,
119
-            ),
120
-            'rerun_migration_from_ee3'            => array(
121
-                'func'       => '_rerun_migration_from_ee3',
122
-                'capability' => 'manage_options',
123
-                'noheader'   => true,
124
-            ),
125
-            'reset_reservations'                  => array(
126
-                'func'       => '_reset_reservations',
127
-                'capability' => 'manage_options',
128
-                'noheader'   => true,
129
-            ),
130
-            'reset_capabilities'                  => array(
131
-                'func'       => '_reset_capabilities',
132
-                'capability' => 'manage_options',
133
-                'noheader'   => true,
134
-            ),
135
-            'reattempt_migration'                 => array(
136
-                'func'       => '_reattempt_migration',
137
-                'capability' => 'manage_options',
138
-                'noheader'   => true,
139
-            ),
140
-            'datetime_tools' => array(
141
-                'func' => '_datetime_tools',
142
-                'capability' => 'manage_options'
143
-            ),
144
-            'run_datetime_offset_fix' => array(
145
-                'func' => '_apply_datetime_offset',
146
-                'noheader' => true,
147
-                'headers_sent_route' => 'datetime_tools',
148
-                'capability' => 'manage_options'
149
-            )
150
-        );
151
-    }
152
-
153
-
154
-
155
-    protected function _set_page_config()
156
-    {
157
-        $this->_page_config = array(
158
-            'default'       => array(
159
-                'nav'           => array(
160
-                    'label' => esc_html__('Maintenance', 'event_espresso'),
161
-                    'order' => 10,
162
-                ),
163
-                'require_nonce' => false,
164
-            ),
165
-            'data_reset'    => array(
166
-                'nav'           => array(
167
-                    'label' => esc_html__('Reset/Delete Data', 'event_espresso'),
168
-                    'order' => 20,
169
-                ),
170
-                'require_nonce' => false,
171
-            ),
172
-            'datetime_tools' => array(
173
-                'nav' => array(
174
-                    'label' => esc_html__('Datetime Utilities', 'event_espresso'),
175
-                    'order' => 25
176
-                ),
177
-                'require_nonce' => false,
178
-            ),
179
-            'system_status' => array(
180
-                'nav'           => array(
181
-                    'label' => esc_html__("System Information", "event_espresso"),
182
-                    'order' => 30,
183
-                ),
184
-                'require_nonce' => false,
185
-            ),
186
-        );
187
-    }
188
-
189
-
190
-
191
-    /**
192
-     * default maintenance page. If we're in maintenance mode level 2, then we need to show
193
-     * the migration scripts and all that UI.
194
-     */
195
-    public function _maintenance()
196
-    {
197
-        //it all depends if we're in maintenance model level 1 (frontend-only) or
198
-        //level 2 (everything except maintenance page)
199
-        try {
200
-            //get the current maintenance level and check if
201
-            //we are removed
202
-            $mm = EE_Maintenance_Mode::instance()->level();
203
-            $placed_in_mm = EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
204
-            if ($mm == EE_Maintenance_Mode::level_2_complete_maintenance && ! $placed_in_mm) {
205
-                //we just took the site out of maintenance mode, so notify the user.
206
-                //unfortunately this message appears to be echoed on the NEXT page load...
207
-                //oh well, we should really be checking for this on addon deactivation anyways
208
-                EE_Error::add_attention(__('Site taken out of maintenance mode because no data migration scripts are required',
209
-                    'event_espresso'));
210
-                $this->_process_notices(array('page' => 'espresso_maintenance_settings'), false);
211
-            }
212
-            //in case an exception is thrown while trying to handle migrations
213
-            switch (EE_Maintenance_Mode::instance()->level()) {
214
-                case EE_Maintenance_Mode::level_0_not_in_maintenance:
215
-                case EE_Maintenance_Mode::level_1_frontend_only_maintenance:
216
-                    $show_maintenance_switch = true;
217
-                    $show_backup_db_text = false;
218
-                    $show_migration_progress = false;
219
-                    $script_names = array();
220
-                    $addons_should_be_upgraded_first = false;
221
-                    break;
222
-                case EE_Maintenance_Mode::level_2_complete_maintenance:
223
-                    $show_maintenance_switch = false;
224
-                    $show_migration_progress = true;
225
-                    if (isset($this->_req_data['continue_migration'])) {
226
-                        $show_backup_db_text = false;
227
-                    } else {
228
-                        $show_backup_db_text = true;
229
-                    }
230
-                    $scripts_needing_to_run = EE_Data_Migration_Manager::instance()
231
-                                                                       ->check_for_applicable_data_migration_scripts();
232
-                    $addons_should_be_upgraded_first = EE_Data_Migration_Manager::instance()->addons_need_updating();
233
-                    $script_names = array();
234
-                    $current_script = null;
235
-                    foreach ($scripts_needing_to_run as $script) {
236
-                        if ($script instanceof EE_Data_Migration_Script_Base) {
237
-                            if ( ! $current_script) {
238
-                                $current_script = $script;
239
-                                $current_script->migration_page_hooks();
240
-                            }
241
-                            $script_names[] = $script->pretty_name();
242
-                        }
243
-                    }
244
-                    break;
245
-            }
246
-            $most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
247
-            $exception_thrown = false;
248
-        } catch (EE_Error $e) {
249
-            EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
250
-            //now, just so we can display the page correctly, make a error migration script stage object
251
-            //and also put the error on it. It only persists for the duration of this request
252
-            $most_recent_migration = new EE_DMS_Unknown_1_0_0();
253
-            $most_recent_migration->add_error($e->getMessage());
254
-            $exception_thrown = true;
255
-        }
256
-        $current_db_state = EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set();
257
-        $current_db_state = str_replace('.decaf', '', $current_db_state);
258
-        if ($exception_thrown
259
-            || ($most_recent_migration
260
-                && $most_recent_migration instanceof EE_Data_Migration_Script_Base
261
-                && $most_recent_migration->is_broken()
262
-            )
263
-        ) {
264
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_was_borked_page.template.php';
265
-            $this->_template_args['support_url'] = 'http://eventespresso.com/support/forums/';
266
-            $this->_template_args['next_url'] = EEH_URL::add_query_args_and_nonce(array('action'  => 'confirm_migration_crash_report_sent',
267
-                                                                                        'success' => '0',
268
-            ), EE_MAINTENANCE_ADMIN_URL);
269
-        } elseif ($addons_should_be_upgraded_first) {
270
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_upgrade_addons_before_migrating.template.php';
271
-        } else {
272
-            if ($most_recent_migration
273
-                && $most_recent_migration instanceof EE_Data_Migration_Script_Base
274
-                && $most_recent_migration->can_continue()
275
-            ) {
276
-                $show_backup_db_text = false;
277
-                $show_continue_current_migration_script = true;
278
-                $show_most_recent_migration = true;
279
-            } elseif (isset($this->_req_data['continue_migration'])) {
280
-                $show_most_recent_migration = true;
281
-                $show_continue_current_migration_script = false;
282
-            } else {
283
-                $show_most_recent_migration = false;
284
-                $show_continue_current_migration_script = false;
285
-            }
286
-            if (isset($current_script)) {
287
-                $migrates_to = $current_script->migrates_to_version();
288
-                $plugin_slug = $migrates_to['slug'];
289
-                $new_version = $migrates_to['version'];
290
-                $this->_template_args = array_merge($this->_template_args, array(
291
-                    'current_db_state' => sprintf(__("EE%s (%s)", "event_espresso"),
292
-                        isset($current_db_state[$plugin_slug]) ? $current_db_state[$plugin_slug] : 3, $plugin_slug),
293
-                    'next_db_state'    => isset($current_script) ? sprintf(__("EE%s (%s)", 'event_espresso'),
294
-                        $new_version, $plugin_slug) : null,
295
-                ));
296
-            } else {
297
-                $this->_template_args['current_db_state'] = null;
298
-                $this->_template_args['next_db_state'] = null;
299
-            }
300
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_page.template.php';
301
-            $this->_template_args = array_merge(
302
-                $this->_template_args,
303
-                array(
304
-                    'show_most_recent_migration'             => $show_most_recent_migration,
305
-                    //flag for showing the most recent migration's status and/or errors
306
-                    'show_migration_progress'                => $show_migration_progress,
307
-                    //flag for showing the option to run migrations and see their progress
308
-                    'show_backup_db_text'                    => $show_backup_db_text,
309
-                    //flag for showing text telling the user to backup their DB
310
-                    'show_maintenance_switch'                => $show_maintenance_switch,
311
-                    //flag for showing the option to change maintenance mode between levels 0 and 1
312
-                    'script_names'                           => $script_names,
313
-                    //array of names of scripts that have run
314
-                    'show_continue_current_migration_script' => $show_continue_current_migration_script,
315
-                    //flag to change wording to indicating that we're only CONTINUING a migration script (somehow it got interrupted0
316
-                    'reset_db_page_link'                     => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reset_db'),
317
-                        EE_MAINTENANCE_ADMIN_URL),
318
-                    'data_reset_page'                        => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'data_reset'),
319
-                        EE_MAINTENANCE_ADMIN_URL),
320
-                    'update_migration_script_page_link'      => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'change_maintenance_level'),
321
-                        EE_MAINTENANCE_ADMIN_URL),
322
-                    'ultimate_db_state'                      => sprintf(__("EE%s", 'event_espresso'),
323
-                        espresso_version()),
324
-                )
325
-            );
326
-            //make sure we have the form fields helper available. It usually is, but sometimes it isn't
327
-        }
328
-        $this->_template_args['most_recent_migration'] = $most_recent_migration;//the actual most recently ran migration
329
-        //now render the migration options part, and put it in a variable
330
-        $migration_options_template_file = apply_filters(
331
-            'FHEE__ee_migration_page__migration_options_template',
332
-            EE_MAINTENANCE_TEMPLATE_PATH . 'migration_options_from_ee4.template.php'
333
-        );
334
-        $migration_options_html = EEH_Template::display_template($migration_options_template_file, $this->_template_args,true);
335
-        $this->_template_args['migration_options_html'] = $migration_options_html;
336
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
337
-            $this->_template_args, true);
338
-        $this->display_admin_page_with_sidebar();
339
-    }
340
-
341
-
342
-
343
-    /**
344
-     * returns JSON and executes another step of the currently-executing data migration (called via ajax)
345
-     */
346
-    public function migration_step()
347
-    {
348
-        $this->_template_args['data'] = EE_Data_Migration_Manager::instance()->response_to_migration_ajax_request();
349
-        $this->_return_json();
350
-    }
351
-
352
-
353
-
354
-    /**
355
-     * Can be used by js when it notices a response with HTML in it in order
356
-     * to log the malformed response
357
-     */
358
-    public function add_error_to_migrations_ran()
359
-    {
360
-        EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($this->_req_data['message']);
361
-        $this->_template_args['data'] = array('ok' => true);
362
-        $this->_return_json();
363
-    }
364
-
365
-
366
-
367
-    /**
368
-     * changes the maintenance level, provided there are still no migration scripts that should run
369
-     */
370
-    public function _change_maintenance_level()
371
-    {
372
-        $new_level = absint($this->_req_data['maintenance_mode_level']);
373
-        if ( ! EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
374
-            EE_Maintenance_Mode::instance()->set_maintenance_level($new_level);
375
-            $success = true;
376
-        } else {
377
-            EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
378
-            $success = false;
379
-        }
380
-        $this->_redirect_after_action($success, 'Maintenance Mode', esc_html__("Updated", "event_espresso"));
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * a tab with options for resetting and/or deleting EE data
387
-     *
388
-     * @throws \EE_Error
389
-     * @throws \DomainException
390
-     */
391
-    public function _data_reset_and_delete()
392
-    {
393
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_data_reset_and_delete.template.php';
394
-        $this->_template_args['reset_reservations_button'] = $this->get_action_link_or_button(
395
-            'reset_reservations',
396
-            'reset_reservations',
397
-            array(),
398
-            'button button-primary ee-confirm',
399
-            '',
400
-            false
401
-        );
402
-        $this->_template_args['reset_capabilities_button'] = $this->get_action_link_or_button(
403
-            'reset_capabilities',
404
-            'reset_capabilities',
405
-            array(),
406
-            'button button-primary ee-confirm',
407
-            '',
408
-            false
409
-        );
410
-        $this->_template_args['delete_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
411
-            array('action' => 'delete_db'),
412
-            EE_MAINTENANCE_ADMIN_URL
413
-        );
414
-        $this->_template_args['reset_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
415
-            array('action' => 'reset_db'),
416
-            EE_MAINTENANCE_ADMIN_URL
417
-        );
418
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
419
-            $this->_template_path,
420
-            $this->_template_args,
421
-            true
422
-        );
423
-        $this->display_admin_page_with_sidebar();
424
-    }
425
-
426
-
427
-
428
-    protected function _reset_reservations()
429
-    {
430
-        if(\EED_Ticket_Sales_Monitor::reset_reservation_counts()) {
431
-            EE_Error::add_success(
432
-                __(
433
-                    'Ticket and datetime reserved counts have been successfully reset.',
434
-                    'event_espresso'
435
-                )
436
-            );
437
-        } else {
438
-            EE_Error::add_success(
439
-                __(
440
-                    'Ticket and datetime reserved counts were correct and did not need resetting.',
441
-                    'event_espresso'
442
-                )
443
-            );
444
-        }
445
-        $this->_redirect_after_action(true, '', '', array('action' => 'data_reset'), true);
446
-    }
447
-
448
-
449
-
450
-    protected function _reset_capabilities()
451
-    {
452
-        EE_Registry::instance()->CAP->init_caps(true);
453
-        EE_Error::add_success(__('Default Event Espresso capabilities have been restored for all current roles.',
454
-            'event_espresso'));
455
-        $this->_redirect_after_action(false, '', '', array('action' => 'data_reset'), true);
456
-    }
457
-
458
-
459
-
460
-    /**
461
-     * resets the DMSs so we can attempt to continue migrating after a fatal error
462
-     * (only a good idea when someone has somehow tried ot fix whatever caused
463
-     * the fatal error in teh first place)
464
-     */
465
-    protected function _reattempt_migration()
466
-    {
467
-        EE_Data_Migration_Manager::instance()->reattempt();
468
-        $this->_redirect_after_action(false, '', '', array('action' => 'default'), true);
469
-    }
470
-
471
-
472
-
473
-    /**
474
-     * shows the big ol' System Information page
475
-     */
476
-    public function _system_status()
477
-    {
478
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_system_stati_page.template.php';
479
-        $this->_template_args['system_stati'] = EEM_System_Status::instance()->get_system_stati();
480
-        $this->_template_args['download_system_status_url'] = EE_Admin_Page::add_query_args_and_nonce(
481
-            array(
482
-                'action' => 'download_system_status',
483
-            ),
484
-            EE_MAINTENANCE_ADMIN_URL
485
-        );
486
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
487
-            $this->_template_args, true);
488
-        $this->display_admin_page_with_sidebar();
489
-    }
490
-
491
-    /**
492
-     * Downloads an HTML file of the system status that can be easily stored or emailed
493
-     */
494
-    public function _download_system_status()
495
-    {
496
-        $status_info = EEM_System_Status::instance()->get_system_stati();
497
-        header( 'Content-Disposition: attachment' );
498
-        header( "Content-Disposition: attachment; filename=system_status_" . sanitize_key( site_url() ) . ".html" );
499
-        echo "<style>table{border:1px solid darkgrey;}td{vertical-align:top}</style>";
500
-        echo "<h1>System Information for " . site_url() . "</h1>";
501
-        echo EEH_Template::layout_array_as_table( $status_info );
502
-        die;
503
-    }
504
-
505
-
506
-
507
-    public function _send_migration_crash_report()
508
-    {
509
-        $from = $this->_req_data['from'];
510
-        $from_name = $this->_req_data['from_name'];
511
-        $body = $this->_req_data['body'];
512
-        try {
513
-            $success = wp_mail(EE_SUPPORT_EMAIL,
514
-                'Migration Crash Report',
515
-                $body . "/r/n<br>" . print_r(EEM_System_Status::instance()->get_system_stati(), true),
516
-                array(
517
-                    "from:$from_name<$from>",
518
-                    //					'content-type:text/html charset=UTF-8'
519
-                ));
520
-        } catch (Exception $e) {
521
-            $success = false;
522
-        }
523
-        $this->_redirect_after_action($success, esc_html__("Migration Crash Report", "event_espresso"),
524
-            esc_html__("sent", "event_espresso"),
525
-            array('success' => $success, 'action' => 'confirm_migration_crash_report_sent'));
526
-    }
527
-
528
-
529
-
530
-    public function _confirm_migration_crash_report_sent()
531
-    {
532
-        try {
533
-            $most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
534
-        } catch (EE_Error $e) {
535
-            EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
536
-            //now, just so we can display the page correctly, make a error migration script stage object
537
-            //and also put the error on it. It only persists for the duration of this request
538
-            $most_recent_migration = new EE_DMS_Unknown_1_0_0();
539
-            $most_recent_migration->add_error($e->getMessage());
540
-        }
541
-        $success = $this->_req_data['success'] == '1' ? true : false;
542
-        $this->_template_args['success'] = $success;
543
-        $this->_template_args['most_recent_migration'] = $most_recent_migration;
544
-        $this->_template_args['reset_db_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reset_db'),
545
-            EE_MAINTENANCE_ADMIN_URL);
546
-        $this->_template_args['reset_db_page_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'data_reset'),
547
-            EE_MAINTENANCE_ADMIN_URL);
548
-        $this->_template_args['reattempt_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reattempt_migration'),
549
-            EE_MAINTENANCE_ADMIN_URL);
550
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_confirm_migration_crash_report_sent.template.php';
551
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
552
-            $this->_template_args, true);
553
-        $this->display_admin_page_with_sidebar();
554
-    }
555
-
556
-
557
-
558
-    /**
559
-     * Resets the entire EE4 database.
560
-     * Currently basically only sets up ee4 database for a fresh install- doesn't
561
-     * actually clean out the old wp options, or cpts (although does erase old ee table data)
562
-     *
563
-     * @param boolean $nuke_old_ee4_data controls whether or not we
564
-     *                                   destroy the old ee4 data, or just try initializing ee4 default data
565
-     */
566
-    public function _reset_db($nuke_old_ee4_data = true)
567
-    {
568
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
569
-        if ($nuke_old_ee4_data) {
570
-            EEH_Activation::delete_all_espresso_cpt_data();
571
-            EEH_Activation::delete_all_espresso_tables_and_data(false);
572
-            EEH_Activation::remove_cron_tasks();
573
-        }
574
-        //make sure when we reset the registry's config that it
575
-        //switches to using the new singleton
576
-        EE_Registry::instance()->CFG = EE_Registry::instance()->CFG->reset(true);
577
-        EE_System::instance()->initialize_db_if_no_migrations_required(true);
578
-        EE_System::instance()->redirect_to_about_ee();
579
-    }
580
-
581
-
582
-
583
-    /**
584
-     * Deletes ALL EE tables, Records, and Options from the database.
585
-     */
586
-    public function _delete_db()
587
-    {
588
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
589
-        EEH_Activation::delete_all_espresso_cpt_data();
590
-        EEH_Activation::delete_all_espresso_tables_and_data();
591
-        EEH_Activation::remove_cron_tasks();
592
-        EEH_Activation::deactivate_event_espresso();
593
-        wp_safe_redirect(admin_url('plugins.php'));
594
-        exit;
595
-    }
596
-
597
-
598
-
599
-    /**
600
-     * sets up EE4 to rerun the migrations from ee3 to ee4
601
-     */
602
-    public function _rerun_migration_from_ee3()
603
-    {
604
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
605
-        EEH_Activation::delete_all_espresso_cpt_data();
606
-        EEH_Activation::delete_all_espresso_tables_and_data(false);
607
-        //set the db state to something that will require migrations
608
-        update_option(EE_Data_Migration_Manager::current_database_state, '3.1.36.0');
609
-        EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_2_complete_maintenance);
610
-        $this->_redirect_after_action(true, esc_html__("Database", 'event_espresso'), esc_html__("reset", 'event_espresso'));
611
-    }
612
-
613
-
614
-
615
-    //none of the below group are currently used for Gateway Settings
616
-    protected function _add_screen_options()
617
-    {
618
-    }
619
-
620
-
621
-
622
-    protected function _add_feature_pointers()
623
-    {
624
-    }
625
-
31
+	/**
32
+	 * @var EE_Datetime_Offset_Fix_Form
33
+	 */
34
+	protected $datetime_fix_offset_form;
35
+
36
+
37
+
38
+	protected function _init_page_props()
39
+	{
40
+		$this->page_slug = EE_MAINTENANCE_PG_SLUG;
41
+		$this->page_label = EE_MAINTENANCE_LABEL;
42
+		$this->_admin_base_url = EE_MAINTENANCE_ADMIN_URL;
43
+		$this->_admin_base_path = EE_MAINTENANCE_ADMIN;
44
+	}
45
+
46
+
47
+
48
+	protected function _ajax_hooks()
49
+	{
50
+		add_action('wp_ajax_migration_step', array($this, 'migration_step'));
51
+		add_action('wp_ajax_add_error_to_migrations_ran', array($this, 'add_error_to_migrations_ran'));
52
+	}
53
+
54
+
55
+
56
+	protected function _define_page_props()
57
+	{
58
+		$this->_admin_page_title = EE_MAINTENANCE_LABEL;
59
+		$this->_labels = array(
60
+			'buttons' => array(
61
+				'reset_reservations' => esc_html__('Reset Ticket and Datetime Reserved Counts', 'event_espresso'),
62
+				'reset_capabilities' => esc_html__('Reset Event Espresso Capabilities', 'event_espresso'),
63
+			),
64
+		);
65
+	}
66
+
67
+
68
+
69
+	protected function _set_page_routes()
70
+	{
71
+		$this->_page_routes = array(
72
+			'default'                             => array(
73
+				'func'       => '_maintenance',
74
+				'capability' => 'manage_options',
75
+			),
76
+			'change_maintenance_level'            => array(
77
+				'func'       => '_change_maintenance_level',
78
+				'capability' => 'manage_options',
79
+				'noheader'   => true,
80
+			),
81
+			'system_status'                       => array(
82
+				'func'       => '_system_status',
83
+				'capability' => 'manage_options',
84
+			),
85
+			'download_system_status' => array(
86
+				'func'       => '_download_system_status',
87
+				'capability' => 'manage_options',
88
+				'noheader'   => true,
89
+			),
90
+			'send_migration_crash_report'         => array(
91
+				'func'       => '_send_migration_crash_report',
92
+				'capability' => 'manage_options',
93
+				'noheader'   => true,
94
+			),
95
+			'confirm_migration_crash_report_sent' => array(
96
+				'func'       => '_confirm_migration_crash_report_sent',
97
+				'capability' => 'manage_options',
98
+			),
99
+			'data_reset'                          => array(
100
+				'func'       => '_data_reset_and_delete',
101
+				'capability' => 'manage_options',
102
+			),
103
+			'reset_db'                            => array(
104
+				'func'       => '_reset_db',
105
+				'capability' => 'manage_options',
106
+				'noheader'   => true,
107
+				'args'       => array('nuke_old_ee4_data' => true),
108
+			),
109
+			'start_with_fresh_ee4_db'             => array(
110
+				'func'       => '_reset_db',
111
+				'capability' => 'manage_options',
112
+				'noheader'   => true,
113
+				'args'       => array('nuke_old_ee4_data' => false),
114
+			),
115
+			'delete_db'                           => array(
116
+				'func'       => '_delete_db',
117
+				'capability' => 'manage_options',
118
+				'noheader'   => true,
119
+			),
120
+			'rerun_migration_from_ee3'            => array(
121
+				'func'       => '_rerun_migration_from_ee3',
122
+				'capability' => 'manage_options',
123
+				'noheader'   => true,
124
+			),
125
+			'reset_reservations'                  => array(
126
+				'func'       => '_reset_reservations',
127
+				'capability' => 'manage_options',
128
+				'noheader'   => true,
129
+			),
130
+			'reset_capabilities'                  => array(
131
+				'func'       => '_reset_capabilities',
132
+				'capability' => 'manage_options',
133
+				'noheader'   => true,
134
+			),
135
+			'reattempt_migration'                 => array(
136
+				'func'       => '_reattempt_migration',
137
+				'capability' => 'manage_options',
138
+				'noheader'   => true,
139
+			),
140
+			'datetime_tools' => array(
141
+				'func' => '_datetime_tools',
142
+				'capability' => 'manage_options'
143
+			),
144
+			'run_datetime_offset_fix' => array(
145
+				'func' => '_apply_datetime_offset',
146
+				'noheader' => true,
147
+				'headers_sent_route' => 'datetime_tools',
148
+				'capability' => 'manage_options'
149
+			)
150
+		);
151
+	}
152
+
153
+
154
+
155
+	protected function _set_page_config()
156
+	{
157
+		$this->_page_config = array(
158
+			'default'       => array(
159
+				'nav'           => array(
160
+					'label' => esc_html__('Maintenance', 'event_espresso'),
161
+					'order' => 10,
162
+				),
163
+				'require_nonce' => false,
164
+			),
165
+			'data_reset'    => array(
166
+				'nav'           => array(
167
+					'label' => esc_html__('Reset/Delete Data', 'event_espresso'),
168
+					'order' => 20,
169
+				),
170
+				'require_nonce' => false,
171
+			),
172
+			'datetime_tools' => array(
173
+				'nav' => array(
174
+					'label' => esc_html__('Datetime Utilities', 'event_espresso'),
175
+					'order' => 25
176
+				),
177
+				'require_nonce' => false,
178
+			),
179
+			'system_status' => array(
180
+				'nav'           => array(
181
+					'label' => esc_html__("System Information", "event_espresso"),
182
+					'order' => 30,
183
+				),
184
+				'require_nonce' => false,
185
+			),
186
+		);
187
+	}
188
+
189
+
190
+
191
+	/**
192
+	 * default maintenance page. If we're in maintenance mode level 2, then we need to show
193
+	 * the migration scripts and all that UI.
194
+	 */
195
+	public function _maintenance()
196
+	{
197
+		//it all depends if we're in maintenance model level 1 (frontend-only) or
198
+		//level 2 (everything except maintenance page)
199
+		try {
200
+			//get the current maintenance level and check if
201
+			//we are removed
202
+			$mm = EE_Maintenance_Mode::instance()->level();
203
+			$placed_in_mm = EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
204
+			if ($mm == EE_Maintenance_Mode::level_2_complete_maintenance && ! $placed_in_mm) {
205
+				//we just took the site out of maintenance mode, so notify the user.
206
+				//unfortunately this message appears to be echoed on the NEXT page load...
207
+				//oh well, we should really be checking for this on addon deactivation anyways
208
+				EE_Error::add_attention(__('Site taken out of maintenance mode because no data migration scripts are required',
209
+					'event_espresso'));
210
+				$this->_process_notices(array('page' => 'espresso_maintenance_settings'), false);
211
+			}
212
+			//in case an exception is thrown while trying to handle migrations
213
+			switch (EE_Maintenance_Mode::instance()->level()) {
214
+				case EE_Maintenance_Mode::level_0_not_in_maintenance:
215
+				case EE_Maintenance_Mode::level_1_frontend_only_maintenance:
216
+					$show_maintenance_switch = true;
217
+					$show_backup_db_text = false;
218
+					$show_migration_progress = false;
219
+					$script_names = array();
220
+					$addons_should_be_upgraded_first = false;
221
+					break;
222
+				case EE_Maintenance_Mode::level_2_complete_maintenance:
223
+					$show_maintenance_switch = false;
224
+					$show_migration_progress = true;
225
+					if (isset($this->_req_data['continue_migration'])) {
226
+						$show_backup_db_text = false;
227
+					} else {
228
+						$show_backup_db_text = true;
229
+					}
230
+					$scripts_needing_to_run = EE_Data_Migration_Manager::instance()
231
+																	   ->check_for_applicable_data_migration_scripts();
232
+					$addons_should_be_upgraded_first = EE_Data_Migration_Manager::instance()->addons_need_updating();
233
+					$script_names = array();
234
+					$current_script = null;
235
+					foreach ($scripts_needing_to_run as $script) {
236
+						if ($script instanceof EE_Data_Migration_Script_Base) {
237
+							if ( ! $current_script) {
238
+								$current_script = $script;
239
+								$current_script->migration_page_hooks();
240
+							}
241
+							$script_names[] = $script->pretty_name();
242
+						}
243
+					}
244
+					break;
245
+			}
246
+			$most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
247
+			$exception_thrown = false;
248
+		} catch (EE_Error $e) {
249
+			EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
250
+			//now, just so we can display the page correctly, make a error migration script stage object
251
+			//and also put the error on it. It only persists for the duration of this request
252
+			$most_recent_migration = new EE_DMS_Unknown_1_0_0();
253
+			$most_recent_migration->add_error($e->getMessage());
254
+			$exception_thrown = true;
255
+		}
256
+		$current_db_state = EE_Data_Migration_Manager::instance()->ensure_current_database_state_is_set();
257
+		$current_db_state = str_replace('.decaf', '', $current_db_state);
258
+		if ($exception_thrown
259
+			|| ($most_recent_migration
260
+				&& $most_recent_migration instanceof EE_Data_Migration_Script_Base
261
+				&& $most_recent_migration->is_broken()
262
+			)
263
+		) {
264
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_was_borked_page.template.php';
265
+			$this->_template_args['support_url'] = 'http://eventespresso.com/support/forums/';
266
+			$this->_template_args['next_url'] = EEH_URL::add_query_args_and_nonce(array('action'  => 'confirm_migration_crash_report_sent',
267
+																						'success' => '0',
268
+			), EE_MAINTENANCE_ADMIN_URL);
269
+		} elseif ($addons_should_be_upgraded_first) {
270
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_upgrade_addons_before_migrating.template.php';
271
+		} else {
272
+			if ($most_recent_migration
273
+				&& $most_recent_migration instanceof EE_Data_Migration_Script_Base
274
+				&& $most_recent_migration->can_continue()
275
+			) {
276
+				$show_backup_db_text = false;
277
+				$show_continue_current_migration_script = true;
278
+				$show_most_recent_migration = true;
279
+			} elseif (isset($this->_req_data['continue_migration'])) {
280
+				$show_most_recent_migration = true;
281
+				$show_continue_current_migration_script = false;
282
+			} else {
283
+				$show_most_recent_migration = false;
284
+				$show_continue_current_migration_script = false;
285
+			}
286
+			if (isset($current_script)) {
287
+				$migrates_to = $current_script->migrates_to_version();
288
+				$plugin_slug = $migrates_to['slug'];
289
+				$new_version = $migrates_to['version'];
290
+				$this->_template_args = array_merge($this->_template_args, array(
291
+					'current_db_state' => sprintf(__("EE%s (%s)", "event_espresso"),
292
+						isset($current_db_state[$plugin_slug]) ? $current_db_state[$plugin_slug] : 3, $plugin_slug),
293
+					'next_db_state'    => isset($current_script) ? sprintf(__("EE%s (%s)", 'event_espresso'),
294
+						$new_version, $plugin_slug) : null,
295
+				));
296
+			} else {
297
+				$this->_template_args['current_db_state'] = null;
298
+				$this->_template_args['next_db_state'] = null;
299
+			}
300
+			$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_page.template.php';
301
+			$this->_template_args = array_merge(
302
+				$this->_template_args,
303
+				array(
304
+					'show_most_recent_migration'             => $show_most_recent_migration,
305
+					//flag for showing the most recent migration's status and/or errors
306
+					'show_migration_progress'                => $show_migration_progress,
307
+					//flag for showing the option to run migrations and see their progress
308
+					'show_backup_db_text'                    => $show_backup_db_text,
309
+					//flag for showing text telling the user to backup their DB
310
+					'show_maintenance_switch'                => $show_maintenance_switch,
311
+					//flag for showing the option to change maintenance mode between levels 0 and 1
312
+					'script_names'                           => $script_names,
313
+					//array of names of scripts that have run
314
+					'show_continue_current_migration_script' => $show_continue_current_migration_script,
315
+					//flag to change wording to indicating that we're only CONTINUING a migration script (somehow it got interrupted0
316
+					'reset_db_page_link'                     => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reset_db'),
317
+						EE_MAINTENANCE_ADMIN_URL),
318
+					'data_reset_page'                        => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'data_reset'),
319
+						EE_MAINTENANCE_ADMIN_URL),
320
+					'update_migration_script_page_link'      => EE_Admin_Page::add_query_args_and_nonce(array('action' => 'change_maintenance_level'),
321
+						EE_MAINTENANCE_ADMIN_URL),
322
+					'ultimate_db_state'                      => sprintf(__("EE%s", 'event_espresso'),
323
+						espresso_version()),
324
+				)
325
+			);
326
+			//make sure we have the form fields helper available. It usually is, but sometimes it isn't
327
+		}
328
+		$this->_template_args['most_recent_migration'] = $most_recent_migration;//the actual most recently ran migration
329
+		//now render the migration options part, and put it in a variable
330
+		$migration_options_template_file = apply_filters(
331
+			'FHEE__ee_migration_page__migration_options_template',
332
+			EE_MAINTENANCE_TEMPLATE_PATH . 'migration_options_from_ee4.template.php'
333
+		);
334
+		$migration_options_html = EEH_Template::display_template($migration_options_template_file, $this->_template_args,true);
335
+		$this->_template_args['migration_options_html'] = $migration_options_html;
336
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
337
+			$this->_template_args, true);
338
+		$this->display_admin_page_with_sidebar();
339
+	}
340
+
341
+
342
+
343
+	/**
344
+	 * returns JSON and executes another step of the currently-executing data migration (called via ajax)
345
+	 */
346
+	public function migration_step()
347
+	{
348
+		$this->_template_args['data'] = EE_Data_Migration_Manager::instance()->response_to_migration_ajax_request();
349
+		$this->_return_json();
350
+	}
351
+
352
+
353
+
354
+	/**
355
+	 * Can be used by js when it notices a response with HTML in it in order
356
+	 * to log the malformed response
357
+	 */
358
+	public function add_error_to_migrations_ran()
359
+	{
360
+		EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($this->_req_data['message']);
361
+		$this->_template_args['data'] = array('ok' => true);
362
+		$this->_return_json();
363
+	}
364
+
365
+
366
+
367
+	/**
368
+	 * changes the maintenance level, provided there are still no migration scripts that should run
369
+	 */
370
+	public function _change_maintenance_level()
371
+	{
372
+		$new_level = absint($this->_req_data['maintenance_mode_level']);
373
+		if ( ! EE_Data_Migration_Manager::instance()->check_for_applicable_data_migration_scripts()) {
374
+			EE_Maintenance_Mode::instance()->set_maintenance_level($new_level);
375
+			$success = true;
376
+		} else {
377
+			EE_Maintenance_Mode::instance()->set_maintenance_mode_if_db_old();
378
+			$success = false;
379
+		}
380
+		$this->_redirect_after_action($success, 'Maintenance Mode', esc_html__("Updated", "event_espresso"));
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * a tab with options for resetting and/or deleting EE data
387
+	 *
388
+	 * @throws \EE_Error
389
+	 * @throws \DomainException
390
+	 */
391
+	public function _data_reset_and_delete()
392
+	{
393
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_data_reset_and_delete.template.php';
394
+		$this->_template_args['reset_reservations_button'] = $this->get_action_link_or_button(
395
+			'reset_reservations',
396
+			'reset_reservations',
397
+			array(),
398
+			'button button-primary ee-confirm',
399
+			'',
400
+			false
401
+		);
402
+		$this->_template_args['reset_capabilities_button'] = $this->get_action_link_or_button(
403
+			'reset_capabilities',
404
+			'reset_capabilities',
405
+			array(),
406
+			'button button-primary ee-confirm',
407
+			'',
408
+			false
409
+		);
410
+		$this->_template_args['delete_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
411
+			array('action' => 'delete_db'),
412
+			EE_MAINTENANCE_ADMIN_URL
413
+		);
414
+		$this->_template_args['reset_db_url'] = EE_Admin_Page::add_query_args_and_nonce(
415
+			array('action' => 'reset_db'),
416
+			EE_MAINTENANCE_ADMIN_URL
417
+		);
418
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
419
+			$this->_template_path,
420
+			$this->_template_args,
421
+			true
422
+		);
423
+		$this->display_admin_page_with_sidebar();
424
+	}
425
+
426
+
427
+
428
+	protected function _reset_reservations()
429
+	{
430
+		if(\EED_Ticket_Sales_Monitor::reset_reservation_counts()) {
431
+			EE_Error::add_success(
432
+				__(
433
+					'Ticket and datetime reserved counts have been successfully reset.',
434
+					'event_espresso'
435
+				)
436
+			);
437
+		} else {
438
+			EE_Error::add_success(
439
+				__(
440
+					'Ticket and datetime reserved counts were correct and did not need resetting.',
441
+					'event_espresso'
442
+				)
443
+			);
444
+		}
445
+		$this->_redirect_after_action(true, '', '', array('action' => 'data_reset'), true);
446
+	}
447
+
448
+
449
+
450
+	protected function _reset_capabilities()
451
+	{
452
+		EE_Registry::instance()->CAP->init_caps(true);
453
+		EE_Error::add_success(__('Default Event Espresso capabilities have been restored for all current roles.',
454
+			'event_espresso'));
455
+		$this->_redirect_after_action(false, '', '', array('action' => 'data_reset'), true);
456
+	}
457
+
458
+
459
+
460
+	/**
461
+	 * resets the DMSs so we can attempt to continue migrating after a fatal error
462
+	 * (only a good idea when someone has somehow tried ot fix whatever caused
463
+	 * the fatal error in teh first place)
464
+	 */
465
+	protected function _reattempt_migration()
466
+	{
467
+		EE_Data_Migration_Manager::instance()->reattempt();
468
+		$this->_redirect_after_action(false, '', '', array('action' => 'default'), true);
469
+	}
470
+
471
+
472
+
473
+	/**
474
+	 * shows the big ol' System Information page
475
+	 */
476
+	public function _system_status()
477
+	{
478
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_system_stati_page.template.php';
479
+		$this->_template_args['system_stati'] = EEM_System_Status::instance()->get_system_stati();
480
+		$this->_template_args['download_system_status_url'] = EE_Admin_Page::add_query_args_and_nonce(
481
+			array(
482
+				'action' => 'download_system_status',
483
+			),
484
+			EE_MAINTENANCE_ADMIN_URL
485
+		);
486
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
487
+			$this->_template_args, true);
488
+		$this->display_admin_page_with_sidebar();
489
+	}
490
+
491
+	/**
492
+	 * Downloads an HTML file of the system status that can be easily stored or emailed
493
+	 */
494
+	public function _download_system_status()
495
+	{
496
+		$status_info = EEM_System_Status::instance()->get_system_stati();
497
+		header( 'Content-Disposition: attachment' );
498
+		header( "Content-Disposition: attachment; filename=system_status_" . sanitize_key( site_url() ) . ".html" );
499
+		echo "<style>table{border:1px solid darkgrey;}td{vertical-align:top}</style>";
500
+		echo "<h1>System Information for " . site_url() . "</h1>";
501
+		echo EEH_Template::layout_array_as_table( $status_info );
502
+		die;
503
+	}
504
+
505
+
506
+
507
+	public function _send_migration_crash_report()
508
+	{
509
+		$from = $this->_req_data['from'];
510
+		$from_name = $this->_req_data['from_name'];
511
+		$body = $this->_req_data['body'];
512
+		try {
513
+			$success = wp_mail(EE_SUPPORT_EMAIL,
514
+				'Migration Crash Report',
515
+				$body . "/r/n<br>" . print_r(EEM_System_Status::instance()->get_system_stati(), true),
516
+				array(
517
+					"from:$from_name<$from>",
518
+					//					'content-type:text/html charset=UTF-8'
519
+				));
520
+		} catch (Exception $e) {
521
+			$success = false;
522
+		}
523
+		$this->_redirect_after_action($success, esc_html__("Migration Crash Report", "event_espresso"),
524
+			esc_html__("sent", "event_espresso"),
525
+			array('success' => $success, 'action' => 'confirm_migration_crash_report_sent'));
526
+	}
527
+
528
+
529
+
530
+	public function _confirm_migration_crash_report_sent()
531
+	{
532
+		try {
533
+			$most_recent_migration = EE_Data_Migration_Manager::instance()->get_last_ran_script(true);
534
+		} catch (EE_Error $e) {
535
+			EE_Data_Migration_Manager::instance()->add_error_to_migrations_ran($e->getMessage());
536
+			//now, just so we can display the page correctly, make a error migration script stage object
537
+			//and also put the error on it. It only persists for the duration of this request
538
+			$most_recent_migration = new EE_DMS_Unknown_1_0_0();
539
+			$most_recent_migration->add_error($e->getMessage());
540
+		}
541
+		$success = $this->_req_data['success'] == '1' ? true : false;
542
+		$this->_template_args['success'] = $success;
543
+		$this->_template_args['most_recent_migration'] = $most_recent_migration;
544
+		$this->_template_args['reset_db_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reset_db'),
545
+			EE_MAINTENANCE_ADMIN_URL);
546
+		$this->_template_args['reset_db_page_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'data_reset'),
547
+			EE_MAINTENANCE_ADMIN_URL);
548
+		$this->_template_args['reattempt_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reattempt_migration'),
549
+			EE_MAINTENANCE_ADMIN_URL);
550
+		$this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_confirm_migration_crash_report_sent.template.php';
551
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
552
+			$this->_template_args, true);
553
+		$this->display_admin_page_with_sidebar();
554
+	}
555
+
556
+
557
+
558
+	/**
559
+	 * Resets the entire EE4 database.
560
+	 * Currently basically only sets up ee4 database for a fresh install- doesn't
561
+	 * actually clean out the old wp options, or cpts (although does erase old ee table data)
562
+	 *
563
+	 * @param boolean $nuke_old_ee4_data controls whether or not we
564
+	 *                                   destroy the old ee4 data, or just try initializing ee4 default data
565
+	 */
566
+	public function _reset_db($nuke_old_ee4_data = true)
567
+	{
568
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
569
+		if ($nuke_old_ee4_data) {
570
+			EEH_Activation::delete_all_espresso_cpt_data();
571
+			EEH_Activation::delete_all_espresso_tables_and_data(false);
572
+			EEH_Activation::remove_cron_tasks();
573
+		}
574
+		//make sure when we reset the registry's config that it
575
+		//switches to using the new singleton
576
+		EE_Registry::instance()->CFG = EE_Registry::instance()->CFG->reset(true);
577
+		EE_System::instance()->initialize_db_if_no_migrations_required(true);
578
+		EE_System::instance()->redirect_to_about_ee();
579
+	}
580
+
581
+
582
+
583
+	/**
584
+	 * Deletes ALL EE tables, Records, and Options from the database.
585
+	 */
586
+	public function _delete_db()
587
+	{
588
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
589
+		EEH_Activation::delete_all_espresso_cpt_data();
590
+		EEH_Activation::delete_all_espresso_tables_and_data();
591
+		EEH_Activation::remove_cron_tasks();
592
+		EEH_Activation::deactivate_event_espresso();
593
+		wp_safe_redirect(admin_url('plugins.php'));
594
+		exit;
595
+	}
596
+
597
+
598
+
599
+	/**
600
+	 * sets up EE4 to rerun the migrations from ee3 to ee4
601
+	 */
602
+	public function _rerun_migration_from_ee3()
603
+	{
604
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_0_not_in_maintenance);
605
+		EEH_Activation::delete_all_espresso_cpt_data();
606
+		EEH_Activation::delete_all_espresso_tables_and_data(false);
607
+		//set the db state to something that will require migrations
608
+		update_option(EE_Data_Migration_Manager::current_database_state, '3.1.36.0');
609
+		EE_Maintenance_Mode::instance()->set_maintenance_level(EE_Maintenance_Mode::level_2_complete_maintenance);
610
+		$this->_redirect_after_action(true, esc_html__("Database", 'event_espresso'), esc_html__("reset", 'event_espresso'));
611
+	}
612
+
613
+
614
+
615
+	//none of the below group are currently used for Gateway Settings
616
+	protected function _add_screen_options()
617
+	{
618
+	}
619
+
620
+
621
+
622
+	protected function _add_feature_pointers()
623
+	{
624
+	}
625
+
626 626
 
627 627
 
628
-    public function admin_init()
629
-    {
630
-    }
631
-
632
-
633
-
634
-    public function admin_notices()
635
-    {
636
-    }
637
-
628
+	public function admin_init()
629
+	{
630
+	}
631
+
632
+
633
+
634
+	public function admin_notices()
635
+	{
636
+	}
637
+
638 638
 
639 639
 
640
-    public function admin_footer_scripts()
641
-    {
642
-    }
640
+	public function admin_footer_scripts()
641
+	{
642
+	}
643 643
 
644 644
 
645 645
 
646
-    public function load_scripts_styles()
647
-    {
648
-        wp_enqueue_script('ee_admin_js');
646
+	public function load_scripts_styles()
647
+	{
648
+		wp_enqueue_script('ee_admin_js');
649 649
 //		wp_enqueue_media();
650 650
 //		wp_enqueue_script('media-upload');
651
-        wp_enqueue_script('ee-maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.js', array('jquery'),
652
-            EVENT_ESPRESSO_VERSION, true);
653
-        wp_register_style('espresso_maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.css', array(),
654
-            EVENT_ESPRESSO_VERSION);
655
-        wp_enqueue_style('espresso_maintenance');
656
-        //localize script stuff
657
-        wp_localize_script('ee-maintenance', 'ee_maintenance', array(
658
-            'migrating'                        => esc_html__("Updating Database...", "event_espresso"),
659
-            'next'                             => esc_html__("Next", "event_espresso"),
660
-            'fatal_error'                      => esc_html__("A Fatal Error Has Occurred", "event_espresso"),
661
-            'click_next_when_ready'            => esc_html__(
662
-                "The current Database Update has ended. Click 'next' when ready to proceed",
663
-                "event_espresso"
664
-            ),
665
-            'status_no_more_migration_scripts' => EE_Data_Migration_Manager::status_no_more_migration_scripts,
666
-            'status_fatal_error'               => EE_Data_Migration_Manager::status_fatal_error,
667
-            'status_completed'                 => EE_Data_Migration_Manager::status_completed,
668
-            'confirm'                          => esc_html__(
669
-                'Are you sure you want to do this? It CANNOT be undone!',
670
-                'event_espresso'
671
-            ),
672
-            'confirm_skip_migration' => esc_html__(
673
-                'You have chosen to NOT migrate your existing data. Are you sure you want to continue?',
674
-                'event_espresso'
675
-            )
676
-        ));
677
-    }
678
-
679
-
680
-
681
-    public function load_scripts_styles_default()
682
-    {
683
-        //styles
651
+		wp_enqueue_script('ee-maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.js', array('jquery'),
652
+			EVENT_ESPRESSO_VERSION, true);
653
+		wp_register_style('espresso_maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.css', array(),
654
+			EVENT_ESPRESSO_VERSION);
655
+		wp_enqueue_style('espresso_maintenance');
656
+		//localize script stuff
657
+		wp_localize_script('ee-maintenance', 'ee_maintenance', array(
658
+			'migrating'                        => esc_html__("Updating Database...", "event_espresso"),
659
+			'next'                             => esc_html__("Next", "event_espresso"),
660
+			'fatal_error'                      => esc_html__("A Fatal Error Has Occurred", "event_espresso"),
661
+			'click_next_when_ready'            => esc_html__(
662
+				"The current Database Update has ended. Click 'next' when ready to proceed",
663
+				"event_espresso"
664
+			),
665
+			'status_no_more_migration_scripts' => EE_Data_Migration_Manager::status_no_more_migration_scripts,
666
+			'status_fatal_error'               => EE_Data_Migration_Manager::status_fatal_error,
667
+			'status_completed'                 => EE_Data_Migration_Manager::status_completed,
668
+			'confirm'                          => esc_html__(
669
+				'Are you sure you want to do this? It CANNOT be undone!',
670
+				'event_espresso'
671
+			),
672
+			'confirm_skip_migration' => esc_html__(
673
+				'You have chosen to NOT migrate your existing data. Are you sure you want to continue?',
674
+				'event_espresso'
675
+			)
676
+		));
677
+	}
678
+
679
+
680
+
681
+	public function load_scripts_styles_default()
682
+	{
683
+		//styles
684 684
 //		wp_enqueue_style('ee-text-links');
685 685
 //		//scripts
686 686
 //		wp_enqueue_script('ee-text-links');
687
-    }
688
-
689
-
690
-    protected function _datetime_tools()
691
-    {
692
-        $form_action = EE_Admin_Page::add_query_args_and_nonce(
693
-            array(
694
-                'action' => 'run_datetime_offset_fix',
695
-                'return_action' => $this->_req_action
696
-            ),
697
-            EE_MAINTENANCE_ADMIN_URL
698
-        );
699
-        $form = $this->_get_datetime_offset_fix_form();
700
-        $this->_admin_page_title = esc_html__('Datetime Utilities', 'event_espresso');
701
-        $this->_template_args['admin_page_content'] = $form->form_open($form_action, 'post')
702
-                                                      . $form->get_html_and_js()
703
-                                                      . $form->form_close();
704
-        $this->display_admin_page_with_no_sidebar();
705
-    }
706
-
707
-
708
-
709
-    protected function _get_datetime_offset_fix_form()
710
-    {
711
-        if (! $this->datetime_fix_offset_form instanceof EE_Form_Section_Proper) {
712
-            $this->datetime_fix_offset_form =  new EE_Form_Section_Proper(
713
-                array(
714
-                    'name' => 'datetime_offset_fix_option',
715
-                    'layout_strategy' => new EE_Admin_Two_Column_Layout(),
716
-                    'subsections' => array(
717
-                        'title' => new EE_Form_Section_HTML(
718
-                            EEH_HTML::h2(
719
-                                esc_html__('Datetime Offset Tool', 'event_espresso')
720
-                            )
721
-                        ),
722
-                        'explanation' => new EE_Form_Section_HTML(
723
-                            EEH_HTML::p(
724
-                                esc_html__(
725
-                                    'Use this tool to automatically apply the provided offset to all Event Espresso records in your database that involve dates and times.',
726
-                                    'event_espresso'
727
-                                )
728
-                            )
729
-                            . EEH_HTML::p(
730
-                                esc_html__(
731
-                                    'Note: If you enter 1.25, that will result in the offset of 1 hour 15 minutes being applied.  Decimals represent the fraction of hours, not minutes.',
732
-                                    'event_espresso'
733
-                                )
734
-                            )
735
-                        ),
736
-                        'offset_input' => new EE_Float_Input(
737
-                            array(
738
-                                'html_name' => 'offset_for_datetimes',
739
-                                'html_label_text' => esc_html__(
740
-                                    'Offset to apply (in hours):',
741
-                                    'event_espresso'
742
-                                ),
743
-                                'min_value' => '-12',
744
-                                'max_value' => '14',
745
-                                'step_value' => '.25',
746
-                                'default' => DatetimeOffsetFix::getOffset()
747
-                            )
748
-                        ),
749
-                        'submit' => new EE_Submit_Input(
750
-                            array(
751
-                                'html_label_text' => '',
752
-                                'default' => esc_html__('Apply Offset', 'event_espresso')
753
-                            )
754
-                        )
755
-                    )
756
-                )
757
-            );
758
-        }
759
-        return $this->datetime_fix_offset_form;
760
-    }
761
-
762
-
763
-    /**
764
-     * Callback for the run_datetime_offset_fix route.
765
-     * @throws EE_Error
766
-     */
767
-    protected function _apply_datetime_offset()
768
-    {
769
-        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
770
-            $form = $this->_get_datetime_offset_fix_form();
771
-            $form->receive_form_submission($this->_req_data);
772
-            if ($form->is_valid()) {
773
-                //save offset so batch processor can get it.
774
-                DatetimeOffsetFix::updateOffset($form->get_input_value('offset_input'));
775
-                //redirect to batch tool
776
-                wp_redirect(
777
-                    EE_Admin_Page::add_query_args_and_nonce(
778
-                        array(
779
-                            'page' => 'espresso_batch',
780
-                            'batch' => 'job',
781
-                            'label' => esc_html__('Applying Offset', 'event_espresso'),
782
-                            'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\DatetimeOffsetFix'),
783
-                            'return_url' => urlencode(home_url(add_query_arg(null, null))),
784
-                        ),
785
-                        admin_url()
786
-                    )
787
-                );
788
-                exit;
789
-            }
790
-        }
791
-    }
687
+	}
688
+
689
+
690
+	protected function _datetime_tools()
691
+	{
692
+		$form_action = EE_Admin_Page::add_query_args_and_nonce(
693
+			array(
694
+				'action' => 'run_datetime_offset_fix',
695
+				'return_action' => $this->_req_action
696
+			),
697
+			EE_MAINTENANCE_ADMIN_URL
698
+		);
699
+		$form = $this->_get_datetime_offset_fix_form();
700
+		$this->_admin_page_title = esc_html__('Datetime Utilities', 'event_espresso');
701
+		$this->_template_args['admin_page_content'] = $form->form_open($form_action, 'post')
702
+													  . $form->get_html_and_js()
703
+													  . $form->form_close();
704
+		$this->display_admin_page_with_no_sidebar();
705
+	}
706
+
707
+
708
+
709
+	protected function _get_datetime_offset_fix_form()
710
+	{
711
+		if (! $this->datetime_fix_offset_form instanceof EE_Form_Section_Proper) {
712
+			$this->datetime_fix_offset_form =  new EE_Form_Section_Proper(
713
+				array(
714
+					'name' => 'datetime_offset_fix_option',
715
+					'layout_strategy' => new EE_Admin_Two_Column_Layout(),
716
+					'subsections' => array(
717
+						'title' => new EE_Form_Section_HTML(
718
+							EEH_HTML::h2(
719
+								esc_html__('Datetime Offset Tool', 'event_espresso')
720
+							)
721
+						),
722
+						'explanation' => new EE_Form_Section_HTML(
723
+							EEH_HTML::p(
724
+								esc_html__(
725
+									'Use this tool to automatically apply the provided offset to all Event Espresso records in your database that involve dates and times.',
726
+									'event_espresso'
727
+								)
728
+							)
729
+							. EEH_HTML::p(
730
+								esc_html__(
731
+									'Note: If you enter 1.25, that will result in the offset of 1 hour 15 minutes being applied.  Decimals represent the fraction of hours, not minutes.',
732
+									'event_espresso'
733
+								)
734
+							)
735
+						),
736
+						'offset_input' => new EE_Float_Input(
737
+							array(
738
+								'html_name' => 'offset_for_datetimes',
739
+								'html_label_text' => esc_html__(
740
+									'Offset to apply (in hours):',
741
+									'event_espresso'
742
+								),
743
+								'min_value' => '-12',
744
+								'max_value' => '14',
745
+								'step_value' => '.25',
746
+								'default' => DatetimeOffsetFix::getOffset()
747
+							)
748
+						),
749
+						'submit' => new EE_Submit_Input(
750
+							array(
751
+								'html_label_text' => '',
752
+								'default' => esc_html__('Apply Offset', 'event_espresso')
753
+							)
754
+						)
755
+					)
756
+				)
757
+			);
758
+		}
759
+		return $this->datetime_fix_offset_form;
760
+	}
761
+
762
+
763
+	/**
764
+	 * Callback for the run_datetime_offset_fix route.
765
+	 * @throws EE_Error
766
+	 */
767
+	protected function _apply_datetime_offset()
768
+	{
769
+		if ($_SERVER['REQUEST_METHOD'] === 'POST') {
770
+			$form = $this->_get_datetime_offset_fix_form();
771
+			$form->receive_form_submission($this->_req_data);
772
+			if ($form->is_valid()) {
773
+				//save offset so batch processor can get it.
774
+				DatetimeOffsetFix::updateOffset($form->get_input_value('offset_input'));
775
+				//redirect to batch tool
776
+				wp_redirect(
777
+					EE_Admin_Page::add_query_args_and_nonce(
778
+						array(
779
+							'page' => 'espresso_batch',
780
+							'batch' => 'job',
781
+							'label' => esc_html__('Applying Offset', 'event_espresso'),
782
+							'job_handler' => urlencode('EventEspressoBatchRequest\JobHandlers\DatetimeOffsetFix'),
783
+							'return_url' => urlencode(home_url(add_query_arg(null, null))),
784
+						),
785
+						admin_url()
786
+					)
787
+				);
788
+				exit;
789
+			}
790
+		}
791
+	}
792 792
 } //end Maintenance_Admin_Page class
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -261,13 +261,13 @@  discard block
 block discarded – undo
261 261
                 && $most_recent_migration->is_broken()
262 262
             )
263 263
         ) {
264
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_was_borked_page.template.php';
264
+            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_migration_was_borked_page.template.php';
265 265
             $this->_template_args['support_url'] = 'http://eventespresso.com/support/forums/';
266 266
             $this->_template_args['next_url'] = EEH_URL::add_query_args_and_nonce(array('action'  => 'confirm_migration_crash_report_sent',
267 267
                                                                                         'success' => '0',
268 268
             ), EE_MAINTENANCE_ADMIN_URL);
269 269
         } elseif ($addons_should_be_upgraded_first) {
270
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_upgrade_addons_before_migrating.template.php';
270
+            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_upgrade_addons_before_migrating.template.php';
271 271
         } else {
272 272
             if ($most_recent_migration
273 273
                 && $most_recent_migration instanceof EE_Data_Migration_Script_Base
@@ -297,7 +297,7 @@  discard block
 block discarded – undo
297 297
                 $this->_template_args['current_db_state'] = null;
298 298
                 $this->_template_args['next_db_state'] = null;
299 299
             }
300
-            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_migration_page.template.php';
300
+            $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_migration_page.template.php';
301 301
             $this->_template_args = array_merge(
302 302
                 $this->_template_args,
303 303
                 array(
@@ -325,13 +325,13 @@  discard block
 block discarded – undo
325 325
             );
326 326
             //make sure we have the form fields helper available. It usually is, but sometimes it isn't
327 327
         }
328
-        $this->_template_args['most_recent_migration'] = $most_recent_migration;//the actual most recently ran migration
328
+        $this->_template_args['most_recent_migration'] = $most_recent_migration; //the actual most recently ran migration
329 329
         //now render the migration options part, and put it in a variable
330 330
         $migration_options_template_file = apply_filters(
331 331
             'FHEE__ee_migration_page__migration_options_template',
332
-            EE_MAINTENANCE_TEMPLATE_PATH . 'migration_options_from_ee4.template.php'
332
+            EE_MAINTENANCE_TEMPLATE_PATH.'migration_options_from_ee4.template.php'
333 333
         );
334
-        $migration_options_html = EEH_Template::display_template($migration_options_template_file, $this->_template_args,true);
334
+        $migration_options_html = EEH_Template::display_template($migration_options_template_file, $this->_template_args, true);
335 335
         $this->_template_args['migration_options_html'] = $migration_options_html;
336 336
         $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
337 337
             $this->_template_args, true);
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
      */
391 391
     public function _data_reset_and_delete()
392 392
     {
393
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_data_reset_and_delete.template.php';
393
+        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_data_reset_and_delete.template.php';
394 394
         $this->_template_args['reset_reservations_button'] = $this->get_action_link_or_button(
395 395
             'reset_reservations',
396 396
             'reset_reservations',
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 
428 428
     protected function _reset_reservations()
429 429
     {
430
-        if(\EED_Ticket_Sales_Monitor::reset_reservation_counts()) {
430
+        if (\EED_Ticket_Sales_Monitor::reset_reservation_counts()) {
431 431
             EE_Error::add_success(
432 432
                 __(
433 433
                     'Ticket and datetime reserved counts have been successfully reset.',
@@ -475,7 +475,7 @@  discard block
 block discarded – undo
475 475
      */
476 476
     public function _system_status()
477 477
     {
478
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_system_stati_page.template.php';
478
+        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_system_stati_page.template.php';
479 479
         $this->_template_args['system_stati'] = EEM_System_Status::instance()->get_system_stati();
480 480
         $this->_template_args['download_system_status_url'] = EE_Admin_Page::add_query_args_and_nonce(
481 481
             array(
@@ -494,11 +494,11 @@  discard block
 block discarded – undo
494 494
     public function _download_system_status()
495 495
     {
496 496
         $status_info = EEM_System_Status::instance()->get_system_stati();
497
-        header( 'Content-Disposition: attachment' );
498
-        header( "Content-Disposition: attachment; filename=system_status_" . sanitize_key( site_url() ) . ".html" );
497
+        header('Content-Disposition: attachment');
498
+        header("Content-Disposition: attachment; filename=system_status_".sanitize_key(site_url()).".html");
499 499
         echo "<style>table{border:1px solid darkgrey;}td{vertical-align:top}</style>";
500
-        echo "<h1>System Information for " . site_url() . "</h1>";
501
-        echo EEH_Template::layout_array_as_table( $status_info );
500
+        echo "<h1>System Information for ".site_url()."</h1>";
501
+        echo EEH_Template::layout_array_as_table($status_info);
502 502
         die;
503 503
     }
504 504
 
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
         try {
513 513
             $success = wp_mail(EE_SUPPORT_EMAIL,
514 514
                 'Migration Crash Report',
515
-                $body . "/r/n<br>" . print_r(EEM_System_Status::instance()->get_system_stati(), true),
515
+                $body."/r/n<br>".print_r(EEM_System_Status::instance()->get_system_stati(), true),
516 516
                 array(
517 517
                     "from:$from_name<$from>",
518 518
                     //					'content-type:text/html charset=UTF-8'
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
             EE_MAINTENANCE_ADMIN_URL);
548 548
         $this->_template_args['reattempt_action_url'] = EE_Admin_Page::add_query_args_and_nonce(array('action' => 'reattempt_migration'),
549 549
             EE_MAINTENANCE_ADMIN_URL);
550
-        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH . 'ee_confirm_migration_crash_report_sent.template.php';
550
+        $this->_template_path = EE_MAINTENANCE_TEMPLATE_PATH.'ee_confirm_migration_crash_report_sent.template.php';
551 551
         $this->_template_args['admin_page_content'] = EEH_Template::display_template($this->_template_path,
552 552
             $this->_template_args, true);
553 553
         $this->display_admin_page_with_sidebar();
@@ -648,9 +648,9 @@  discard block
 block discarded – undo
648 648
         wp_enqueue_script('ee_admin_js');
649 649
 //		wp_enqueue_media();
650 650
 //		wp_enqueue_script('media-upload');
651
-        wp_enqueue_script('ee-maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.js', array('jquery'),
651
+        wp_enqueue_script('ee-maintenance', EE_MAINTENANCE_ASSETS_URL.'ee-maintenance.js', array('jquery'),
652 652
             EVENT_ESPRESSO_VERSION, true);
653
-        wp_register_style('espresso_maintenance', EE_MAINTENANCE_ASSETS_URL . 'ee-maintenance.css', array(),
653
+        wp_register_style('espresso_maintenance', EE_MAINTENANCE_ASSETS_URL.'ee-maintenance.css', array(),
654 654
             EVENT_ESPRESSO_VERSION);
655 655
         wp_enqueue_style('espresso_maintenance');
656 656
         //localize script stuff
@@ -708,8 +708,8 @@  discard block
 block discarded – undo
708 708
 
709 709
     protected function _get_datetime_offset_fix_form()
710 710
     {
711
-        if (! $this->datetime_fix_offset_form instanceof EE_Form_Section_Proper) {
712
-            $this->datetime_fix_offset_form =  new EE_Form_Section_Proper(
711
+        if ( ! $this->datetime_fix_offset_form instanceof EE_Form_Section_Proper) {
712
+            $this->datetime_fix_offset_form = new EE_Form_Section_Proper(
713 713
                 array(
714 714
                     'name' => 'datetime_offset_fix_option',
715 715
                     'layout_strategy' => new EE_Admin_Two_Column_Layout(),
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -38,217 +38,217 @@
 block discarded – undo
38 38
  * @since       4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 
64 64
 } else {
65
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
-        /**
68
-         * espresso_minimum_php_version_error
69
-         *
70
-         * @return void
71
-         */
72
-        function espresso_minimum_php_version_error()
73
-        {
74
-            ?>
65
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
66
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
67
+		/**
68
+		 * espresso_minimum_php_version_error
69
+		 *
70
+		 * @return void
71
+		 */
72
+		function espresso_minimum_php_version_error()
73
+		{
74
+			?>
75 75
             <div class="error">
76 76
                 <p>
77 77
                     <?php
78
-                    printf(
79
-                        esc_html__(
80
-                            '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.',
81
-                            'event_espresso'
82
-                        ),
83
-                        EE_MIN_PHP_VER_REQUIRED,
84
-                        PHP_VERSION,
85
-                        '<br/>',
86
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
87
-                    );
88
-                    ?>
78
+					printf(
79
+						esc_html__(
80
+							'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.',
81
+							'event_espresso'
82
+						),
83
+						EE_MIN_PHP_VER_REQUIRED,
84
+						PHP_VERSION,
85
+						'<br/>',
86
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
87
+					);
88
+					?>
89 89
                 </p>
90 90
             </div>
91 91
             <?php
92
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
93
-        }
92
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
93
+		}
94 94
 
95
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
96
-    } else {
97
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
98
-        /**
99
-         * espresso_version
100
-         * Returns the plugin version
101
-         *
102
-         * @return string
103
-         */
104
-        function espresso_version()
105
-        {
106
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.50.rc.006');
107
-        }
95
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
96
+	} else {
97
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
98
+		/**
99
+		 * espresso_version
100
+		 * Returns the plugin version
101
+		 *
102
+		 * @return string
103
+		 */
104
+		function espresso_version()
105
+		{
106
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.50.rc.006');
107
+		}
108 108
 
109
-        /**
110
-         * espresso_plugin_activation
111
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
112
-         */
113
-        function espresso_plugin_activation()
114
-        {
115
-            update_option('ee_espresso_activation', true);
116
-        }
109
+		/**
110
+		 * espresso_plugin_activation
111
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
112
+		 */
113
+		function espresso_plugin_activation()
114
+		{
115
+			update_option('ee_espresso_activation', true);
116
+		}
117 117
 
118
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
119
-        /**
120
-         *    espresso_load_error_handling
121
-         *    this function loads EE's class for handling exceptions and errors
122
-         */
123
-        function espresso_load_error_handling()
124
-        {
125
-            static $error_handling_loaded = false;
126
-            if ($error_handling_loaded) {
127
-                return;
128
-            }
129
-            // load debugging tools
130
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
131
-                require_once   EE_HELPERS . 'EEH_Debug_Tools.helper.php';
132
-                \EEH_Debug_Tools::instance();
133
-            }
134
-            // load error handling
135
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
136
-                require_once EE_CORE . 'EE_Error.core.php';
137
-            } else {
138
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
139
-            }
140
-            $error_handling_loaded = true;
141
-        }
118
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
119
+		/**
120
+		 *    espresso_load_error_handling
121
+		 *    this function loads EE's class for handling exceptions and errors
122
+		 */
123
+		function espresso_load_error_handling()
124
+		{
125
+			static $error_handling_loaded = false;
126
+			if ($error_handling_loaded) {
127
+				return;
128
+			}
129
+			// load debugging tools
130
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
131
+				require_once   EE_HELPERS . 'EEH_Debug_Tools.helper.php';
132
+				\EEH_Debug_Tools::instance();
133
+			}
134
+			// load error handling
135
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
136
+				require_once EE_CORE . 'EE_Error.core.php';
137
+			} else {
138
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
139
+			}
140
+			$error_handling_loaded = true;
141
+		}
142 142
 
143
-        /**
144
-         *    espresso_load_required
145
-         *    given a class name and path, this function will load that file or throw an exception
146
-         *
147
-         * @param    string $classname
148
-         * @param    string $full_path_to_file
149
-         * @throws    EE_Error
150
-         */
151
-        function espresso_load_required($classname, $full_path_to_file)
152
-        {
153
-            if (is_readable($full_path_to_file)) {
154
-                require_once $full_path_to_file;
155
-            } else {
156
-                throw new \EE_Error (
157
-                    sprintf(
158
-                        esc_html__(
159
-                            'The %s class file could not be located or is not readable due to file permissions.',
160
-                            'event_espresso'
161
-                        ),
162
-                        $classname
163
-                    )
164
-                );
165
-            }
166
-        }
143
+		/**
144
+		 *    espresso_load_required
145
+		 *    given a class name and path, this function will load that file or throw an exception
146
+		 *
147
+		 * @param    string $classname
148
+		 * @param    string $full_path_to_file
149
+		 * @throws    EE_Error
150
+		 */
151
+		function espresso_load_required($classname, $full_path_to_file)
152
+		{
153
+			if (is_readable($full_path_to_file)) {
154
+				require_once $full_path_to_file;
155
+			} else {
156
+				throw new \EE_Error (
157
+					sprintf(
158
+						esc_html__(
159
+							'The %s class file could not be located or is not readable due to file permissions.',
160
+							'event_espresso'
161
+						),
162
+						$classname
163
+					)
164
+				);
165
+			}
166
+		}
167 167
 
168
-        /**
169
-         * @since 4.9.27
170
-         * @throws \EE_Error
171
-         * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
172
-         * @throws \EventEspresso\core\exceptions\InvalidEntityException
173
-         * @throws \EventEspresso\core\exceptions\InvalidIdentifierException
174
-         * @throws \EventEspresso\core\exceptions\InvalidClassException
175
-         * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
176
-         * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException
177
-         * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException
178
-         * @throws \OutOfBoundsException
179
-         */
180
-        function bootstrap_espresso()
181
-        {
182
-            require_once __DIR__ . '/core/espresso_definitions.php';
183
-            try {
184
-                espresso_load_error_handling();
185
-                espresso_load_required(
186
-                    'EEH_Base',
187
-                    EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
188
-                );
189
-                espresso_load_required(
190
-                    'EEH_File',
191
-                    EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
192
-                );
193
-                espresso_load_required(
194
-                    'EEH_File',
195
-                    EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
196
-                );
197
-                espresso_load_required(
198
-                    'EEH_Array',
199
-                    EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
200
-                );
201
-                // instantiate and configure PSR4 autoloader
202
-                espresso_load_required(
203
-                    'Psr4Autoloader',
204
-                    EE_CORE . 'Psr4Autoloader.php'
205
-                );
206
-                espresso_load_required(
207
-                    'EE_Psr4AutoloaderInit',
208
-                    EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
209
-                );
210
-                $AutoloaderInit = new EE_Psr4AutoloaderInit();
211
-                $AutoloaderInit->initializeAutoloader();
212
-                espresso_load_required(
213
-                    'EE_Request',
214
-                    EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
215
-                );
216
-                espresso_load_required(
217
-                    'EE_Response',
218
-                    EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
219
-                );
220
-                espresso_load_required(
221
-                    'EE_Bootstrap',
222
-                    EE_CORE . 'EE_Bootstrap.core.php'
223
-                );
224
-                // bootstrap EE and the request stack
225
-                new EE_Bootstrap(
226
-                    new EE_Request($_GET, $_POST, $_COOKIE),
227
-                    new EE_Response()
228
-                );
229
-            } catch (Exception $e) {
230
-                require_once EE_CORE . 'exceptions' . DS . 'ExceptionStackTraceDisplay.php';
231
-                new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
232
-            }
233
-        }
234
-        bootstrap_espresso();
235
-    }
168
+		/**
169
+		 * @since 4.9.27
170
+		 * @throws \EE_Error
171
+		 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
172
+		 * @throws \EventEspresso\core\exceptions\InvalidEntityException
173
+		 * @throws \EventEspresso\core\exceptions\InvalidIdentifierException
174
+		 * @throws \EventEspresso\core\exceptions\InvalidClassException
175
+		 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
176
+		 * @throws \EventEspresso\core\services\container\exceptions\ServiceExistsException
177
+		 * @throws \EventEspresso\core\services\container\exceptions\ServiceNotFoundException
178
+		 * @throws \OutOfBoundsException
179
+		 */
180
+		function bootstrap_espresso()
181
+		{
182
+			require_once __DIR__ . '/core/espresso_definitions.php';
183
+			try {
184
+				espresso_load_error_handling();
185
+				espresso_load_required(
186
+					'EEH_Base',
187
+					EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php'
188
+				);
189
+				espresso_load_required(
190
+					'EEH_File',
191
+					EE_CORE . 'interfaces' . DS . 'EEHI_File.interface.php'
192
+				);
193
+				espresso_load_required(
194
+					'EEH_File',
195
+					EE_CORE . 'helpers' . DS . 'EEH_File.helper.php'
196
+				);
197
+				espresso_load_required(
198
+					'EEH_Array',
199
+					EE_CORE . 'helpers' . DS . 'EEH_Array.helper.php'
200
+				);
201
+				// instantiate and configure PSR4 autoloader
202
+				espresso_load_required(
203
+					'Psr4Autoloader',
204
+					EE_CORE . 'Psr4Autoloader.php'
205
+				);
206
+				espresso_load_required(
207
+					'EE_Psr4AutoloaderInit',
208
+					EE_CORE . 'EE_Psr4AutoloaderInit.core.php'
209
+				);
210
+				$AutoloaderInit = new EE_Psr4AutoloaderInit();
211
+				$AutoloaderInit->initializeAutoloader();
212
+				espresso_load_required(
213
+					'EE_Request',
214
+					EE_CORE . 'request_stack' . DS . 'EE_Request.core.php'
215
+				);
216
+				espresso_load_required(
217
+					'EE_Response',
218
+					EE_CORE . 'request_stack' . DS . 'EE_Response.core.php'
219
+				);
220
+				espresso_load_required(
221
+					'EE_Bootstrap',
222
+					EE_CORE . 'EE_Bootstrap.core.php'
223
+				);
224
+				// bootstrap EE and the request stack
225
+				new EE_Bootstrap(
226
+					new EE_Request($_GET, $_POST, $_COOKIE),
227
+					new EE_Response()
228
+				);
229
+			} catch (Exception $e) {
230
+				require_once EE_CORE . 'exceptions' . DS . 'ExceptionStackTraceDisplay.php';
231
+				new EventEspresso\core\exceptions\ExceptionStackTraceDisplay($e);
232
+			}
233
+		}
234
+		bootstrap_espresso();
235
+	}
236 236
 }
237 237
 if (! function_exists('espresso_deactivate_plugin')) {
238
-    /**
239
-     *    deactivate_plugin
240
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
241
-     *
242
-     * @access public
243
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
244
-     * @return    void
245
-     */
246
-    function espresso_deactivate_plugin($plugin_basename = '')
247
-    {
248
-        if (! function_exists('deactivate_plugins')) {
249
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
250
-        }
251
-        unset($_GET['activate'], $_REQUEST['activate']);
252
-        deactivate_plugins($plugin_basename);
253
-    }
238
+	/**
239
+	 *    deactivate_plugin
240
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
241
+	 *
242
+	 * @access public
243
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
244
+	 * @return    void
245
+	 */
246
+	function espresso_deactivate_plugin($plugin_basename = '')
247
+	{
248
+		if (! function_exists('deactivate_plugins')) {
249
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
250
+		}
251
+		unset($_GET['activate'], $_REQUEST['activate']);
252
+		deactivate_plugins($plugin_basename);
253
+	}
254 254
 }
Please login to merge, or discard this patch.
core/services/notifications/PersistentAdminNoticeManager.php 1 patch
Indentation   +353 added lines, -353 removed lines patch added patch discarded remove patch
@@ -30,359 +30,359 @@
 block discarded – undo
30 30
 class PersistentAdminNoticeManager
31 31
 {
32 32
 
33
-    const WP_OPTION_KEY = 'ee_pers_admin_notices';
34
-
35
-    /**
36
-     * @var Collection|PersistentAdminNotice[] $notice_collection
37
-     */
38
-    private $notice_collection;
39
-
40
-    /**
41
-     * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
42
-     * persistent admin notice was displayed, and ultimately dismissed from.
43
-     *
44
-     * @type string $return_url
45
-     */
46
-    private $return_url;
47
-
48
-    /**
49
-     * @type CapabilitiesChecker $capabilities_checker
50
-     */
51
-    private $capabilities_checker;
52
-
53
-    /**
54
-     * @type EE_Request $request
55
-     */
56
-    private $request;
57
-
58
-
59
-
60
-    /**
61
-     * CapChecker constructor
62
-     *
63
-     * @param string              $return_url  where to  redirect to after dismissing notices
64
-     * @param CapabilitiesChecker $capabilities_checker
65
-     * @param EE_Request          $request
66
-     * @throws InvalidDataTypeException
67
-     */
68
-    public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, EE_Request $request)
69
-    {
70
-        $this->setReturnUrl($return_url);
71
-        $this->capabilities_checker = $capabilities_checker;
72
-        $this->request              = $request;
73
-        // setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
74
-        // and we want to retrieve and generate any nag notices at the last possible moment
75
-        add_action('admin_notices', array($this, 'displayNotices'), 9);
76
-        add_action('network_admin_notices', array($this, 'displayNotices'), 9);
77
-        add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
78
-        add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
79
-    }
80
-
81
-
82
-
83
-    /**
84
-     * @param string $return_url
85
-     * @throws InvalidDataTypeException
86
-     */
87
-    private function setReturnUrl($return_url)
88
-    {
89
-        if (! is_string($return_url)) {
90
-            throw new InvalidDataTypeException('$return_url', $return_url, 'string');
91
-        }
92
-        $this->return_url = $return_url;
93
-    }
94
-
95
-
96
-
97
-    /**
98
-     * @return Collection
99
-     * @throws InvalidEntityException
100
-     * @throws InvalidInterfaceException
101
-     * @throws InvalidDataTypeException
102
-     * @throws DomainException
103
-     */
104
-    protected function getPersistentAdminNoticeCollection()
105
-    {
106
-        if (! $this->notice_collection instanceof Collection) {
107
-            $this->notice_collection = new Collection(
108
-                'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
109
-            );
110
-            $this->retrieveStoredNotices();
111
-            $this->registerNotices();
112
-        }
113
-        return $this->notice_collection;
114
-    }
115
-
116
-
117
-
118
-    /**
119
-     * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
120
-     *
121
-     * @return void
122
-     * @throws InvalidEntityException
123
-     * @throws DomainException
124
-     * @throws InvalidDataTypeException
125
-     */
126
-    protected function retrieveStoredNotices()
127
-    {
128
-        $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
129
-        // \EEH_Debug_Tools::printr($persistent_admin_notices, '$persistent_admin_notices', __FILE__, __LINE__);
130
-        if (! empty($persistent_admin_notices)) {
131
-            foreach ($persistent_admin_notices as $name => $details) {
132
-                if (is_array($details)) {
133
-                    if (
134
-                        ! isset(
135
-                            $details['message'],
136
-                            $details['capability'],
137
-                            $details['cap_context'],
138
-                            $details['dismissed']
139
-                        )
140
-                    ) {
141
-                        throw new DomainException(
142
-                            sprintf(
143
-                                esc_html__(
144
-                                    'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
145
-                                    'event_espresso'
146
-                                ),
147
-                                $name
148
-                            )
149
-                        );
150
-                    }
151
-                    // new format for nag notices
152
-                    $this->notice_collection->add(
153
-                        new PersistentAdminNotice(
154
-                            $name,
155
-                            $details['message'],
156
-                            false,
157
-                            $details['capability'],
158
-                            $details['cap_context'],
159
-                            $details['dismissed']
160
-                        ),
161
-                        $name
162
-                    );
163
-                } else {
164
-                    try {
165
-                        // old nag notices, that we want to convert to the new format
166
-                        $this->notice_collection->add(
167
-                            new PersistentAdminNotice(
168
-                                $name,
169
-                                (string)$details,
170
-                                false,
171
-                                '',
172
-                                '',
173
-                                empty($details)
174
-                            ),
175
-                            $name
176
-                        );
177
-                    } catch (Exception $e) {
178
-                        EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
179
-                    }
180
-                }
181
-                // each notice will self register when the action hook in registerNotices is triggered
182
-            }
183
-        }
184
-    }
185
-
186
-
187
-
188
-    /**
189
-     * exposes the Persistent Admin Notice Collection via an action
190
-     * so that PersistentAdminNotice objects can be added and/or removed
191
-     * without compromising the actual collection like a filter would
192
-     */
193
-    protected function registerNotices()
194
-    {
195
-        do_action(
196
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
197
-            $this->notice_collection
198
-        );
199
-    }
200
-
201
-
202
-
203
-    /**
204
-     * @throws DomainException
205
-     * @throws InvalidClassException
206
-     * @throws InvalidDataTypeException
207
-     * @throws InvalidInterfaceException
208
-     * @throws InvalidEntityException
209
-     */
210
-    public function displayNotices()
211
-    {
212
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
213
-        if ($this->notice_collection->hasObjects()) {
214
-            // and display notices
215
-            foreach ($this->notice_collection as $persistent_admin_notice) {
216
-                /** @var PersistentAdminNotice $persistent_admin_notice */
217
-                // don't display notices that have already been dismissed
218
-                if ($persistent_admin_notice->getDismissed()) {
219
-                    continue;
220
-                }
221
-                try {
222
-                    $this->capabilities_checker->processCapCheck(
223
-                        $persistent_admin_notice->getCapCheck()
224
-                    );
225
-                } catch (InsufficientPermissionsException $e) {
226
-                    // user does not have required cap, so skip to next notice
227
-                    // and just eat the exception - nom nom nom nom
228
-                    continue;
229
-                }
230
-                $this->displayPersistentAdminNotice($persistent_admin_notice);
231
-            }
232
-            $this->enqueueAssets();
233
-        }
234
-    }
235
-
236
-
237
-
238
-    /**
239
-     * does what it's named
240
-     *
241
-     * @return void
242
-     */
243
-    public function enqueueAssets()
244
-    {
245
-        wp_register_script(
246
-            'espresso_core',
247
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
248
-            array('jquery'),
249
-            EVENT_ESPRESSO_VERSION,
250
-            true
251
-        );
252
-        wp_register_script(
253
-            'ee_error_js',
254
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
255
-            array('espresso_core'),
256
-            EVENT_ESPRESSO_VERSION,
257
-            true
258
-        );
259
-        wp_localize_script(
260
-            'ee_error_js',
261
-            'ee_dismiss',
262
-            array(
263
-                'return_url'    => urlencode($this->return_url),
264
-                'ajax_url'      => WP_AJAX_URL,
265
-                'unknown_error' => esc_html__(
266
-                    'An unknown error has occurred on the server while attempting to dismiss this notice.',
267
-                    'event_espresso'
268
-                ),
269
-            )
270
-        );
271
-        wp_enqueue_script('ee_error_js');
272
-    }
273
-
274
-
275
-
276
-    /**
277
-     * displayPersistentAdminNoticeHtml
278
-     *
279
-     * @param  PersistentAdminNotice $persistent_admin_notice
280
-     */
281
-    protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
282
-    {
283
-        // used in template
284
-        $persistent_admin_notice_name    = $persistent_admin_notice->getName();
285
-        $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
286
-        require EE_TEMPLATES . DS . 'notifications' . DS . 'persistent_admin_notice.template.php';
287
-    }
288
-
289
-
290
-
291
-    /**
292
-     * dismissNotice
293
-     *
294
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
295
-     * @param bool   $purge    if true, then delete it from the db
296
-     * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
297
-     * @return void
298
-     * @throws InvalidEntityException
299
-     * @throws InvalidInterfaceException
300
-     * @throws InvalidDataTypeException
301
-     * @throws DomainException
302
-     */
303
-    public function dismissNotice($pan_name = '', $purge = false, $return = false)
304
-    {
305
-        $pan_name                = $this->request->get('ee_nag_notice', $pan_name);
306
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
307
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
308
-            /** @var PersistentAdminNotice $persistent_admin_notice */
309
-            $persistent_admin_notice = $this->notice_collection->get($pan_name);
310
-            $persistent_admin_notice->setDismissed(true);
311
-            $persistent_admin_notice->setPurge($purge);
312
-            $this->saveNotices();
313
-        }
314
-        if ($return) {
315
-            return;
316
-        }
317
-        if ($this->request->ajax) {
318
-            // grab any notices and concatenate into string
319
-            echo wp_json_encode(
320
-                array(
321
-                    'errors' => implode('<br />', EE_Error::get_notices(false)),
322
-                )
323
-            );
324
-            exit();
325
-        }
326
-        // save errors to a transient to be displayed on next request (after redirect)
327
-        EE_Error::get_notices(false, true);
328
-        wp_safe_redirect(
329
-            urldecode(
330
-                $this->request->get('return_url', '')
331
-            )
332
-        );
333
-    }
334
-
335
-
336
-
337
-    /**
338
-     * saveNotices
339
-     *
340
-     * @throws DomainException
341
-     * @throws InvalidDataTypeException
342
-     * @throws InvalidInterfaceException
343
-     * @throws InvalidEntityException
344
-     */
345
-    public function saveNotices()
346
-    {
347
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
348
-        if ($this->notice_collection->hasObjects()) {
349
-            $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
350
-            //maybe initialize persistent_admin_notices
351
-            if (empty($persistent_admin_notices)) {
352
-                add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
353
-            }
354
-            foreach ($this->notice_collection as $persistent_admin_notice) {
355
-                // are we deleting this notice ?
356
-                if ($persistent_admin_notice->getPurge()) {
357
-                    unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
358
-                } else {
359
-                    /** @var PersistentAdminNotice $persistent_admin_notice */
360
-                    $persistent_admin_notices[$persistent_admin_notice->getName()] = array(
361
-                        'message'     => $persistent_admin_notice->getMessage(),
362
-                        'capability'  => $persistent_admin_notice->getCapability(),
363
-                        'cap_context' => $persistent_admin_notice->getCapContext(),
364
-                        'dismissed'   => $persistent_admin_notice->getDismissed(),
365
-                    );
366
-                }
367
-            }
368
-            update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
369
-        }
370
-    }
371
-
372
-
373
-
374
-    /**
375
-     * @throws DomainException
376
-     * @throws InvalidDataTypeException
377
-     * @throws InvalidEntityException
378
-     * @throws InvalidInterfaceException
379
-     */
380
-    public function registerAndSaveNotices()
381
-    {
382
-        $this->getPersistentAdminNoticeCollection();
383
-        $this->registerNotices();
384
-        $this->saveNotices();
385
-    }
33
+	const WP_OPTION_KEY = 'ee_pers_admin_notices';
34
+
35
+	/**
36
+	 * @var Collection|PersistentAdminNotice[] $notice_collection
37
+	 */
38
+	private $notice_collection;
39
+
40
+	/**
41
+	 * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
42
+	 * persistent admin notice was displayed, and ultimately dismissed from.
43
+	 *
44
+	 * @type string $return_url
45
+	 */
46
+	private $return_url;
47
+
48
+	/**
49
+	 * @type CapabilitiesChecker $capabilities_checker
50
+	 */
51
+	private $capabilities_checker;
52
+
53
+	/**
54
+	 * @type EE_Request $request
55
+	 */
56
+	private $request;
57
+
58
+
59
+
60
+	/**
61
+	 * CapChecker constructor
62
+	 *
63
+	 * @param string              $return_url  where to  redirect to after dismissing notices
64
+	 * @param CapabilitiesChecker $capabilities_checker
65
+	 * @param EE_Request          $request
66
+	 * @throws InvalidDataTypeException
67
+	 */
68
+	public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, EE_Request $request)
69
+	{
70
+		$this->setReturnUrl($return_url);
71
+		$this->capabilities_checker = $capabilities_checker;
72
+		$this->request              = $request;
73
+		// setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
74
+		// and we want to retrieve and generate any nag notices at the last possible moment
75
+		add_action('admin_notices', array($this, 'displayNotices'), 9);
76
+		add_action('network_admin_notices', array($this, 'displayNotices'), 9);
77
+		add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
78
+		add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
79
+	}
80
+
81
+
82
+
83
+	/**
84
+	 * @param string $return_url
85
+	 * @throws InvalidDataTypeException
86
+	 */
87
+	private function setReturnUrl($return_url)
88
+	{
89
+		if (! is_string($return_url)) {
90
+			throw new InvalidDataTypeException('$return_url', $return_url, 'string');
91
+		}
92
+		$this->return_url = $return_url;
93
+	}
94
+
95
+
96
+
97
+	/**
98
+	 * @return Collection
99
+	 * @throws InvalidEntityException
100
+	 * @throws InvalidInterfaceException
101
+	 * @throws InvalidDataTypeException
102
+	 * @throws DomainException
103
+	 */
104
+	protected function getPersistentAdminNoticeCollection()
105
+	{
106
+		if (! $this->notice_collection instanceof Collection) {
107
+			$this->notice_collection = new Collection(
108
+				'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
109
+			);
110
+			$this->retrieveStoredNotices();
111
+			$this->registerNotices();
112
+		}
113
+		return $this->notice_collection;
114
+	}
115
+
116
+
117
+
118
+	/**
119
+	 * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
120
+	 *
121
+	 * @return void
122
+	 * @throws InvalidEntityException
123
+	 * @throws DomainException
124
+	 * @throws InvalidDataTypeException
125
+	 */
126
+	protected function retrieveStoredNotices()
127
+	{
128
+		$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
129
+		// \EEH_Debug_Tools::printr($persistent_admin_notices, '$persistent_admin_notices', __FILE__, __LINE__);
130
+		if (! empty($persistent_admin_notices)) {
131
+			foreach ($persistent_admin_notices as $name => $details) {
132
+				if (is_array($details)) {
133
+					if (
134
+						! isset(
135
+							$details['message'],
136
+							$details['capability'],
137
+							$details['cap_context'],
138
+							$details['dismissed']
139
+						)
140
+					) {
141
+						throw new DomainException(
142
+							sprintf(
143
+								esc_html__(
144
+									'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
145
+									'event_espresso'
146
+								),
147
+								$name
148
+							)
149
+						);
150
+					}
151
+					// new format for nag notices
152
+					$this->notice_collection->add(
153
+						new PersistentAdminNotice(
154
+							$name,
155
+							$details['message'],
156
+							false,
157
+							$details['capability'],
158
+							$details['cap_context'],
159
+							$details['dismissed']
160
+						),
161
+						$name
162
+					);
163
+				} else {
164
+					try {
165
+						// old nag notices, that we want to convert to the new format
166
+						$this->notice_collection->add(
167
+							new PersistentAdminNotice(
168
+								$name,
169
+								(string)$details,
170
+								false,
171
+								'',
172
+								'',
173
+								empty($details)
174
+							),
175
+							$name
176
+						);
177
+					} catch (Exception $e) {
178
+						EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
179
+					}
180
+				}
181
+				// each notice will self register when the action hook in registerNotices is triggered
182
+			}
183
+		}
184
+	}
185
+
186
+
187
+
188
+	/**
189
+	 * exposes the Persistent Admin Notice Collection via an action
190
+	 * so that PersistentAdminNotice objects can be added and/or removed
191
+	 * without compromising the actual collection like a filter would
192
+	 */
193
+	protected function registerNotices()
194
+	{
195
+		do_action(
196
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
197
+			$this->notice_collection
198
+		);
199
+	}
200
+
201
+
202
+
203
+	/**
204
+	 * @throws DomainException
205
+	 * @throws InvalidClassException
206
+	 * @throws InvalidDataTypeException
207
+	 * @throws InvalidInterfaceException
208
+	 * @throws InvalidEntityException
209
+	 */
210
+	public function displayNotices()
211
+	{
212
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
213
+		if ($this->notice_collection->hasObjects()) {
214
+			// and display notices
215
+			foreach ($this->notice_collection as $persistent_admin_notice) {
216
+				/** @var PersistentAdminNotice $persistent_admin_notice */
217
+				// don't display notices that have already been dismissed
218
+				if ($persistent_admin_notice->getDismissed()) {
219
+					continue;
220
+				}
221
+				try {
222
+					$this->capabilities_checker->processCapCheck(
223
+						$persistent_admin_notice->getCapCheck()
224
+					);
225
+				} catch (InsufficientPermissionsException $e) {
226
+					// user does not have required cap, so skip to next notice
227
+					// and just eat the exception - nom nom nom nom
228
+					continue;
229
+				}
230
+				$this->displayPersistentAdminNotice($persistent_admin_notice);
231
+			}
232
+			$this->enqueueAssets();
233
+		}
234
+	}
235
+
236
+
237
+
238
+	/**
239
+	 * does what it's named
240
+	 *
241
+	 * @return void
242
+	 */
243
+	public function enqueueAssets()
244
+	{
245
+		wp_register_script(
246
+			'espresso_core',
247
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
248
+			array('jquery'),
249
+			EVENT_ESPRESSO_VERSION,
250
+			true
251
+		);
252
+		wp_register_script(
253
+			'ee_error_js',
254
+			EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
255
+			array('espresso_core'),
256
+			EVENT_ESPRESSO_VERSION,
257
+			true
258
+		);
259
+		wp_localize_script(
260
+			'ee_error_js',
261
+			'ee_dismiss',
262
+			array(
263
+				'return_url'    => urlencode($this->return_url),
264
+				'ajax_url'      => WP_AJAX_URL,
265
+				'unknown_error' => esc_html__(
266
+					'An unknown error has occurred on the server while attempting to dismiss this notice.',
267
+					'event_espresso'
268
+				),
269
+			)
270
+		);
271
+		wp_enqueue_script('ee_error_js');
272
+	}
273
+
274
+
275
+
276
+	/**
277
+	 * displayPersistentAdminNoticeHtml
278
+	 *
279
+	 * @param  PersistentAdminNotice $persistent_admin_notice
280
+	 */
281
+	protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
282
+	{
283
+		// used in template
284
+		$persistent_admin_notice_name    = $persistent_admin_notice->getName();
285
+		$persistent_admin_notice_message = $persistent_admin_notice->getMessage();
286
+		require EE_TEMPLATES . DS . 'notifications' . DS . 'persistent_admin_notice.template.php';
287
+	}
288
+
289
+
290
+
291
+	/**
292
+	 * dismissNotice
293
+	 *
294
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
295
+	 * @param bool   $purge    if true, then delete it from the db
296
+	 * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
297
+	 * @return void
298
+	 * @throws InvalidEntityException
299
+	 * @throws InvalidInterfaceException
300
+	 * @throws InvalidDataTypeException
301
+	 * @throws DomainException
302
+	 */
303
+	public function dismissNotice($pan_name = '', $purge = false, $return = false)
304
+	{
305
+		$pan_name                = $this->request->get('ee_nag_notice', $pan_name);
306
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
307
+		if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
308
+			/** @var PersistentAdminNotice $persistent_admin_notice */
309
+			$persistent_admin_notice = $this->notice_collection->get($pan_name);
310
+			$persistent_admin_notice->setDismissed(true);
311
+			$persistent_admin_notice->setPurge($purge);
312
+			$this->saveNotices();
313
+		}
314
+		if ($return) {
315
+			return;
316
+		}
317
+		if ($this->request->ajax) {
318
+			// grab any notices and concatenate into string
319
+			echo wp_json_encode(
320
+				array(
321
+					'errors' => implode('<br />', EE_Error::get_notices(false)),
322
+				)
323
+			);
324
+			exit();
325
+		}
326
+		// save errors to a transient to be displayed on next request (after redirect)
327
+		EE_Error::get_notices(false, true);
328
+		wp_safe_redirect(
329
+			urldecode(
330
+				$this->request->get('return_url', '')
331
+			)
332
+		);
333
+	}
334
+
335
+
336
+
337
+	/**
338
+	 * saveNotices
339
+	 *
340
+	 * @throws DomainException
341
+	 * @throws InvalidDataTypeException
342
+	 * @throws InvalidInterfaceException
343
+	 * @throws InvalidEntityException
344
+	 */
345
+	public function saveNotices()
346
+	{
347
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
348
+		if ($this->notice_collection->hasObjects()) {
349
+			$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
350
+			//maybe initialize persistent_admin_notices
351
+			if (empty($persistent_admin_notices)) {
352
+				add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
353
+			}
354
+			foreach ($this->notice_collection as $persistent_admin_notice) {
355
+				// are we deleting this notice ?
356
+				if ($persistent_admin_notice->getPurge()) {
357
+					unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
358
+				} else {
359
+					/** @var PersistentAdminNotice $persistent_admin_notice */
360
+					$persistent_admin_notices[$persistent_admin_notice->getName()] = array(
361
+						'message'     => $persistent_admin_notice->getMessage(),
362
+						'capability'  => $persistent_admin_notice->getCapability(),
363
+						'cap_context' => $persistent_admin_notice->getCapContext(),
364
+						'dismissed'   => $persistent_admin_notice->getDismissed(),
365
+					);
366
+				}
367
+			}
368
+			update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
369
+		}
370
+	}
371
+
372
+
373
+
374
+	/**
375
+	 * @throws DomainException
376
+	 * @throws InvalidDataTypeException
377
+	 * @throws InvalidEntityException
378
+	 * @throws InvalidInterfaceException
379
+	 */
380
+	public function registerAndSaveNotices()
381
+	{
382
+		$this->getPersistentAdminNoticeCollection();
383
+		$this->registerNotices();
384
+		$this->saveNotices();
385
+	}
386 386
 
387 387
 
388 388
 }
Please login to merge, or discard this patch.