Completed
Branch FET/11071/remove-directories-c... (a14c00)
by
unknown
56:10 queued 43:04
created
core/services/Benchmark.php 2 patches
Indentation   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -20,310 +20,310 @@
 block discarded – undo
20 20
 class Benchmark
21 21
 {
22 22
 
23
-    /**
24
-     * array containing the start time for the timers
25
-     */
26
-    private static $start_times;
27
-
28
-    /**
29
-     * array containing all the timer'd times, which can be outputted via show_times()
30
-     */
31
-    private static $times = array();
32
-
33
-    /**
34
-     * @var array
35
-     */
36
-    protected static $memory_usage = array();
37
-
38
-
39
-
40
-    /**
41
-     * whether to benchmark code or not
42
-     */
43
-    public static function doNotRun()
44
-    {
45
-        return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
46
-    }
47
-
48
-
49
-
50
-    /**
51
-     * resetTimes
52
-     */
53
-    public static function resetTimes()
54
-    {
55
-        Benchmark::$times = array();
56
-    }
57
-
58
-
59
-
60
-    /**
61
-     * Add Benchmark::startTimer() before a block of code you want to measure the performance of
62
-     *
63
-     * @param null $timer_name
64
-     */
65
-    public static function startTimer($timer_name = null)
66
-    {
67
-        if (Benchmark::doNotRun()) {
68
-            return;
69
-        }
70
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
71
-        Benchmark::$start_times[$timer_name] = microtime(true);
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
78
-     *
79
-     * @param string $timer_name
80
-     */
81
-    public static function stopTimer($timer_name = '')
82
-    {
83
-        if (Benchmark::doNotRun()) {
84
-            return;
85
-        }
86
-        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
87
-        if (isset(Benchmark::$start_times[$timer_name])) {
88
-            $start_time = Benchmark::$start_times[$timer_name];
89
-            unset(Benchmark::$start_times[$timer_name]);
90
-        } else {
91
-            $start_time = array_pop(Benchmark::$start_times);
92
-        }
93
-        Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
94
-    }
95
-
96
-
97
-
98
-    /**
99
-     * Measure the memory usage by PHP so far.
100
-     *
101
-     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
102
-     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
103
-     * @param bool    $formatted
104
-     * @return void
105
-     */
106
-    public static function measureMemory($label = 'memory usage', $output_now = false, $formatted = true)
107
-    {
108
-        if (Benchmark::doNotRun()) {
109
-            return;
110
-        }
111
-        $memory_used = Benchmark::convert(memory_get_usage(true));
112
-        Benchmark::$memory_usage[$label] = $memory_used;
113
-        if ($output_now) {
114
-            echo $formatted
115
-                ? "<br>{$label} : {$memory_used}"
116
-                : "\n {$label} : {$memory_used}";
117
-        }
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * will display the benchmarking results at shutdown
124
-     *
125
-     * @param bool $formatted
126
-     * @return void
127
-     */
128
-    public static function displayResultsAtShutdown($formatted = true)
129
-    {
130
-        add_action(
131
-            'shutdown',
132
-            function () use ($formatted) {
133
-                Benchmark::displayResults(true, $formatted);
134
-            }
135
-        );
136
-    }
137
-
138
-
139
-
140
-    /**
141
-     * will display the benchmarking results at shutdown
142
-     *
143
-     * @param string $filepath
144
-     * @param bool   $formatted
145
-     * @param bool   $append
146
-     * @return void
147
-     */
148
-    public static function writeResultsAtShutdown($filepath = '', $formatted = true, $append = true)
149
-    {
150
-        add_action(
151
-            'shutdown',
152
-            function () use ($filepath, $formatted, $append) {
153
-                Benchmark::writeResultsToFile($filepath, $formatted, $append);
154
-            }
155
-        );
156
-    }
157
-
158
-
159
-
160
-    /**
161
-     * @param bool $formatted
162
-     * @return string
163
-     */
164
-    private static function generateResults($formatted = true)
165
-    {
166
-        if (Benchmark::doNotRun()) {
167
-            return '';
168
-        }
169
-        $output = '';
170
-        if (! empty(Benchmark::$times)) {
171
-            $total = 0;
172
-            $output .= $formatted
173
-                ? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
174
-                : '';
175
-            foreach (Benchmark::$times as $timer_name => $total_time) {
176
-                $output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
177
-                $output .= $formatted ? '<br />'  : "\n";
178
-                $total += $total_time;
179
-            }
180
-            if($formatted) {
181
-                $output .= '<br />';
182
-                $output .= '<h4>TOTAL TIME</h4>';
183
-                $output .= Benchmark::formatTime('', $total, $formatted);
184
-                $output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
185
-                $output .= '<br />';
186
-                $output .= '<h5>Performance scale (from best to worse)</h5>';
187
-                $output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
188
-                $output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
189
-                $output .= '<span style="color:limegreen">Like...groovy!</span><br />';
190
-                $output .= '<span style="color:gold">Ruh Oh</span><br />';
191
-                $output .= '<span style="color:darkorange">Zoinks!</span><br />';
192
-                $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
193
-            }
194
-        }
195
-        if (! empty(Benchmark::$memory_usage)) {
196
-            $output .= $formatted
197
-                ? '<h5>Memory</h5>'
198
-                : "\nMemory";
199
-            foreach (Benchmark::$memory_usage as $label => $memory_usage) {
200
-                $output .= $formatted
201
-                    ? '<br />'
202
-                    : "\n";
203
-                $output .= "{$memory_usage} : {$label}";
204
-            }
205
-        }
206
-        if (empty($output)) {
207
-            return '';
208
-        }
209
-        $output = $formatted
210
-            ? '<div style="border:1px solid #dddddd; background-color:#ffffff;'
211
-              . (is_admin()
212
-                ? ' margin:2em 2em 2em 180px;'
213
-                : ' margin:2em;')
214
-              . ' padding:2em;">'
215
-              . '<h4>BENCHMARKING</h4>'
216
-              . $output
217
-              . '</div>'
218
-            : $output;
219
-        return $output;
220
-    }
221
-
222
-
223
-
224
-    /**
225
-     * @param bool $echo
226
-     * @param bool $formatted
227
-     * @return string
228
-     */
229
-    public static function displayResults($echo = true, $formatted = true)
230
-    {
231
-        $results = Benchmark::generateResults($formatted);
232
-        if ($echo) {
233
-            echo $results;
234
-            $results = '';
235
-        }
236
-        return $results;
237
-    }
238
-
239
-
240
-    /**
241
-     * @param string $filepath
242
-     * @param bool   $formatted
243
-     * @param bool   $append
244
-     * @throws EE_Error
245
-     */
246
-    public static function writeResultsToFile($filepath = '', $formatted = true, $append = true)
247
-    {
248
-        $filepath = ! empty($filepath) && is_readable(dirname($filepath))
249
-            ? $filepath
250
-            : '';
251
-        if( empty($filepath)) {
252
-            $filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
253
-        }
254
-        EEH_File::ensure_file_exists_and_is_writable($filepath);
255
-        file_put_contents(
256
-            $filepath,
257
-            "\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
258
-            $append ? FILE_APPEND | LOCK_EX : LOCK_EX
259
-        );
260
-    }
261
-
262
-
263
-
264
-    /**
265
-     * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
266
-     *
267
-     * @param int $size
268
-     * @return string
269
-     */
270
-    public static function convert($size)
271
-    {
272
-        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
273
-        return round(
274
-            $size / pow(1024, $i = floor(log($size, 1024))),
275
-            2
276
-        ) . ' ' . $unit[absint($i)];
277
-    }
278
-
279
-
280
-
281
-    /**
282
-     * @param string $timer_name
283
-     * @param float  $total_time
284
-     * @param bool   $formatted
285
-     * @return string
286
-     */
287
-    public static function formatTime($timer_name, $total_time, $formatted = true)
288
-    {
289
-        $total_time *= 1000;
290
-        switch ($total_time) {
291
-            case $total_time > 12500 :
292
-                $color = 'red';
293
-                $bold = 'bold';
294
-                break;
295
-            case $total_time > 2500 :
296
-                $color = 'darkorange';
297
-                $bold = 'bold';
298
-                break;
299
-            case $total_time > 500 :
300
-                $color = 'gold';
301
-                $bold = 'bold';
302
-                break;
303
-            case $total_time > 100 :
304
-                $color = 'limegreen';
305
-                $bold = 'normal';
306
-                break;
307
-            case $total_time > 20 :
308
-                $color = 'deepskyblue';
309
-                $bold = 'normal';
310
-                break;
311
-            default :
312
-                $color = 'mediumpurple';
313
-                $bold = 'normal';
314
-                break;
315
-        }
316
-        return $formatted
317
-            ? '<span style="min-width: 10px; margin:0 1em; color:'
318
-               . $color
319
-               . '; font-weight:'
320
-               . $bold
321
-               . '; font-size:1.2em;">'
322
-               . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
323
-               . '</span> '
324
-               . $timer_name
325
-            :  str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT);
326
-    }
23
+	/**
24
+	 * array containing the start time for the timers
25
+	 */
26
+	private static $start_times;
27
+
28
+	/**
29
+	 * array containing all the timer'd times, which can be outputted via show_times()
30
+	 */
31
+	private static $times = array();
32
+
33
+	/**
34
+	 * @var array
35
+	 */
36
+	protected static $memory_usage = array();
37
+
38
+
39
+
40
+	/**
41
+	 * whether to benchmark code or not
42
+	 */
43
+	public static function doNotRun()
44
+	{
45
+		return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
46
+	}
47
+
48
+
49
+
50
+	/**
51
+	 * resetTimes
52
+	 */
53
+	public static function resetTimes()
54
+	{
55
+		Benchmark::$times = array();
56
+	}
57
+
58
+
59
+
60
+	/**
61
+	 * Add Benchmark::startTimer() before a block of code you want to measure the performance of
62
+	 *
63
+	 * @param null $timer_name
64
+	 */
65
+	public static function startTimer($timer_name = null)
66
+	{
67
+		if (Benchmark::doNotRun()) {
68
+			return;
69
+		}
70
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
71
+		Benchmark::$start_times[$timer_name] = microtime(true);
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
78
+	 *
79
+	 * @param string $timer_name
80
+	 */
81
+	public static function stopTimer($timer_name = '')
82
+	{
83
+		if (Benchmark::doNotRun()) {
84
+			return;
85
+		}
86
+		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
87
+		if (isset(Benchmark::$start_times[$timer_name])) {
88
+			$start_time = Benchmark::$start_times[$timer_name];
89
+			unset(Benchmark::$start_times[$timer_name]);
90
+		} else {
91
+			$start_time = array_pop(Benchmark::$start_times);
92
+		}
93
+		Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
94
+	}
95
+
96
+
97
+
98
+	/**
99
+	 * Measure the memory usage by PHP so far.
100
+	 *
101
+	 * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
102
+	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
103
+	 * @param bool    $formatted
104
+	 * @return void
105
+	 */
106
+	public static function measureMemory($label = 'memory usage', $output_now = false, $formatted = true)
107
+	{
108
+		if (Benchmark::doNotRun()) {
109
+			return;
110
+		}
111
+		$memory_used = Benchmark::convert(memory_get_usage(true));
112
+		Benchmark::$memory_usage[$label] = $memory_used;
113
+		if ($output_now) {
114
+			echo $formatted
115
+				? "<br>{$label} : {$memory_used}"
116
+				: "\n {$label} : {$memory_used}";
117
+		}
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * will display the benchmarking results at shutdown
124
+	 *
125
+	 * @param bool $formatted
126
+	 * @return void
127
+	 */
128
+	public static function displayResultsAtShutdown($formatted = true)
129
+	{
130
+		add_action(
131
+			'shutdown',
132
+			function () use ($formatted) {
133
+				Benchmark::displayResults(true, $formatted);
134
+			}
135
+		);
136
+	}
137
+
138
+
139
+
140
+	/**
141
+	 * will display the benchmarking results at shutdown
142
+	 *
143
+	 * @param string $filepath
144
+	 * @param bool   $formatted
145
+	 * @param bool   $append
146
+	 * @return void
147
+	 */
148
+	public static function writeResultsAtShutdown($filepath = '', $formatted = true, $append = true)
149
+	{
150
+		add_action(
151
+			'shutdown',
152
+			function () use ($filepath, $formatted, $append) {
153
+				Benchmark::writeResultsToFile($filepath, $formatted, $append);
154
+			}
155
+		);
156
+	}
157
+
158
+
159
+
160
+	/**
161
+	 * @param bool $formatted
162
+	 * @return string
163
+	 */
164
+	private static function generateResults($formatted = true)
165
+	{
166
+		if (Benchmark::doNotRun()) {
167
+			return '';
168
+		}
169
+		$output = '';
170
+		if (! empty(Benchmark::$times)) {
171
+			$total = 0;
172
+			$output .= $formatted
173
+				? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
174
+				: '';
175
+			foreach (Benchmark::$times as $timer_name => $total_time) {
176
+				$output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
177
+				$output .= $formatted ? '<br />'  : "\n";
178
+				$total += $total_time;
179
+			}
180
+			if($formatted) {
181
+				$output .= '<br />';
182
+				$output .= '<h4>TOTAL TIME</h4>';
183
+				$output .= Benchmark::formatTime('', $total, $formatted);
184
+				$output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
185
+				$output .= '<br />';
186
+				$output .= '<h5>Performance scale (from best to worse)</h5>';
187
+				$output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
188
+				$output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
189
+				$output .= '<span style="color:limegreen">Like...groovy!</span><br />';
190
+				$output .= '<span style="color:gold">Ruh Oh</span><br />';
191
+				$output .= '<span style="color:darkorange">Zoinks!</span><br />';
192
+				$output .= '<span style="color:red">Like...HEEELLLP</span><br />';
193
+			}
194
+		}
195
+		if (! empty(Benchmark::$memory_usage)) {
196
+			$output .= $formatted
197
+				? '<h5>Memory</h5>'
198
+				: "\nMemory";
199
+			foreach (Benchmark::$memory_usage as $label => $memory_usage) {
200
+				$output .= $formatted
201
+					? '<br />'
202
+					: "\n";
203
+				$output .= "{$memory_usage} : {$label}";
204
+			}
205
+		}
206
+		if (empty($output)) {
207
+			return '';
208
+		}
209
+		$output = $formatted
210
+			? '<div style="border:1px solid #dddddd; background-color:#ffffff;'
211
+			  . (is_admin()
212
+				? ' margin:2em 2em 2em 180px;'
213
+				: ' margin:2em;')
214
+			  . ' padding:2em;">'
215
+			  . '<h4>BENCHMARKING</h4>'
216
+			  . $output
217
+			  . '</div>'
218
+			: $output;
219
+		return $output;
220
+	}
221
+
222
+
223
+
224
+	/**
225
+	 * @param bool $echo
226
+	 * @param bool $formatted
227
+	 * @return string
228
+	 */
229
+	public static function displayResults($echo = true, $formatted = true)
230
+	{
231
+		$results = Benchmark::generateResults($formatted);
232
+		if ($echo) {
233
+			echo $results;
234
+			$results = '';
235
+		}
236
+		return $results;
237
+	}
238
+
239
+
240
+	/**
241
+	 * @param string $filepath
242
+	 * @param bool   $formatted
243
+	 * @param bool   $append
244
+	 * @throws EE_Error
245
+	 */
246
+	public static function writeResultsToFile($filepath = '', $formatted = true, $append = true)
247
+	{
248
+		$filepath = ! empty($filepath) && is_readable(dirname($filepath))
249
+			? $filepath
250
+			: '';
251
+		if( empty($filepath)) {
252
+			$filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
253
+		}
254
+		EEH_File::ensure_file_exists_and_is_writable($filepath);
255
+		file_put_contents(
256
+			$filepath,
257
+			"\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
258
+			$append ? FILE_APPEND | LOCK_EX : LOCK_EX
259
+		);
260
+	}
261
+
262
+
263
+
264
+	/**
265
+	 * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
266
+	 *
267
+	 * @param int $size
268
+	 * @return string
269
+	 */
270
+	public static function convert($size)
271
+	{
272
+		$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
273
+		return round(
274
+			$size / pow(1024, $i = floor(log($size, 1024))),
275
+			2
276
+		) . ' ' . $unit[absint($i)];
277
+	}
278
+
279
+
280
+
281
+	/**
282
+	 * @param string $timer_name
283
+	 * @param float  $total_time
284
+	 * @param bool   $formatted
285
+	 * @return string
286
+	 */
287
+	public static function formatTime($timer_name, $total_time, $formatted = true)
288
+	{
289
+		$total_time *= 1000;
290
+		switch ($total_time) {
291
+			case $total_time > 12500 :
292
+				$color = 'red';
293
+				$bold = 'bold';
294
+				break;
295
+			case $total_time > 2500 :
296
+				$color = 'darkorange';
297
+				$bold = 'bold';
298
+				break;
299
+			case $total_time > 500 :
300
+				$color = 'gold';
301
+				$bold = 'bold';
302
+				break;
303
+			case $total_time > 100 :
304
+				$color = 'limegreen';
305
+				$bold = 'normal';
306
+				break;
307
+			case $total_time > 20 :
308
+				$color = 'deepskyblue';
309
+				$bold = 'normal';
310
+				break;
311
+			default :
312
+				$color = 'mediumpurple';
313
+				$bold = 'normal';
314
+				break;
315
+		}
316
+		return $formatted
317
+			? '<span style="min-width: 10px; margin:0 1em; color:'
318
+			   . $color
319
+			   . '; font-weight:'
320
+			   . $bold
321
+			   . '; font-size:1.2em;">'
322
+			   . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
323
+			   . '</span> '
324
+			   . $timer_name
325
+			:  str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT);
326
+	}
327 327
 
328 328
 
329 329
 
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
     {
130 130
         add_action(
131 131
             'shutdown',
132
-            function () use ($formatted) {
132
+            function() use ($formatted) {
133 133
                 Benchmark::displayResults(true, $formatted);
134 134
             }
135 135
         );
@@ -149,7 +149,7 @@  discard block
 block discarded – undo
149 149
     {
150 150
         add_action(
151 151
             'shutdown',
152
-            function () use ($filepath, $formatted, $append) {
152
+            function() use ($filepath, $formatted, $append) {
153 153
                 Benchmark::writeResultsToFile($filepath, $formatted, $append);
154 154
             }
155 155
         );
@@ -167,17 +167,17 @@  discard block
 block discarded – undo
167 167
             return '';
168 168
         }
169 169
         $output = '';
170
-        if (! empty(Benchmark::$times)) {
170
+        if ( ! empty(Benchmark::$times)) {
171 171
             $total = 0;
172 172
             $output .= $formatted
173 173
                 ? '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />'
174 174
                 : '';
175 175
             foreach (Benchmark::$times as $timer_name => $total_time) {
176 176
                 $output .= Benchmark::formatTime($timer_name, $total_time, $formatted);
177
-                $output .= $formatted ? '<br />'  : "\n";
177
+                $output .= $formatted ? '<br />' : "\n";
178 178
                 $total += $total_time;
179 179
             }
180
-            if($formatted) {
180
+            if ($formatted) {
181 181
                 $output .= '<br />';
182 182
                 $output .= '<h4>TOTAL TIME</h4>';
183 183
                 $output .= Benchmark::formatTime('', $total, $formatted);
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
                 $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
193 193
             }
194 194
         }
195
-        if (! empty(Benchmark::$memory_usage)) {
195
+        if ( ! empty(Benchmark::$memory_usage)) {
196 196
             $output .= $formatted
197 197
                 ? '<h5>Memory</h5>'
198 198
                 : "\nMemory";
@@ -248,13 +248,13 @@  discard block
 block discarded – undo
248 248
         $filepath = ! empty($filepath) && is_readable(dirname($filepath))
249 249
             ? $filepath
250 250
             : '';
251
-        if( empty($filepath)) {
252
-            $filepath = EVENT_ESPRESSO_UPLOAD_DIR . 'logs/benchmarking-' . date('Y-m-d') . '.html';
251
+        if (empty($filepath)) {
252
+            $filepath = EVENT_ESPRESSO_UPLOAD_DIR.'logs/benchmarking-'.date('Y-m-d').'.html';
253 253
         }
254 254
         EEH_File::ensure_file_exists_and_is_writable($filepath);
255 255
         file_put_contents(
256 256
             $filepath,
257
-            "\n" . date('Y-m-d H:i:s') . Benchmark::generateResults($formatted),
257
+            "\n".date('Y-m-d H:i:s').Benchmark::generateResults($formatted),
258 258
             $append ? FILE_APPEND | LOCK_EX : LOCK_EX
259 259
         );
260 260
     }
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
         return round(
274 274
             $size / pow(1024, $i = floor(log($size, 1024))),
275 275
             2
276
-        ) . ' ' . $unit[absint($i)];
276
+        ).' '.$unit[absint($i)];
277 277
     }
278 278
 
279 279
 
Please login to merge, or discard this patch.
core/helpers/EEH_Activation.helper.php 2 patches
Indentation   +1581 added lines, -1581 removed lines patch added patch discarded remove patch
@@ -18,233 +18,233 @@  discard block
 block discarded – undo
18 18
 class EEH_Activation implements ResettableInterface
19 19
 {
20 20
 
21
-    /**
22
-     * constant used to indicate a cron task is no longer in use
23
-     */
24
-    const cron_task_no_longer_in_use = 'no_longer_in_use';
25
-
26
-    /**
27
-     * WP_User->ID
28
-     *
29
-     * @var int
30
-     */
31
-    private static $_default_creator_id;
32
-
33
-    /**
34
-     * indicates whether or not we've already verified core's default data during this request,
35
-     * because after migrations are done, any addons activated while in maintenance mode
36
-     * will want to setup their own default data, and they might hook into core's default data
37
-     * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
38
-     * This prevents doing that for EVERY single addon.
39
-     *
40
-     * @var boolean
41
-     */
42
-    protected static $_initialized_db_content_already_in_this_request = false;
43
-
44
-    /**
45
-     * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
46
-     */
47
-    private static $table_analysis;
48
-
49
-    /**
50
-     * @var \EventEspresso\core\services\database\TableManager $table_manager
51
-     */
52
-    private static $table_manager;
53
-
54
-
55
-    /**
56
-     * @return \EventEspresso\core\services\database\TableAnalysis
57
-     */
58
-    public static function getTableAnalysis()
59
-    {
60
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
61
-            self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
62
-        }
63
-        return self::$table_analysis;
64
-    }
65
-
66
-
67
-    /**
68
-     * @return \EventEspresso\core\services\database\TableManager
69
-     */
70
-    public static function getTableManager()
71
-    {
72
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
73
-            self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
74
-        }
75
-        return self::$table_manager;
76
-    }
77
-
78
-
79
-    /**
80
-     *    _ensure_table_name_has_prefix
81
-     *
82
-     * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
83
-     * @access     public
84
-     * @static
85
-     * @param $table_name
86
-     * @return string
87
-     */
88
-    public static function ensure_table_name_has_prefix($table_name)
89
-    {
90
-        return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
91
-    }
92
-
93
-
94
-    /**
95
-     *    system_initialization
96
-     *    ensures the EE configuration settings are loaded with at least default options set
97
-     *    and that all critical EE pages have been generated with the appropriate shortcodes in place
98
-     *
99
-     * @access public
100
-     * @static
101
-     * @return void
102
-     */
103
-    public static function system_initialization()
104
-    {
105
-        EEH_Activation::reset_and_update_config();
106
-        //which is fired BEFORE activation of plugin anyways
107
-        EEH_Activation::verify_default_pages_exist();
108
-    }
109
-
110
-
111
-    /**
112
-     * Sets the database schema and creates folders. This should
113
-     * be called on plugin activation and reactivation
114
-     *
115
-     * @return boolean success, whether the database and folders are setup properly
116
-     * @throws \EE_Error
117
-     */
118
-    public static function initialize_db_and_folders()
119
-    {
120
-        return EEH_Activation::create_database_tables();
121
-    }
122
-
123
-
124
-    /**
125
-     * assuming we have an up-to-date database schema, this will populate it
126
-     * with default and initial data. This should be called
127
-     * upon activation of a new plugin, reactivation, and at the end
128
-     * of running migration scripts
129
-     *
130
-     * @throws \EE_Error
131
-     */
132
-    public static function initialize_db_content()
133
-    {
134
-        //let's avoid doing all this logic repeatedly, especially when addons are requesting it
135
-        if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
136
-            return;
137
-        }
138
-        EEH_Activation::$_initialized_db_content_already_in_this_request = true;
139
-
140
-        EEH_Activation::initialize_system_questions();
141
-        EEH_Activation::insert_default_status_codes();
142
-        EEH_Activation::generate_default_message_templates();
143
-        EEH_Activation::create_no_ticket_prices_array();
144
-
145
-        EEH_Activation::validate_messages_system();
146
-        EEH_Activation::insert_default_payment_methods();
147
-        //in case we've
148
-        EEH_Activation::remove_cron_tasks();
149
-        EEH_Activation::create_cron_tasks();
150
-        // remove all TXN locks since that is being done via extra meta now
151
-        delete_option('ee_locked_transactions');
152
-        //also, check for CAF default db content
153
-        do_action('AHEE__EEH_Activation__initialize_db_content');
154
-        //also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
155
-        //which users really won't care about on initial activation
156
-        EE_Error::overwrite_success();
157
-    }
158
-
159
-
160
-    /**
161
-     * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
162
-     * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
163
-     * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
164
-     * (null)
165
-     *
166
-     * @param string $which_to_include can be 'current' (ones that are currently in use),
167
-     *                                 'old' (only returns ones that should no longer be used),or 'all',
168
-     * @return array
169
-     * @throws \EE_Error
170
-     */
171
-    public static function get_cron_tasks($which_to_include)
172
-    {
173
-        $cron_tasks = apply_filters(
174
-            'FHEE__EEH_Activation__get_cron_tasks',
175
-            array(
176
-                'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
21
+	/**
22
+	 * constant used to indicate a cron task is no longer in use
23
+	 */
24
+	const cron_task_no_longer_in_use = 'no_longer_in_use';
25
+
26
+	/**
27
+	 * WP_User->ID
28
+	 *
29
+	 * @var int
30
+	 */
31
+	private static $_default_creator_id;
32
+
33
+	/**
34
+	 * indicates whether or not we've already verified core's default data during this request,
35
+	 * because after migrations are done, any addons activated while in maintenance mode
36
+	 * will want to setup their own default data, and they might hook into core's default data
37
+	 * and trigger core to setup its default data. In which case they might all ask for core to init its default data.
38
+	 * This prevents doing that for EVERY single addon.
39
+	 *
40
+	 * @var boolean
41
+	 */
42
+	protected static $_initialized_db_content_already_in_this_request = false;
43
+
44
+	/**
45
+	 * @var \EventEspresso\core\services\database\TableAnalysis $table_analysis
46
+	 */
47
+	private static $table_analysis;
48
+
49
+	/**
50
+	 * @var \EventEspresso\core\services\database\TableManager $table_manager
51
+	 */
52
+	private static $table_manager;
53
+
54
+
55
+	/**
56
+	 * @return \EventEspresso\core\services\database\TableAnalysis
57
+	 */
58
+	public static function getTableAnalysis()
59
+	{
60
+		if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
61
+			self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
62
+		}
63
+		return self::$table_analysis;
64
+	}
65
+
66
+
67
+	/**
68
+	 * @return \EventEspresso\core\services\database\TableManager
69
+	 */
70
+	public static function getTableManager()
71
+	{
72
+		if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
73
+			self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
74
+		}
75
+		return self::$table_manager;
76
+	}
77
+
78
+
79
+	/**
80
+	 *    _ensure_table_name_has_prefix
81
+	 *
82
+	 * @deprecated instead use TableAnalysis::ensureTableNameHasPrefix()
83
+	 * @access     public
84
+	 * @static
85
+	 * @param $table_name
86
+	 * @return string
87
+	 */
88
+	public static function ensure_table_name_has_prefix($table_name)
89
+	{
90
+		return \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix($table_name);
91
+	}
92
+
93
+
94
+	/**
95
+	 *    system_initialization
96
+	 *    ensures the EE configuration settings are loaded with at least default options set
97
+	 *    and that all critical EE pages have been generated with the appropriate shortcodes in place
98
+	 *
99
+	 * @access public
100
+	 * @static
101
+	 * @return void
102
+	 */
103
+	public static function system_initialization()
104
+	{
105
+		EEH_Activation::reset_and_update_config();
106
+		//which is fired BEFORE activation of plugin anyways
107
+		EEH_Activation::verify_default_pages_exist();
108
+	}
109
+
110
+
111
+	/**
112
+	 * Sets the database schema and creates folders. This should
113
+	 * be called on plugin activation and reactivation
114
+	 *
115
+	 * @return boolean success, whether the database and folders are setup properly
116
+	 * @throws \EE_Error
117
+	 */
118
+	public static function initialize_db_and_folders()
119
+	{
120
+		return EEH_Activation::create_database_tables();
121
+	}
122
+
123
+
124
+	/**
125
+	 * assuming we have an up-to-date database schema, this will populate it
126
+	 * with default and initial data. This should be called
127
+	 * upon activation of a new plugin, reactivation, and at the end
128
+	 * of running migration scripts
129
+	 *
130
+	 * @throws \EE_Error
131
+	 */
132
+	public static function initialize_db_content()
133
+	{
134
+		//let's avoid doing all this logic repeatedly, especially when addons are requesting it
135
+		if (EEH_Activation::$_initialized_db_content_already_in_this_request) {
136
+			return;
137
+		}
138
+		EEH_Activation::$_initialized_db_content_already_in_this_request = true;
139
+
140
+		EEH_Activation::initialize_system_questions();
141
+		EEH_Activation::insert_default_status_codes();
142
+		EEH_Activation::generate_default_message_templates();
143
+		EEH_Activation::create_no_ticket_prices_array();
144
+
145
+		EEH_Activation::validate_messages_system();
146
+		EEH_Activation::insert_default_payment_methods();
147
+		//in case we've
148
+		EEH_Activation::remove_cron_tasks();
149
+		EEH_Activation::create_cron_tasks();
150
+		// remove all TXN locks since that is being done via extra meta now
151
+		delete_option('ee_locked_transactions');
152
+		//also, check for CAF default db content
153
+		do_action('AHEE__EEH_Activation__initialize_db_content');
154
+		//also: EEM_Gateways::load_all_gateways() outputs a lot of success messages
155
+		//which users really won't care about on initial activation
156
+		EE_Error::overwrite_success();
157
+	}
158
+
159
+
160
+	/**
161
+	 * Returns an array of cron tasks. Array values are the actions fired by the cron tasks (the "hooks"),
162
+	 * values are the frequency (the "recurrence"). See http://codex.wordpress.org/Function_Reference/wp_schedule_event
163
+	 * If the cron task should NO longer be used, it should have a value of EEH_Activation::cron_task_no_longer_in_use
164
+	 * (null)
165
+	 *
166
+	 * @param string $which_to_include can be 'current' (ones that are currently in use),
167
+	 *                                 'old' (only returns ones that should no longer be used),or 'all',
168
+	 * @return array
169
+	 * @throws \EE_Error
170
+	 */
171
+	public static function get_cron_tasks($which_to_include)
172
+	{
173
+		$cron_tasks = apply_filters(
174
+			'FHEE__EEH_Activation__get_cron_tasks',
175
+			array(
176
+				'AHEE__EE_Cron_Tasks__clean_up_junk_transactions'      => 'hourly',
177 177
 //				'AHEE__EE_Cron_Tasks__finalize_abandoned_transactions' => EEH_Activation::cron_task_no_longer_in_use, actually this is still in use
178
-                'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
179
-                //there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
180
-                'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
181
-            )
182
-        );
183
-        if ($which_to_include === 'old') {
184
-            $cron_tasks = array_filter(
185
-                $cron_tasks,
186
-                function ($value) {
187
-                    return $value === EEH_Activation::cron_task_no_longer_in_use;
188
-                }
189
-            );
190
-        } elseif ($which_to_include === 'current') {
191
-            $cron_tasks = array_filter($cron_tasks);
192
-        } elseif (WP_DEBUG && $which_to_include !== 'all') {
193
-            throw new EE_Error(
194
-                sprintf(
195
-                    __(
196
-                        'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
197
-                        'event_espresso'
198
-                    ),
199
-                    $which_to_include
200
-                )
201
-            );
202
-        }
203
-        return $cron_tasks;
204
-    }
205
-
206
-
207
-    /**
208
-     * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
209
-     *
210
-     * @throws \EE_Error
211
-     */
212
-    public static function create_cron_tasks()
213
-    {
214
-
215
-        foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
216
-            if (! wp_next_scheduled($hook_name)) {
217
-                /**
218
-                 * This allows client code to define the initial start timestamp for this schedule.
219
-                 */
220
-                if (is_array($frequency)
221
-                    && count($frequency) === 2
222
-                    && isset($frequency[0], $frequency[1])
223
-                ) {
224
-                    $start_timestamp = $frequency[0];
225
-                    $frequency = $frequency[1];
226
-                } else {
227
-                    $start_timestamp = time();
228
-                }
229
-                wp_schedule_event($start_timestamp, $frequency, $hook_name);
230
-            }
231
-        }
232
-
233
-    }
234
-
235
-
236
-    /**
237
-     * Remove the currently-existing and now-removed cron tasks.
238
-     *
239
-     * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
240
-     * @throws \EE_Error
241
-     */
242
-    public static function remove_cron_tasks($remove_all = true)
243
-    {
244
-        $cron_tasks_to_remove = $remove_all ? 'all' : 'old';
245
-        $crons                = _get_cron_array();
246
-        $crons                = is_array($crons) ? $crons : array();
247
-        /* reminder of what $crons look like:
178
+				'AHEE__EE_Cron_Tasks__update_transaction_with_payment' => EEH_Activation::cron_task_no_longer_in_use,
179
+				//there may have been a bug which prevented from these cron tasks from getting unscheduled, so we might want to remove these for a few updates
180
+				'AHEE_EE_Cron_Tasks__clean_out_old_gateway_logs'       => 'daily',
181
+			)
182
+		);
183
+		if ($which_to_include === 'old') {
184
+			$cron_tasks = array_filter(
185
+				$cron_tasks,
186
+				function ($value) {
187
+					return $value === EEH_Activation::cron_task_no_longer_in_use;
188
+				}
189
+			);
190
+		} elseif ($which_to_include === 'current') {
191
+			$cron_tasks = array_filter($cron_tasks);
192
+		} elseif (WP_DEBUG && $which_to_include !== 'all') {
193
+			throw new EE_Error(
194
+				sprintf(
195
+					__(
196
+						'Invalid argument of "%1$s" passed to EEH_Activation::get_cron_tasks. Valid values are "all", "old" and "current".',
197
+						'event_espresso'
198
+					),
199
+					$which_to_include
200
+				)
201
+			);
202
+		}
203
+		return $cron_tasks;
204
+	}
205
+
206
+
207
+	/**
208
+	 * Ensure cron tasks are setup (the removal of crons should be done by remove_crons())
209
+	 *
210
+	 * @throws \EE_Error
211
+	 */
212
+	public static function create_cron_tasks()
213
+	{
214
+
215
+		foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
216
+			if (! wp_next_scheduled($hook_name)) {
217
+				/**
218
+				 * This allows client code to define the initial start timestamp for this schedule.
219
+				 */
220
+				if (is_array($frequency)
221
+					&& count($frequency) === 2
222
+					&& isset($frequency[0], $frequency[1])
223
+				) {
224
+					$start_timestamp = $frequency[0];
225
+					$frequency = $frequency[1];
226
+				} else {
227
+					$start_timestamp = time();
228
+				}
229
+				wp_schedule_event($start_timestamp, $frequency, $hook_name);
230
+			}
231
+		}
232
+
233
+	}
234
+
235
+
236
+	/**
237
+	 * Remove the currently-existing and now-removed cron tasks.
238
+	 *
239
+	 * @param boolean $remove_all whether to only remove the old ones, or remove absolutely ALL the EE ones
240
+	 * @throws \EE_Error
241
+	 */
242
+	public static function remove_cron_tasks($remove_all = true)
243
+	{
244
+		$cron_tasks_to_remove = $remove_all ? 'all' : 'old';
245
+		$crons                = _get_cron_array();
246
+		$crons                = is_array($crons) ? $crons : array();
247
+		/* reminder of what $crons look like:
248 248
          * Top-level keys are timestamps, and their values are arrays.
249 249
          * The 2nd level arrays have keys with each of the cron task hook names to run at that time
250 250
          * and their values are arrays.
@@ -261,911 +261,911 @@  discard block
 block discarded – undo
261 261
          *					...
262 262
          *      ...
263 263
          */
264
-        $ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
265
-        foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
266
-            if (is_array($hooks_to_fire_at_time)) {
267
-                foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
268
-                    if (isset($ee_cron_tasks_to_remove[$hook_name])
269
-                        && is_array($ee_cron_tasks_to_remove[$hook_name])
270
-                    ) {
271
-                        unset($crons[$timestamp][$hook_name]);
272
-                    }
273
-                }
274
-                //also take care of any empty cron timestamps.
275
-                if (empty($hooks_to_fire_at_time)) {
276
-                    unset($crons[$timestamp]);
277
-                }
278
-            }
279
-        }
280
-        _set_cron_array($crons);
281
-    }
282
-
283
-
284
-    /**
285
-     *    CPT_initialization
286
-     *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
287
-     *
288
-     * @access public
289
-     * @static
290
-     * @return void
291
-     */
292
-    public static function CPT_initialization()
293
-    {
294
-        // register Custom Post Types
295
-        EE_Registry::instance()->load_core('Register_CPTs');
296
-        flush_rewrite_rules();
297
-    }
298
-
299
-
300
-
301
-    /**
302
-     *    reset_and_update_config
303
-     * The following code was moved over from EE_Config so that it will no longer run on every request.
304
-     * If there is old calendar config data saved, then it will get converted on activation.
305
-     * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
306
-     *
307
-     * @access public
308
-     * @static
309
-     * @return void
310
-     */
311
-    public static function reset_and_update_config()
312
-    {
313
-        do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
314
-        add_filter(
315
-            'FHEE__EE_Config___load_core_config__config_settings',
316
-            array('EEH_Activation', 'migrate_old_config_data'),
317
-            10,
318
-            3
319
-        );
320
-        //EE_Config::reset();
321
-        if (! EE_Config::logging_enabled()) {
322
-            delete_option(EE_Config::LOG_NAME);
323
-        }
324
-    }
325
-
326
-
327
-    /**
328
-     *    load_calendar_config
329
-     *
330
-     * @access    public
331
-     * @return    void
332
-     */
333
-    public static function load_calendar_config()
334
-    {
335
-        // grab array of all plugin folders and loop thru it
336
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
337
-        if (empty($plugins)) {
338
-            return;
339
-        }
340
-        foreach ($plugins as $plugin_path) {
341
-            // grab plugin folder name from path
342
-            $plugin = basename($plugin_path);
343
-            // drill down to Espresso plugins
344
-            // then to calendar related plugins
345
-            if (
346
-                strpos($plugin, 'espresso') !== false
347
-                || strpos($plugin, 'Espresso') !== false
348
-                || strpos($plugin, 'ee4') !== false
349
-                || strpos($plugin, 'EE4') !== false
350
-                || strpos($plugin, 'calendar') !== false
351
-            ) {
352
-                // this is what we are looking for
353
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
354
-                // does it exist in this folder ?
355
-                if (is_readable($calendar_config)) {
356
-                    // YEAH! let's load it
357
-                    require_once($calendar_config);
358
-                }
359
-            }
360
-        }
361
-    }
362
-
363
-
364
-
365
-    /**
366
-     *    _migrate_old_config_data
367
-     *
368
-     * @access    public
369
-     * @param array|stdClass $settings
370
-     * @param string         $config
371
-     * @param \EE_Config     $EE_Config
372
-     * @return \stdClass
373
-     */
374
-    public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
375
-    {
376
-        $convert_from_array = array('addons');
377
-        // in case old settings were saved as an array
378
-        if (is_array($settings) && in_array($config, $convert_from_array)) {
379
-            // convert existing settings to an object
380
-            $config_array = $settings;
381
-            $settings = new stdClass();
382
-            foreach ($config_array as $key => $value) {
383
-                if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
384
-                    $EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
385
-                } else {
386
-                    $settings->{$key} = $value;
387
-                }
388
-            }
389
-            add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
390
-        }
391
-        return $settings;
392
-    }
393
-
394
-
395
-    /**
396
-     * deactivate_event_espresso
397
-     *
398
-     * @access public
399
-     * @static
400
-     * @return void
401
-     */
402
-    public static function deactivate_event_espresso()
403
-    {
404
-        // check permissions
405
-        if (current_user_can('activate_plugins')) {
406
-            deactivate_plugins(EE_PLUGIN_BASENAME, true);
407
-        }
408
-    }
409
-
410
-
411
-
412
-    /**
413
-     * verify_default_pages_exist
414
-     *
415
-     * @access public
416
-     * @static
417
-     * @return void
418
-     * @throws InvalidDataTypeException
419
-     */
420
-    public static function verify_default_pages_exist()
421
-    {
422
-        $critical_page_problem = false;
423
-        $critical_pages = array(
424
-            array(
425
-                'id'   => 'reg_page_id',
426
-                'name' => __('Registration Checkout', 'event_espresso'),
427
-                'post' => null,
428
-                'code' => 'ESPRESSO_CHECKOUT',
429
-            ),
430
-            array(
431
-                'id'   => 'txn_page_id',
432
-                'name' => __('Transactions', 'event_espresso'),
433
-                'post' => null,
434
-                'code' => 'ESPRESSO_TXN_PAGE',
435
-            ),
436
-            array(
437
-                'id'   => 'thank_you_page_id',
438
-                'name' => __('Thank You', 'event_espresso'),
439
-                'post' => null,
440
-                'code' => 'ESPRESSO_THANK_YOU',
441
-            ),
442
-            array(
443
-                'id'   => 'cancel_page_id',
444
-                'name' => __('Registration Cancelled', 'event_espresso'),
445
-                'post' => null,
446
-                'code' => 'ESPRESSO_CANCELLED',
447
-            ),
448
-        );
449
-        $EE_Core_Config = EE_Registry::instance()->CFG->core;
450
-        foreach ($critical_pages as $critical_page) {
451
-            // is critical page ID set in config ?
452
-            if ($EE_Core_Config->{$critical_page['id']} !== false) {
453
-                // attempt to find post by ID
454
-                $critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
455
-            }
456
-            // no dice?
457
-            if ($critical_page['post'] === null) {
458
-                // attempt to find post by title
459
-                $critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
460
-                // still nothing?
461
-                if ($critical_page['post'] === null) {
462
-                    $critical_page = EEH_Activation::create_critical_page($critical_page);
463
-                    // REALLY? Still nothing ??!?!?
464
-                    if ($critical_page['post'] === null) {
465
-                        $msg = __(
466
-                            'The Event Espresso critical page configuration settings could not be updated.',
467
-                            'event_espresso'
468
-                        );
469
-                        EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
470
-                        break;
471
-                    }
472
-                }
473
-            }
474
-            // check that Post ID matches critical page ID in config
475
-            if (
476
-                isset($critical_page['post']->ID)
477
-                && $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
478
-            ) {
479
-                //update Config with post ID
480
-                $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
481
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
482
-                    $msg = __(
483
-                        'The Event Espresso critical page configuration settings could not be updated.',
484
-                        'event_espresso'
485
-                    );
486
-                    EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
487
-                }
488
-            }
489
-            $critical_page_problem =
490
-                ! isset($critical_page['post']->post_status)
491
-                || $critical_page['post']->post_status !== 'publish'
492
-                || strpos($critical_page['post']->post_content, $critical_page['code']) === false
493
-                    ? true
494
-                    : $critical_page_problem;
495
-        }
496
-        if ($critical_page_problem) {
497
-            new PersistentAdminNotice(
498
-                'critical_page_problem',
499
-                sprintf(
500
-                    esc_html__(
501
-                        'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
502
-                        'event_espresso'
503
-                    ),
504
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
505
-                    . __('Event Espresso Critical Pages Settings', 'event_espresso')
506
-                    . '</a>'
507
-                )
508
-            );
509
-        }
510
-        if (EE_Error::has_notices()) {
511
-            EE_Error::get_notices(false, true, true);
512
-        }
513
-    }
514
-
515
-
516
-
517
-    /**
518
-     * Returns the first post which uses the specified shortcode
519
-     *
520
-     * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
521
-     *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
522
-     *                             "[ESPRESSO_THANK_YOU"
523
-     *                             (we don't search for the closing shortcode bracket because they might have added
524
-     *                             parameter to the shortcode
525
-     * @return WP_Post or NULl
526
-     */
527
-    public static function get_page_by_ee_shortcode($ee_shortcode)
528
-    {
529
-        global $wpdb;
530
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
531
-        $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
532
-        if ($post_id) {
533
-            return get_post($post_id);
534
-        } else {
535
-            return null;
536
-        }
537
-    }
538
-
539
-
540
-    /**
541
-     *    This function generates a post for critical espresso pages
542
-     *
543
-     * @access public
544
-     * @static
545
-     * @param array $critical_page
546
-     * @return array
547
-     */
548
-    public static function create_critical_page($critical_page)
549
-    {
550
-
551
-        $post_args = array(
552
-            'post_title'     => $critical_page['name'],
553
-            'post_status'    => 'publish',
554
-            'post_type'      => 'page',
555
-            'comment_status' => 'closed',
556
-            'post_content'   => '[' . $critical_page['code'] . ']',
557
-        );
558
-
559
-        $post_id = wp_insert_post($post_args);
560
-        if (! $post_id) {
561
-            $msg = sprintf(
562
-                __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
563
-                $critical_page['name']
564
-            );
565
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
566
-            return $critical_page;
567
-        }
568
-        // get newly created post's details
569
-        if (! $critical_page['post'] = get_post($post_id)) {
570
-            $msg = sprintf(
571
-                __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
572
-                $critical_page['name']
573
-            );
574
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
575
-        }
576
-
577
-        return $critical_page;
578
-
579
-    }
580
-
581
-
582
-
583
-
584
-    /**
585
-     * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
586
-     * The role being used to check is filterable.
587
-     *
588
-     * @since  4.6.0
589
-     * @global WPDB $wpdb
590
-     * @return mixed null|int WP_user ID or NULL
591
-     */
592
-    public static function get_default_creator_id()
593
-    {
594
-        global $wpdb;
595
-        if ( ! empty(self::$_default_creator_id)) {
596
-            return self::$_default_creator_id;
597
-        }/**/
598
-        $role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
599
-        //let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
600
-        $pre_filtered_id = apply_filters(
601
-            'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
602
-            false,
603
-            $role_to_check
604
-        );
605
-        if ($pre_filtered_id !== false) {
606
-            return (int)$pre_filtered_id;
607
-        }
608
-        $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
609
-        $query = $wpdb->prepare(
610
-            "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
611
-            '%' . $role_to_check . '%'
612
-        );
613
-        $user_id = $wpdb->get_var($query);
614
-        $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
615
-        if ($user_id && (int)$user_id) {
616
-            self::$_default_creator_id = (int)$user_id;
617
-            return self::$_default_creator_id;
618
-        } else {
619
-            return null;
620
-        }
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * used by EE and EE addons during plugin activation to create tables.
627
-     * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
628
-     * but includes extra logic regarding activations.
629
-     *
630
-     * @access public
631
-     * @static
632
-     * @param string  $table_name              without the $wpdb->prefix
633
-     * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
634
-     *                                         table query)
635
-     * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
636
-     * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
637
-     *                                         and new once this function is done (ie, you really do want to CREATE a
638
-     *                                         table, and expect it to be empty once you're done) leave as FALSE when
639
-     *                                         you just want to verify the table exists and matches this definition
640
-     *                                         (and if it HAS data in it you want to leave it be)
641
-     * @return void
642
-     * @throws EE_Error if there are database errors
643
-     */
644
-    public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
645
-    {
646
-        if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
647
-            return;
648
-        }
649
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
650
-        if ( ! function_exists('dbDelta')) {
651
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
652
-        }
653
-        $tableAnalysis = \EEH_Activation::getTableAnalysis();
654
-        $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
655
-        // do we need to first delete an existing version of this table ?
656
-        if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
657
-            // ok, delete the table... but ONLY if it's empty
658
-            $deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
659
-            // table is NOT empty, are you SURE you want to delete this table ???
660
-            if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
661
-                \EEH_Activation::getTableManager()->dropTable($wp_table_name);
662
-            } else if ( ! $deleted_safely) {
663
-                // so we should be more cautious rather than just dropping tables so easily
664
-                error_log(
665
-                    sprintf(
666
-                        __(
667
-                            'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
668
-                            'event_espresso'
669
-                        ),
670
-                        $wp_table_name,
671
-                        '<br/>',
672
-                        'espresso_db_update'
673
-                    )
674
-                );
675
-            }
676
-        }
677
-        $engine = str_replace('ENGINE=', '', $engine);
678
-        \EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
679
-    }
680
-
681
-
682
-
683
-    /**
684
-     *    add_column_if_it_doesn't_exist
685
-     *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
686
-     *
687
-     * @access     public
688
-     * @static
689
-     * @deprecated instead use TableManager::addColumn()
690
-     * @param string $table_name  (without "wp_", eg "esp_attendee"
691
-     * @param string $column_name
692
-     * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
693
-     *                            'VARCHAR(10)'
694
-     * @return bool|int
695
-     */
696
-    public static function add_column_if_it_doesnt_exist(
697
-        $table_name,
698
-        $column_name,
699
-        $column_info = 'INT UNSIGNED NOT NULL'
700
-    ) {
701
-        return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
702
-    }
703
-
704
-
705
-    /**
706
-     * get_fields_on_table
707
-     * Gets all the fields on the database table.
708
-     *
709
-     * @access     public
710
-     * @deprecated instead use TableManager::getTableColumns()
711
-     * @static
712
-     * @param string $table_name , without prefixed $wpdb->prefix
713
-     * @return array of database column names
714
-     */
715
-    public static function get_fields_on_table($table_name = null)
716
-    {
717
-        return \EEH_Activation::getTableManager()->getTableColumns($table_name);
718
-    }
719
-
720
-
721
-    /**
722
-     * db_table_is_empty
723
-     *
724
-     * @access     public\
725
-     * @deprecated instead use TableAnalysis::tableIsEmpty()
726
-     * @static
727
-     * @param string $table_name
728
-     * @return bool
729
-     */
730
-    public static function db_table_is_empty($table_name)
731
-    {
732
-        return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
733
-    }
734
-
735
-
736
-    /**
737
-     * delete_db_table_if_empty
738
-     *
739
-     * @access public
740
-     * @static
741
-     * @param string $table_name
742
-     * @return bool | int
743
-     */
744
-    public static function delete_db_table_if_empty($table_name)
745
-    {
746
-        if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
747
-            return \EEH_Activation::getTableManager()->dropTable($table_name);
748
-        }
749
-        return false;
750
-    }
751
-
752
-
753
-    /**
754
-     * delete_unused_db_table
755
-     *
756
-     * @access     public
757
-     * @static
758
-     * @deprecated instead use TableManager::dropTable()
759
-     * @param string $table_name
760
-     * @return bool | int
761
-     */
762
-    public static function delete_unused_db_table($table_name)
763
-    {
764
-        return \EEH_Activation::getTableManager()->dropTable($table_name);
765
-    }
766
-
767
-
768
-    /**
769
-     * drop_index
770
-     *
771
-     * @access     public
772
-     * @static
773
-     * @deprecated instead use TableManager::dropIndex()
774
-     * @param string $table_name
775
-     * @param string $index_name
776
-     * @return bool | int
777
-     */
778
-    public static function drop_index($table_name, $index_name)
779
-    {
780
-        return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
781
-    }
782
-
783
-
784
-
785
-    /**
786
-     * create_database_tables
787
-     *
788
-     * @access public
789
-     * @static
790
-     * @throws EE_Error
791
-     * @return boolean success (whether database is setup properly or not)
792
-     */
793
-    public static function create_database_tables()
794
-    {
795
-        EE_Registry::instance()->load_core('Data_Migration_Manager');
796
-        //find the migration script that sets the database to be compatible with the code
797
-        $dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
798
-        if ($dms_name) {
799
-            $current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
800
-            $current_data_migration_script->set_migrating(false);
801
-            $current_data_migration_script->schema_changes_before_migration();
802
-            $current_data_migration_script->schema_changes_after_migration();
803
-            if ($current_data_migration_script->get_errors()) {
804
-                if (WP_DEBUG) {
805
-                    foreach ($current_data_migration_script->get_errors() as $error) {
806
-                        EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
807
-                    }
808
-                } else {
809
-                    EE_Error::add_error(
810
-                        __(
811
-                            'There were errors creating the Event Espresso database tables and Event Espresso has been 
264
+		$ee_cron_tasks_to_remove = EEH_Activation::get_cron_tasks($cron_tasks_to_remove);
265
+		foreach ($crons as $timestamp => $hooks_to_fire_at_time) {
266
+			if (is_array($hooks_to_fire_at_time)) {
267
+				foreach ($hooks_to_fire_at_time as $hook_name => $hook_actions) {
268
+					if (isset($ee_cron_tasks_to_remove[$hook_name])
269
+						&& is_array($ee_cron_tasks_to_remove[$hook_name])
270
+					) {
271
+						unset($crons[$timestamp][$hook_name]);
272
+					}
273
+				}
274
+				//also take care of any empty cron timestamps.
275
+				if (empty($hooks_to_fire_at_time)) {
276
+					unset($crons[$timestamp]);
277
+				}
278
+			}
279
+		}
280
+		_set_cron_array($crons);
281
+	}
282
+
283
+
284
+	/**
285
+	 *    CPT_initialization
286
+	 *    registers all EE CPTs ( Custom Post Types ) then flushes rewrite rules so that all endpoints exist
287
+	 *
288
+	 * @access public
289
+	 * @static
290
+	 * @return void
291
+	 */
292
+	public static function CPT_initialization()
293
+	{
294
+		// register Custom Post Types
295
+		EE_Registry::instance()->load_core('Register_CPTs');
296
+		flush_rewrite_rules();
297
+	}
298
+
299
+
300
+
301
+	/**
302
+	 *    reset_and_update_config
303
+	 * The following code was moved over from EE_Config so that it will no longer run on every request.
304
+	 * If there is old calendar config data saved, then it will get converted on activation.
305
+	 * This was basically a DMS before we had DMS's, and will get removed after a few more versions.
306
+	 *
307
+	 * @access public
308
+	 * @static
309
+	 * @return void
310
+	 */
311
+	public static function reset_and_update_config()
312
+	{
313
+		do_action('AHEE__EE_Config___load_core_config__start', array('EEH_Activation', 'load_calendar_config'));
314
+		add_filter(
315
+			'FHEE__EE_Config___load_core_config__config_settings',
316
+			array('EEH_Activation', 'migrate_old_config_data'),
317
+			10,
318
+			3
319
+		);
320
+		//EE_Config::reset();
321
+		if (! EE_Config::logging_enabled()) {
322
+			delete_option(EE_Config::LOG_NAME);
323
+		}
324
+	}
325
+
326
+
327
+	/**
328
+	 *    load_calendar_config
329
+	 *
330
+	 * @access    public
331
+	 * @return    void
332
+	 */
333
+	public static function load_calendar_config()
334
+	{
335
+		// grab array of all plugin folders and loop thru it
336
+		$plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
337
+		if (empty($plugins)) {
338
+			return;
339
+		}
340
+		foreach ($plugins as $plugin_path) {
341
+			// grab plugin folder name from path
342
+			$plugin = basename($plugin_path);
343
+			// drill down to Espresso plugins
344
+			// then to calendar related plugins
345
+			if (
346
+				strpos($plugin, 'espresso') !== false
347
+				|| strpos($plugin, 'Espresso') !== false
348
+				|| strpos($plugin, 'ee4') !== false
349
+				|| strpos($plugin, 'EE4') !== false
350
+				|| strpos($plugin, 'calendar') !== false
351
+			) {
352
+				// this is what we are looking for
353
+				$calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
354
+				// does it exist in this folder ?
355
+				if (is_readable($calendar_config)) {
356
+					// YEAH! let's load it
357
+					require_once($calendar_config);
358
+				}
359
+			}
360
+		}
361
+	}
362
+
363
+
364
+
365
+	/**
366
+	 *    _migrate_old_config_data
367
+	 *
368
+	 * @access    public
369
+	 * @param array|stdClass $settings
370
+	 * @param string         $config
371
+	 * @param \EE_Config     $EE_Config
372
+	 * @return \stdClass
373
+	 */
374
+	public static function migrate_old_config_data($settings = array(), $config = '', EE_Config $EE_Config)
375
+	{
376
+		$convert_from_array = array('addons');
377
+		// in case old settings were saved as an array
378
+		if (is_array($settings) && in_array($config, $convert_from_array)) {
379
+			// convert existing settings to an object
380
+			$config_array = $settings;
381
+			$settings = new stdClass();
382
+			foreach ($config_array as $key => $value) {
383
+				if ($key === 'calendar' && class_exists('EE_Calendar_Config')) {
384
+					$EE_Config->set_config('addons', 'EE_Calendar', 'EE_Calendar_Config', $value);
385
+				} else {
386
+					$settings->{$key} = $value;
387
+				}
388
+			}
389
+			add_filter('FHEE__EE_Config___load_core_config__update_espresso_config', '__return_true');
390
+		}
391
+		return $settings;
392
+	}
393
+
394
+
395
+	/**
396
+	 * deactivate_event_espresso
397
+	 *
398
+	 * @access public
399
+	 * @static
400
+	 * @return void
401
+	 */
402
+	public static function deactivate_event_espresso()
403
+	{
404
+		// check permissions
405
+		if (current_user_can('activate_plugins')) {
406
+			deactivate_plugins(EE_PLUGIN_BASENAME, true);
407
+		}
408
+	}
409
+
410
+
411
+
412
+	/**
413
+	 * verify_default_pages_exist
414
+	 *
415
+	 * @access public
416
+	 * @static
417
+	 * @return void
418
+	 * @throws InvalidDataTypeException
419
+	 */
420
+	public static function verify_default_pages_exist()
421
+	{
422
+		$critical_page_problem = false;
423
+		$critical_pages = array(
424
+			array(
425
+				'id'   => 'reg_page_id',
426
+				'name' => __('Registration Checkout', 'event_espresso'),
427
+				'post' => null,
428
+				'code' => 'ESPRESSO_CHECKOUT',
429
+			),
430
+			array(
431
+				'id'   => 'txn_page_id',
432
+				'name' => __('Transactions', 'event_espresso'),
433
+				'post' => null,
434
+				'code' => 'ESPRESSO_TXN_PAGE',
435
+			),
436
+			array(
437
+				'id'   => 'thank_you_page_id',
438
+				'name' => __('Thank You', 'event_espresso'),
439
+				'post' => null,
440
+				'code' => 'ESPRESSO_THANK_YOU',
441
+			),
442
+			array(
443
+				'id'   => 'cancel_page_id',
444
+				'name' => __('Registration Cancelled', 'event_espresso'),
445
+				'post' => null,
446
+				'code' => 'ESPRESSO_CANCELLED',
447
+			),
448
+		);
449
+		$EE_Core_Config = EE_Registry::instance()->CFG->core;
450
+		foreach ($critical_pages as $critical_page) {
451
+			// is critical page ID set in config ?
452
+			if ($EE_Core_Config->{$critical_page['id']} !== false) {
453
+				// attempt to find post by ID
454
+				$critical_page['post'] = get_post($EE_Core_Config->{$critical_page['id']});
455
+			}
456
+			// no dice?
457
+			if ($critical_page['post'] === null) {
458
+				// attempt to find post by title
459
+				$critical_page['post'] = self::get_page_by_ee_shortcode($critical_page['code']);
460
+				// still nothing?
461
+				if ($critical_page['post'] === null) {
462
+					$critical_page = EEH_Activation::create_critical_page($critical_page);
463
+					// REALLY? Still nothing ??!?!?
464
+					if ($critical_page['post'] === null) {
465
+						$msg = __(
466
+							'The Event Espresso critical page configuration settings could not be updated.',
467
+							'event_espresso'
468
+						);
469
+						EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
470
+						break;
471
+					}
472
+				}
473
+			}
474
+			// check that Post ID matches critical page ID in config
475
+			if (
476
+				isset($critical_page['post']->ID)
477
+				&& $critical_page['post']->ID !== $EE_Core_Config->{$critical_page['id']}
478
+			) {
479
+				//update Config with post ID
480
+				$EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
481
+				if (! EE_Config::instance()->update_espresso_config(false, false)) {
482
+					$msg = __(
483
+						'The Event Espresso critical page configuration settings could not be updated.',
484
+						'event_espresso'
485
+					);
486
+					EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
487
+				}
488
+			}
489
+			$critical_page_problem =
490
+				! isset($critical_page['post']->post_status)
491
+				|| $critical_page['post']->post_status !== 'publish'
492
+				|| strpos($critical_page['post']->post_content, $critical_page['code']) === false
493
+					? true
494
+					: $critical_page_problem;
495
+		}
496
+		if ($critical_page_problem) {
497
+			new PersistentAdminNotice(
498
+				'critical_page_problem',
499
+				sprintf(
500
+					esc_html__(
501
+						'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
502
+						'event_espresso'
503
+					),
504
+					'<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
505
+					. __('Event Espresso Critical Pages Settings', 'event_espresso')
506
+					. '</a>'
507
+				)
508
+			);
509
+		}
510
+		if (EE_Error::has_notices()) {
511
+			EE_Error::get_notices(false, true, true);
512
+		}
513
+	}
514
+
515
+
516
+
517
+	/**
518
+	 * Returns the first post which uses the specified shortcode
519
+	 *
520
+	 * @param string $ee_shortcode usually one of the critical pages shortcodes, eg
521
+	 *                             ESPRESSO_THANK_YOU. So we will search fora post with the content
522
+	 *                             "[ESPRESSO_THANK_YOU"
523
+	 *                             (we don't search for the closing shortcode bracket because they might have added
524
+	 *                             parameter to the shortcode
525
+	 * @return WP_Post or NULl
526
+	 */
527
+	public static function get_page_by_ee_shortcode($ee_shortcode)
528
+	{
529
+		global $wpdb;
530
+		$shortcode_and_opening_bracket = '[' . $ee_shortcode;
531
+		$post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
532
+		if ($post_id) {
533
+			return get_post($post_id);
534
+		} else {
535
+			return null;
536
+		}
537
+	}
538
+
539
+
540
+	/**
541
+	 *    This function generates a post for critical espresso pages
542
+	 *
543
+	 * @access public
544
+	 * @static
545
+	 * @param array $critical_page
546
+	 * @return array
547
+	 */
548
+	public static function create_critical_page($critical_page)
549
+	{
550
+
551
+		$post_args = array(
552
+			'post_title'     => $critical_page['name'],
553
+			'post_status'    => 'publish',
554
+			'post_type'      => 'page',
555
+			'comment_status' => 'closed',
556
+			'post_content'   => '[' . $critical_page['code'] . ']',
557
+		);
558
+
559
+		$post_id = wp_insert_post($post_args);
560
+		if (! $post_id) {
561
+			$msg = sprintf(
562
+				__('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
563
+				$critical_page['name']
564
+			);
565
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
566
+			return $critical_page;
567
+		}
568
+		// get newly created post's details
569
+		if (! $critical_page['post'] = get_post($post_id)) {
570
+			$msg = sprintf(
571
+				__('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
572
+				$critical_page['name']
573
+			);
574
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
575
+		}
576
+
577
+		return $critical_page;
578
+
579
+	}
580
+
581
+
582
+
583
+
584
+	/**
585
+	 * Tries to find the oldest admin for this site.  If there are no admins for this site then return NULL.
586
+	 * The role being used to check is filterable.
587
+	 *
588
+	 * @since  4.6.0
589
+	 * @global WPDB $wpdb
590
+	 * @return mixed null|int WP_user ID or NULL
591
+	 */
592
+	public static function get_default_creator_id()
593
+	{
594
+		global $wpdb;
595
+		if ( ! empty(self::$_default_creator_id)) {
596
+			return self::$_default_creator_id;
597
+		}/**/
598
+		$role_to_check = apply_filters('FHEE__EEH_Activation__get_default_creator_id__role_to_check', 'administrator');
599
+		//let's allow pre_filtering for early exits by alternative methods for getting id.  We check for truthy result and if so then exit early.
600
+		$pre_filtered_id = apply_filters(
601
+			'FHEE__EEH_Activation__get_default_creator_id__pre_filtered_id',
602
+			false,
603
+			$role_to_check
604
+		);
605
+		if ($pre_filtered_id !== false) {
606
+			return (int)$pre_filtered_id;
607
+		}
608
+		$capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
609
+		$query = $wpdb->prepare(
610
+			"SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
611
+			'%' . $role_to_check . '%'
612
+		);
613
+		$user_id = $wpdb->get_var($query);
614
+		$user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
615
+		if ($user_id && (int)$user_id) {
616
+			self::$_default_creator_id = (int)$user_id;
617
+			return self::$_default_creator_id;
618
+		} else {
619
+			return null;
620
+		}
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * used by EE and EE addons during plugin activation to create tables.
627
+	 * Its a wrapper for EventEspresso\core\services\database\TableManager::createTable,
628
+	 * but includes extra logic regarding activations.
629
+	 *
630
+	 * @access public
631
+	 * @static
632
+	 * @param string  $table_name              without the $wpdb->prefix
633
+	 * @param string  $sql                     SQL for creating the table (contents between brackets in an SQL create
634
+	 *                                         table query)
635
+	 * @param string  $engine                  like 'ENGINE=MyISAM' or 'ENGINE=InnoDB'
636
+	 * @param boolean $drop_pre_existing_table set to TRUE when you want to make SURE the table is completely empty
637
+	 *                                         and new once this function is done (ie, you really do want to CREATE a
638
+	 *                                         table, and expect it to be empty once you're done) leave as FALSE when
639
+	 *                                         you just want to verify the table exists and matches this definition
640
+	 *                                         (and if it HAS data in it you want to leave it be)
641
+	 * @return void
642
+	 * @throws EE_Error if there are database errors
643
+	 */
644
+	public static function create_table($table_name, $sql, $engine = 'ENGINE=MyISAM ', $drop_pre_existing_table = false)
645
+	{
646
+		if (apply_filters('FHEE__EEH_Activation__create_table__short_circuit', false, $table_name, $sql)) {
647
+			return;
648
+		}
649
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
650
+		if ( ! function_exists('dbDelta')) {
651
+			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
652
+		}
653
+		$tableAnalysis = \EEH_Activation::getTableAnalysis();
654
+		$wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
655
+		// do we need to first delete an existing version of this table ?
656
+		if ($drop_pre_existing_table && $tableAnalysis->tableExists($wp_table_name)) {
657
+			// ok, delete the table... but ONLY if it's empty
658
+			$deleted_safely = EEH_Activation::delete_db_table_if_empty($wp_table_name);
659
+			// table is NOT empty, are you SURE you want to delete this table ???
660
+			if ( ! $deleted_safely && defined('EE_DROP_BAD_TABLES') && EE_DROP_BAD_TABLES) {
661
+				\EEH_Activation::getTableManager()->dropTable($wp_table_name);
662
+			} else if ( ! $deleted_safely) {
663
+				// so we should be more cautious rather than just dropping tables so easily
664
+				error_log(
665
+					sprintf(
666
+						__(
667
+							'It appears that database table "%1$s" exists when it shouldn\'t, and therefore may contain erroneous data. If you have previously restored your database from a backup that didn\'t remove the old tables, then we recommend: %2$s 1. create a new COMPLETE backup of your database, %2$s 2. delete ALL tables from your database, %2$s 3. restore to your previous backup. %2$s If, however, you have not restored to a backup, then somehow your "%3$s" WordPress option could not be read. You can probably ignore this message, but should investigate why that option is being removed.',
668
+							'event_espresso'
669
+						),
670
+						$wp_table_name,
671
+						'<br/>',
672
+						'espresso_db_update'
673
+					)
674
+				);
675
+			}
676
+		}
677
+		$engine = str_replace('ENGINE=', '', $engine);
678
+		\EEH_Activation::getTableManager()->createTable($table_name, $sql, $engine);
679
+	}
680
+
681
+
682
+
683
+	/**
684
+	 *    add_column_if_it_doesn't_exist
685
+	 *    Checks if this column already exists on the specified table. Handy for addons which want to add a column
686
+	 *
687
+	 * @access     public
688
+	 * @static
689
+	 * @deprecated instead use TableManager::addColumn()
690
+	 * @param string $table_name  (without "wp_", eg "esp_attendee"
691
+	 * @param string $column_name
692
+	 * @param string $column_info if your SQL were 'ALTER TABLE table_name ADD price VARCHAR(10)', this would be
693
+	 *                            'VARCHAR(10)'
694
+	 * @return bool|int
695
+	 */
696
+	public static function add_column_if_it_doesnt_exist(
697
+		$table_name,
698
+		$column_name,
699
+		$column_info = 'INT UNSIGNED NOT NULL'
700
+	) {
701
+		return \EEH_Activation::getTableManager()->addColumn($table_name, $column_name, $column_info);
702
+	}
703
+
704
+
705
+	/**
706
+	 * get_fields_on_table
707
+	 * Gets all the fields on the database table.
708
+	 *
709
+	 * @access     public
710
+	 * @deprecated instead use TableManager::getTableColumns()
711
+	 * @static
712
+	 * @param string $table_name , without prefixed $wpdb->prefix
713
+	 * @return array of database column names
714
+	 */
715
+	public static function get_fields_on_table($table_name = null)
716
+	{
717
+		return \EEH_Activation::getTableManager()->getTableColumns($table_name);
718
+	}
719
+
720
+
721
+	/**
722
+	 * db_table_is_empty
723
+	 *
724
+	 * @access     public\
725
+	 * @deprecated instead use TableAnalysis::tableIsEmpty()
726
+	 * @static
727
+	 * @param string $table_name
728
+	 * @return bool
729
+	 */
730
+	public static function db_table_is_empty($table_name)
731
+	{
732
+		return \EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name);
733
+	}
734
+
735
+
736
+	/**
737
+	 * delete_db_table_if_empty
738
+	 *
739
+	 * @access public
740
+	 * @static
741
+	 * @param string $table_name
742
+	 * @return bool | int
743
+	 */
744
+	public static function delete_db_table_if_empty($table_name)
745
+	{
746
+		if (\EEH_Activation::getTableAnalysis()->tableIsEmpty($table_name)) {
747
+			return \EEH_Activation::getTableManager()->dropTable($table_name);
748
+		}
749
+		return false;
750
+	}
751
+
752
+
753
+	/**
754
+	 * delete_unused_db_table
755
+	 *
756
+	 * @access     public
757
+	 * @static
758
+	 * @deprecated instead use TableManager::dropTable()
759
+	 * @param string $table_name
760
+	 * @return bool | int
761
+	 */
762
+	public static function delete_unused_db_table($table_name)
763
+	{
764
+		return \EEH_Activation::getTableManager()->dropTable($table_name);
765
+	}
766
+
767
+
768
+	/**
769
+	 * drop_index
770
+	 *
771
+	 * @access     public
772
+	 * @static
773
+	 * @deprecated instead use TableManager::dropIndex()
774
+	 * @param string $table_name
775
+	 * @param string $index_name
776
+	 * @return bool | int
777
+	 */
778
+	public static function drop_index($table_name, $index_name)
779
+	{
780
+		return \EEH_Activation::getTableManager()->dropIndex($table_name, $index_name);
781
+	}
782
+
783
+
784
+
785
+	/**
786
+	 * create_database_tables
787
+	 *
788
+	 * @access public
789
+	 * @static
790
+	 * @throws EE_Error
791
+	 * @return boolean success (whether database is setup properly or not)
792
+	 */
793
+	public static function create_database_tables()
794
+	{
795
+		EE_Registry::instance()->load_core('Data_Migration_Manager');
796
+		//find the migration script that sets the database to be compatible with the code
797
+		$dms_name = EE_Data_Migration_Manager::instance()->get_most_up_to_date_dms();
798
+		if ($dms_name) {
799
+			$current_data_migration_script = EE_Registry::instance()->load_dms($dms_name);
800
+			$current_data_migration_script->set_migrating(false);
801
+			$current_data_migration_script->schema_changes_before_migration();
802
+			$current_data_migration_script->schema_changes_after_migration();
803
+			if ($current_data_migration_script->get_errors()) {
804
+				if (WP_DEBUG) {
805
+					foreach ($current_data_migration_script->get_errors() as $error) {
806
+						EE_Error::add_error($error, __FILE__, __FUNCTION__, __LINE__);
807
+					}
808
+				} else {
809
+					EE_Error::add_error(
810
+						__(
811
+							'There were errors creating the Event Espresso database tables and Event Espresso has been 
812 812
                             deactivated. To view the errors, please enable WP_DEBUG in your wp-config.php file.',
813
-                            'event_espresso'
814
-                        )
815
-                    );
816
-                }
817
-                return false;
818
-            }
819
-            EE_Data_Migration_Manager::instance()->update_current_database_state_to();
820
-        } else {
821
-            EE_Error::add_error(
822
-                __(
823
-                    'Could not determine most up-to-date data migration script from which to pull database schema
813
+							'event_espresso'
814
+						)
815
+					);
816
+				}
817
+				return false;
818
+			}
819
+			EE_Data_Migration_Manager::instance()->update_current_database_state_to();
820
+		} else {
821
+			EE_Error::add_error(
822
+				__(
823
+					'Could not determine most up-to-date data migration script from which to pull database schema
824 824
                      structure. So database is probably not setup properly',
825
-                    'event_espresso'
826
-                ),
827
-                __FILE__,
828
-                __FUNCTION__,
829
-                __LINE__
830
-            );
831
-            return false;
832
-        }
833
-        return true;
834
-    }
835
-
836
-
837
-
838
-    /**
839
-     * initialize_system_questions
840
-     *
841
-     * @access public
842
-     * @static
843
-     * @return void
844
-     */
845
-    public static function initialize_system_questions()
846
-    {
847
-        // QUESTION GROUPS
848
-        global $wpdb;
849
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
850
-        $SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
851
-        // what we have
852
-        $question_groups = $wpdb->get_col($SQL);
853
-        // check the response
854
-        $question_groups = is_array($question_groups) ? $question_groups : array();
855
-        // what we should have
856
-        $QSG_systems = array(1, 2);
857
-        // loop thru what we should have and compare to what we have
858
-        foreach ($QSG_systems as $QSG_system) {
859
-            // reset values array
860
-            $QSG_values = array();
861
-            // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
862
-            if (! in_array("$QSG_system", $question_groups)) {
863
-                // add it
864
-                switch ($QSG_system) {
865
-                    case 1:
866
-                        $QSG_values = array(
867
-                            'QSG_name'            => __('Personal Information', 'event_espresso'),
868
-                            'QSG_identifier'      => 'personal-information-' . time(),
869
-                            'QSG_desc'            => '',
870
-                            'QSG_order'           => 1,
871
-                            'QSG_show_group_name' => 1,
872
-                            'QSG_show_group_desc' => 1,
873
-                            'QSG_system'          => EEM_Question_Group::system_personal,
874
-                            'QSG_deleted'         => 0,
875
-                        );
876
-                        break;
877
-                    case 2:
878
-                        $QSG_values = array(
879
-                            'QSG_name'            => __('Address Information', 'event_espresso'),
880
-                            'QSG_identifier'      => 'address-information-' . time(),
881
-                            'QSG_desc'            => '',
882
-                            'QSG_order'           => 2,
883
-                            'QSG_show_group_name' => 1,
884
-                            'QSG_show_group_desc' => 1,
885
-                            'QSG_system'          => EEM_Question_Group::system_address,
886
-                            'QSG_deleted'         => 0,
887
-                        );
888
-                        break;
889
-                }
890
-                // make sure we have some values before inserting them
891
-                if (! empty($QSG_values)) {
892
-                    // insert system question
893
-                    $wpdb->insert(
894
-                        $table_name,
895
-                        $QSG_values,
896
-                        array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
897
-                    );
898
-                    $QSG_IDs[$QSG_system] = $wpdb->insert_id;
899
-                }
900
-            }
901
-        }
902
-        // QUESTIONS
903
-        global $wpdb;
904
-        $table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
905
-        $SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
906
-        // what we have
907
-        $questions = $wpdb->get_col($SQL);
908
-        // what we should have
909
-        $QST_systems = array(
910
-            'fname',
911
-            'lname',
912
-            'email',
913
-            'address',
914
-            'address2',
915
-            'city',
916
-            'country',
917
-            'state',
918
-            'zip',
919
-            'phone',
920
-        );
921
-        $order_for_group_1 = 1;
922
-        $order_for_group_2 = 1;
923
-        // loop thru what we should have and compare to what we have
924
-        foreach ($QST_systems as $QST_system) {
925
-            // reset values array
926
-            $QST_values = array();
927
-            // if we don't have what we should have
928
-            if (! in_array($QST_system, $questions)) {
929
-                // add it
930
-                switch ($QST_system) {
931
-                    case 'fname':
932
-                        $QST_values = array(
933
-                            'QST_display_text'  => __('First Name', 'event_espresso'),
934
-                            'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
935
-                            'QST_system'        => 'fname',
936
-                            'QST_type'          => 'TEXT',
937
-                            'QST_required'      => 1,
938
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
939
-                            'QST_order'         => 1,
940
-                            'QST_admin_only'    => 0,
941
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
942
-                            'QST_wp_user'       => self::get_default_creator_id(),
943
-                            'QST_deleted'       => 0,
944
-                        );
945
-                        break;
946
-                    case 'lname':
947
-                        $QST_values = array(
948
-                            'QST_display_text'  => __('Last Name', 'event_espresso'),
949
-                            'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
950
-                            'QST_system'        => 'lname',
951
-                            'QST_type'          => 'TEXT',
952
-                            'QST_required'      => 1,
953
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
954
-                            'QST_order'         => 2,
955
-                            'QST_admin_only'    => 0,
956
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
957
-                            'QST_wp_user'       => self::get_default_creator_id(),
958
-                            'QST_deleted'       => 0,
959
-                        );
960
-                        break;
961
-                    case 'email':
962
-                        $QST_values = array(
963
-                            'QST_display_text'  => __('Email Address', 'event_espresso'),
964
-                            'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
965
-                            'QST_system'        => 'email',
966
-                            'QST_type'          => 'EMAIL',
967
-                            'QST_required'      => 1,
968
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
969
-                            'QST_order'         => 3,
970
-                            'QST_admin_only'    => 0,
971
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
972
-                            'QST_wp_user'       => self::get_default_creator_id(),
973
-                            'QST_deleted'       => 0,
974
-                        );
975
-                        break;
976
-                    case 'address':
977
-                        $QST_values = array(
978
-                            'QST_display_text'  => __('Address', 'event_espresso'),
979
-                            'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
980
-                            'QST_system'        => 'address',
981
-                            'QST_type'          => 'TEXT',
982
-                            'QST_required'      => 0,
983
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
984
-                            'QST_order'         => 4,
985
-                            'QST_admin_only'    => 0,
986
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
987
-                            'QST_wp_user'       => self::get_default_creator_id(),
988
-                            'QST_deleted'       => 0,
989
-                        );
990
-                        break;
991
-                    case 'address2':
992
-                        $QST_values = array(
993
-                            'QST_display_text'  => __('Address2', 'event_espresso'),
994
-                            'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
995
-                            'QST_system'        => 'address2',
996
-                            'QST_type'          => 'TEXT',
997
-                            'QST_required'      => 0,
998
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
999
-                            'QST_order'         => 5,
1000
-                            'QST_admin_only'    => 0,
1001
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1002
-                            'QST_wp_user'       => self::get_default_creator_id(),
1003
-                            'QST_deleted'       => 0,
1004
-                        );
1005
-                        break;
1006
-                    case 'city':
1007
-                        $QST_values = array(
1008
-                            'QST_display_text'  => __('City', 'event_espresso'),
1009
-                            'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1010
-                            'QST_system'        => 'city',
1011
-                            'QST_type'          => 'TEXT',
1012
-                            'QST_required'      => 0,
1013
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1014
-                            'QST_order'         => 6,
1015
-                            'QST_admin_only'    => 0,
1016
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1017
-                            'QST_wp_user'       => self::get_default_creator_id(),
1018
-                            'QST_deleted'       => 0,
1019
-                        );
1020
-                        break;
1021
-                    case 'country':
1022
-                        $QST_values = array(
1023
-                            'QST_display_text'  => __('Country', 'event_espresso'),
1024
-                            'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1025
-                            'QST_system'        => 'country',
1026
-                            'QST_type'          => 'COUNTRY',
1027
-                            'QST_required'      => 0,
1028
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1029
-                            'QST_order'         => 7,
1030
-                            'QST_admin_only'    => 0,
1031
-                            'QST_wp_user'       => self::get_default_creator_id(),
1032
-                            'QST_deleted'       => 0,
1033
-                        );
1034
-                        break;
1035
-                    case 'state':
1036
-                        $QST_values = array(
1037
-                            'QST_display_text'  => __('State/Province', 'event_espresso'),
1038
-                            'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1039
-                            'QST_system'        => 'state',
1040
-                            'QST_type'          => 'STATE',
1041
-                            'QST_required'      => 0,
1042
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1043
-                            'QST_order'         => 8,
1044
-                            'QST_admin_only'    => 0,
1045
-                            'QST_wp_user'       => self::get_default_creator_id(),
1046
-                            'QST_deleted'       => 0,
1047
-                        );
1048
-                        break;
1049
-                    case 'zip':
1050
-                        $QST_values = array(
1051
-                            'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1052
-                            'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1053
-                            'QST_system'        => 'zip',
1054
-                            'QST_type'          => 'TEXT',
1055
-                            'QST_required'      => 0,
1056
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1057
-                            'QST_order'         => 9,
1058
-                            'QST_admin_only'    => 0,
1059
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1060
-                            'QST_wp_user'       => self::get_default_creator_id(),
1061
-                            'QST_deleted'       => 0,
1062
-                        );
1063
-                        break;
1064
-                    case 'phone':
1065
-                        $QST_values = array(
1066
-                            'QST_display_text'  => __('Phone Number', 'event_espresso'),
1067
-                            'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1068
-                            'QST_system'        => 'phone',
1069
-                            'QST_type'          => 'TEXT',
1070
-                            'QST_required'      => 0,
1071
-                            'QST_required_text' => __('This field is required', 'event_espresso'),
1072
-                            'QST_order'         => 10,
1073
-                            'QST_admin_only'    => 0,
1074
-                            'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1075
-                            'QST_wp_user'       => self::get_default_creator_id(),
1076
-                            'QST_deleted'       => 0,
1077
-                        );
1078
-                        break;
1079
-                }
1080
-                if (! empty($QST_values)) {
1081
-                    // insert system question
1082
-                    $wpdb->insert(
1083
-                        $table_name,
1084
-                        $QST_values,
1085
-                        array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1086
-                    );
1087
-                    $QST_ID = $wpdb->insert_id;
1088
-                    // QUESTION GROUP QUESTIONS
1089
-                    if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1090
-                        $system_question_we_want = EEM_Question_Group::system_personal;
1091
-                    } else {
1092
-                        $system_question_we_want = EEM_Question_Group::system_address;
1093
-                    }
1094
-                    if (isset($QSG_IDs[$system_question_we_want])) {
1095
-                        $QSG_ID = $QSG_IDs[$system_question_we_want];
1096
-                    } else {
1097
-                        $id_col = EEM_Question_Group::instance()
1098
-                                                    ->get_col(array(array('QSG_system' => $system_question_we_want)));
1099
-                        if (is_array($id_col)) {
1100
-                            $QSG_ID = reset($id_col);
1101
-                        } else {
1102
-                            //ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1103
-                            EE_Log::instance()->log(
1104
-                                __FILE__,
1105
-                                __FUNCTION__,
1106
-                                sprintf(
1107
-                                    __(
1108
-                                        'Could not associate question %1$s to a question group because no system question
825
+					'event_espresso'
826
+				),
827
+				__FILE__,
828
+				__FUNCTION__,
829
+				__LINE__
830
+			);
831
+			return false;
832
+		}
833
+		return true;
834
+	}
835
+
836
+
837
+
838
+	/**
839
+	 * initialize_system_questions
840
+	 *
841
+	 * @access public
842
+	 * @static
843
+	 * @return void
844
+	 */
845
+	public static function initialize_system_questions()
846
+	{
847
+		// QUESTION GROUPS
848
+		global $wpdb;
849
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group');
850
+		$SQL = "SELECT QSG_system FROM $table_name WHERE QSG_system != 0";
851
+		// what we have
852
+		$question_groups = $wpdb->get_col($SQL);
853
+		// check the response
854
+		$question_groups = is_array($question_groups) ? $question_groups : array();
855
+		// what we should have
856
+		$QSG_systems = array(1, 2);
857
+		// loop thru what we should have and compare to what we have
858
+		foreach ($QSG_systems as $QSG_system) {
859
+			// reset values array
860
+			$QSG_values = array();
861
+			// if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
862
+			if (! in_array("$QSG_system", $question_groups)) {
863
+				// add it
864
+				switch ($QSG_system) {
865
+					case 1:
866
+						$QSG_values = array(
867
+							'QSG_name'            => __('Personal Information', 'event_espresso'),
868
+							'QSG_identifier'      => 'personal-information-' . time(),
869
+							'QSG_desc'            => '',
870
+							'QSG_order'           => 1,
871
+							'QSG_show_group_name' => 1,
872
+							'QSG_show_group_desc' => 1,
873
+							'QSG_system'          => EEM_Question_Group::system_personal,
874
+							'QSG_deleted'         => 0,
875
+						);
876
+						break;
877
+					case 2:
878
+						$QSG_values = array(
879
+							'QSG_name'            => __('Address Information', 'event_espresso'),
880
+							'QSG_identifier'      => 'address-information-' . time(),
881
+							'QSG_desc'            => '',
882
+							'QSG_order'           => 2,
883
+							'QSG_show_group_name' => 1,
884
+							'QSG_show_group_desc' => 1,
885
+							'QSG_system'          => EEM_Question_Group::system_address,
886
+							'QSG_deleted'         => 0,
887
+						);
888
+						break;
889
+				}
890
+				// make sure we have some values before inserting them
891
+				if (! empty($QSG_values)) {
892
+					// insert system question
893
+					$wpdb->insert(
894
+						$table_name,
895
+						$QSG_values,
896
+						array('%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d')
897
+					);
898
+					$QSG_IDs[$QSG_system] = $wpdb->insert_id;
899
+				}
900
+			}
901
+		}
902
+		// QUESTIONS
903
+		global $wpdb;
904
+		$table_name = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question');
905
+		$SQL = "SELECT QST_system FROM $table_name WHERE QST_system != ''";
906
+		// what we have
907
+		$questions = $wpdb->get_col($SQL);
908
+		// what we should have
909
+		$QST_systems = array(
910
+			'fname',
911
+			'lname',
912
+			'email',
913
+			'address',
914
+			'address2',
915
+			'city',
916
+			'country',
917
+			'state',
918
+			'zip',
919
+			'phone',
920
+		);
921
+		$order_for_group_1 = 1;
922
+		$order_for_group_2 = 1;
923
+		// loop thru what we should have and compare to what we have
924
+		foreach ($QST_systems as $QST_system) {
925
+			// reset values array
926
+			$QST_values = array();
927
+			// if we don't have what we should have
928
+			if (! in_array($QST_system, $questions)) {
929
+				// add it
930
+				switch ($QST_system) {
931
+					case 'fname':
932
+						$QST_values = array(
933
+							'QST_display_text'  => __('First Name', 'event_espresso'),
934
+							'QST_admin_label'   => __('First Name - System Question', 'event_espresso'),
935
+							'QST_system'        => 'fname',
936
+							'QST_type'          => 'TEXT',
937
+							'QST_required'      => 1,
938
+							'QST_required_text' => __('This field is required', 'event_espresso'),
939
+							'QST_order'         => 1,
940
+							'QST_admin_only'    => 0,
941
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
942
+							'QST_wp_user'       => self::get_default_creator_id(),
943
+							'QST_deleted'       => 0,
944
+						);
945
+						break;
946
+					case 'lname':
947
+						$QST_values = array(
948
+							'QST_display_text'  => __('Last Name', 'event_espresso'),
949
+							'QST_admin_label'   => __('Last Name - System Question', 'event_espresso'),
950
+							'QST_system'        => 'lname',
951
+							'QST_type'          => 'TEXT',
952
+							'QST_required'      => 1,
953
+							'QST_required_text' => __('This field is required', 'event_espresso'),
954
+							'QST_order'         => 2,
955
+							'QST_admin_only'    => 0,
956
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
957
+							'QST_wp_user'       => self::get_default_creator_id(),
958
+							'QST_deleted'       => 0,
959
+						);
960
+						break;
961
+					case 'email':
962
+						$QST_values = array(
963
+							'QST_display_text'  => __('Email Address', 'event_espresso'),
964
+							'QST_admin_label'   => __('Email Address - System Question', 'event_espresso'),
965
+							'QST_system'        => 'email',
966
+							'QST_type'          => 'EMAIL',
967
+							'QST_required'      => 1,
968
+							'QST_required_text' => __('This field is required', 'event_espresso'),
969
+							'QST_order'         => 3,
970
+							'QST_admin_only'    => 0,
971
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
972
+							'QST_wp_user'       => self::get_default_creator_id(),
973
+							'QST_deleted'       => 0,
974
+						);
975
+						break;
976
+					case 'address':
977
+						$QST_values = array(
978
+							'QST_display_text'  => __('Address', 'event_espresso'),
979
+							'QST_admin_label'   => __('Address - System Question', 'event_espresso'),
980
+							'QST_system'        => 'address',
981
+							'QST_type'          => 'TEXT',
982
+							'QST_required'      => 0,
983
+							'QST_required_text' => __('This field is required', 'event_espresso'),
984
+							'QST_order'         => 4,
985
+							'QST_admin_only'    => 0,
986
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
987
+							'QST_wp_user'       => self::get_default_creator_id(),
988
+							'QST_deleted'       => 0,
989
+						);
990
+						break;
991
+					case 'address2':
992
+						$QST_values = array(
993
+							'QST_display_text'  => __('Address2', 'event_espresso'),
994
+							'QST_admin_label'   => __('Address2 - System Question', 'event_espresso'),
995
+							'QST_system'        => 'address2',
996
+							'QST_type'          => 'TEXT',
997
+							'QST_required'      => 0,
998
+							'QST_required_text' => __('This field is required', 'event_espresso'),
999
+							'QST_order'         => 5,
1000
+							'QST_admin_only'    => 0,
1001
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1002
+							'QST_wp_user'       => self::get_default_creator_id(),
1003
+							'QST_deleted'       => 0,
1004
+						);
1005
+						break;
1006
+					case 'city':
1007
+						$QST_values = array(
1008
+							'QST_display_text'  => __('City', 'event_espresso'),
1009
+							'QST_admin_label'   => __('City - System Question', 'event_espresso'),
1010
+							'QST_system'        => 'city',
1011
+							'QST_type'          => 'TEXT',
1012
+							'QST_required'      => 0,
1013
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1014
+							'QST_order'         => 6,
1015
+							'QST_admin_only'    => 0,
1016
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1017
+							'QST_wp_user'       => self::get_default_creator_id(),
1018
+							'QST_deleted'       => 0,
1019
+						);
1020
+						break;
1021
+					case 'country':
1022
+						$QST_values = array(
1023
+							'QST_display_text'  => __('Country', 'event_espresso'),
1024
+							'QST_admin_label'   => __('Country - System Question', 'event_espresso'),
1025
+							'QST_system'        => 'country',
1026
+							'QST_type'          => 'COUNTRY',
1027
+							'QST_required'      => 0,
1028
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1029
+							'QST_order'         => 7,
1030
+							'QST_admin_only'    => 0,
1031
+							'QST_wp_user'       => self::get_default_creator_id(),
1032
+							'QST_deleted'       => 0,
1033
+						);
1034
+						break;
1035
+					case 'state':
1036
+						$QST_values = array(
1037
+							'QST_display_text'  => __('State/Province', 'event_espresso'),
1038
+							'QST_admin_label'   => __('State/Province - System Question', 'event_espresso'),
1039
+							'QST_system'        => 'state',
1040
+							'QST_type'          => 'STATE',
1041
+							'QST_required'      => 0,
1042
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1043
+							'QST_order'         => 8,
1044
+							'QST_admin_only'    => 0,
1045
+							'QST_wp_user'       => self::get_default_creator_id(),
1046
+							'QST_deleted'       => 0,
1047
+						);
1048
+						break;
1049
+					case 'zip':
1050
+						$QST_values = array(
1051
+							'QST_display_text'  => __('Zip/Postal Code', 'event_espresso'),
1052
+							'QST_admin_label'   => __('Zip/Postal Code - System Question', 'event_espresso'),
1053
+							'QST_system'        => 'zip',
1054
+							'QST_type'          => 'TEXT',
1055
+							'QST_required'      => 0,
1056
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1057
+							'QST_order'         => 9,
1058
+							'QST_admin_only'    => 0,
1059
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1060
+							'QST_wp_user'       => self::get_default_creator_id(),
1061
+							'QST_deleted'       => 0,
1062
+						);
1063
+						break;
1064
+					case 'phone':
1065
+						$QST_values = array(
1066
+							'QST_display_text'  => __('Phone Number', 'event_espresso'),
1067
+							'QST_admin_label'   => __('Phone Number - System Question', 'event_espresso'),
1068
+							'QST_system'        => 'phone',
1069
+							'QST_type'          => 'TEXT',
1070
+							'QST_required'      => 0,
1071
+							'QST_required_text' => __('This field is required', 'event_espresso'),
1072
+							'QST_order'         => 10,
1073
+							'QST_admin_only'    => 0,
1074
+							'QST_max'           => EEM_Question::instance()->absolute_max_for_system_question($QST_system),
1075
+							'QST_wp_user'       => self::get_default_creator_id(),
1076
+							'QST_deleted'       => 0,
1077
+						);
1078
+						break;
1079
+				}
1080
+				if (! empty($QST_values)) {
1081
+					// insert system question
1082
+					$wpdb->insert(
1083
+						$table_name,
1084
+						$QST_values,
1085
+						array('%s', '%s', '%s', '%s', '%d', '%s', '%d', '%d', '%d', '%d')
1086
+					);
1087
+					$QST_ID = $wpdb->insert_id;
1088
+					// QUESTION GROUP QUESTIONS
1089
+					if (in_array($QST_system, array('fname', 'lname', 'email'))) {
1090
+						$system_question_we_want = EEM_Question_Group::system_personal;
1091
+					} else {
1092
+						$system_question_we_want = EEM_Question_Group::system_address;
1093
+					}
1094
+					if (isset($QSG_IDs[$system_question_we_want])) {
1095
+						$QSG_ID = $QSG_IDs[$system_question_we_want];
1096
+					} else {
1097
+						$id_col = EEM_Question_Group::instance()
1098
+													->get_col(array(array('QSG_system' => $system_question_we_want)));
1099
+						if (is_array($id_col)) {
1100
+							$QSG_ID = reset($id_col);
1101
+						} else {
1102
+							//ok so we didn't find it in the db either?? that's weird because we should have inserted it at the start of this method
1103
+							EE_Log::instance()->log(
1104
+								__FILE__,
1105
+								__FUNCTION__,
1106
+								sprintf(
1107
+									__(
1108
+										'Could not associate question %1$s to a question group because no system question
1109 1109
                                          group existed',
1110
-                                        'event_espresso'
1111
-                                    ),
1112
-                                    $QST_ID),
1113
-                                'error');
1114
-                            continue;
1115
-                        }
1116
-                    }
1117
-                    // add system questions to groups
1118
-                    $wpdb->insert(
1119
-                        \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1120
-                        array(
1121
-                            'QSG_ID'    => $QSG_ID,
1122
-                            'QST_ID'    => $QST_ID,
1123
-                            'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1124
-                        ),
1125
-                        array('%d', '%d', '%d')
1126
-                    );
1127
-                }
1128
-            }
1129
-        }
1130
-    }
1131
-
1132
-
1133
-    /**
1134
-     * Makes sure the default payment method (Invoice) is active.
1135
-     * This used to be done automatically as part of constructing the old gateways config
1136
-     *
1137
-     * @throws \EE_Error
1138
-     */
1139
-    public static function insert_default_payment_methods()
1140
-    {
1141
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1142
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
1143
-            EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1144
-        } else {
1145
-            EEM_Payment_Method::instance()->verify_button_urls();
1146
-        }
1147
-    }
1148
-
1149
-    /**
1150
-     * insert_default_status_codes
1151
-     *
1152
-     * @access public
1153
-     * @static
1154
-     * @return void
1155
-     */
1156
-    public static function insert_default_status_codes()
1157
-    {
1158
-
1159
-        global $wpdb;
1160
-
1161
-        if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1162
-
1163
-            $table_name = EEM_Status::instance()->table();
1164
-
1165
-            $SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1166
-            $wpdb->query($SQL);
1167
-
1168
-            $SQL = "INSERT INTO $table_name
1110
+										'event_espresso'
1111
+									),
1112
+									$QST_ID),
1113
+								'error');
1114
+							continue;
1115
+						}
1116
+					}
1117
+					// add system questions to groups
1118
+					$wpdb->insert(
1119
+						\EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('esp_question_group_question'),
1120
+						array(
1121
+							'QSG_ID'    => $QSG_ID,
1122
+							'QST_ID'    => $QST_ID,
1123
+							'QGQ_order' => ($QSG_ID === 1) ? $order_for_group_1++ : $order_for_group_2++,
1124
+						),
1125
+						array('%d', '%d', '%d')
1126
+					);
1127
+				}
1128
+			}
1129
+		}
1130
+	}
1131
+
1132
+
1133
+	/**
1134
+	 * Makes sure the default payment method (Invoice) is active.
1135
+	 * This used to be done automatically as part of constructing the old gateways config
1136
+	 *
1137
+	 * @throws \EE_Error
1138
+	 */
1139
+	public static function insert_default_payment_methods()
1140
+	{
1141
+		if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1142
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
1143
+			EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1144
+		} else {
1145
+			EEM_Payment_Method::instance()->verify_button_urls();
1146
+		}
1147
+	}
1148
+
1149
+	/**
1150
+	 * insert_default_status_codes
1151
+	 *
1152
+	 * @access public
1153
+	 * @static
1154
+	 * @return void
1155
+	 */
1156
+	public static function insert_default_status_codes()
1157
+	{
1158
+
1159
+		global $wpdb;
1160
+
1161
+		if (\EEH_Activation::getTableAnalysis()->tableExists(EEM_Status::instance()->table())) {
1162
+
1163
+			$table_name = EEM_Status::instance()->table();
1164
+
1165
+			$SQL = "DELETE FROM $table_name WHERE STS_ID IN ( 'ACT', 'NAC', 'NOP', 'OPN', 'CLS', 'PND', 'ONG', 'SEC', 'DRF', 'DEL', 'DEN', 'EXP', 'RPP', 'RCN', 'RDC', 'RAP', 'RNA', 'RWL', 'TAB', 'TIN', 'TFL', 'TCM', 'TOP', 'PAP', 'PCN', 'PFL', 'PDC', 'EDR', 'ESN', 'PPN', 'RIC', 'MSN', 'MFL', 'MID', 'MRS', 'MIC', 'MDO', 'MEX' );";
1166
+			$wpdb->query($SQL);
1167
+
1168
+			$SQL = "INSERT INTO $table_name
1169 1169
 					(STS_ID, STS_code, STS_type, STS_can_edit, STS_desc, STS_open) VALUES
1170 1170
 					('ACT', 'ACTIVE', 'event', 0, NULL, 1),
1171 1171
 					('NAC', 'NOT_ACTIVE', 'event', 0, NULL, 0),
@@ -1205,462 +1205,462 @@  discard block
 block discarded – undo
1205 1205
 					('MID', 'IDLE', 'message', 0, NULL, 1),
1206 1206
 					('MRS', 'RESEND', 'message', 0, NULL, 1),
1207 1207
 					('MIC', 'INCOMPLETE', 'message', 0, NULL, 0);";
1208
-            $wpdb->query($SQL);
1209
-
1210
-        }
1211
-
1212
-    }
1213
-
1214
-
1215
-    /**
1216
-     * generate_default_message_templates
1217
-     *
1218
-     * @static
1219
-     * @throws EE_Error
1220
-     * @return bool     true means new templates were created.
1221
-     *                  false means no templates were created.
1222
-     *                  This is NOT an error flag. To check for errors you will want
1223
-     *                  to use either EE_Error or a try catch for an EE_Error exception.
1224
-     */
1225
-    public static function generate_default_message_templates()
1226
-    {
1227
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1228
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1229
-        /*
1208
+			$wpdb->query($SQL);
1209
+
1210
+		}
1211
+
1212
+	}
1213
+
1214
+
1215
+	/**
1216
+	 * generate_default_message_templates
1217
+	 *
1218
+	 * @static
1219
+	 * @throws EE_Error
1220
+	 * @return bool     true means new templates were created.
1221
+	 *                  false means no templates were created.
1222
+	 *                  This is NOT an error flag. To check for errors you will want
1223
+	 *                  to use either EE_Error or a try catch for an EE_Error exception.
1224
+	 */
1225
+	public static function generate_default_message_templates()
1226
+	{
1227
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1228
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1229
+		/*
1230 1230
          * This first method is taking care of ensuring any default messengers
1231 1231
          * that should be made active and have templates generated are done.
1232 1232
          */
1233
-        $new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1234
-            $message_resource_manager
1235
-        );
1236
-        /**
1237
-         * This method is verifying there are no NEW default message types
1238
-         * for ACTIVE messengers that need activated (and corresponding templates setup).
1239
-         */
1240
-        $new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1241
-            $message_resource_manager
1242
-        );
1243
-        //after all is done, let's persist these changes to the db.
1244
-        $message_resource_manager->update_has_activated_messengers_option();
1245
-        $message_resource_manager->update_active_messengers_option();
1246
-        // will return true if either of these are true.  Otherwise will return false.
1247
-        return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1248
-    }
1249
-
1250
-
1251
-
1252
-    /**
1253
-     * @param \EE_Message_Resource_Manager $message_resource_manager
1254
-     * @return array|bool
1255
-     * @throws \EE_Error
1256
-     */
1257
-    protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1258
-        EE_Message_Resource_Manager $message_resource_manager
1259
-    ) {
1260
-        /** @type EE_messenger[] $active_messengers */
1261
-        $active_messengers = $message_resource_manager->active_messengers();
1262
-        $installed_message_types = $message_resource_manager->installed_message_types();
1263
-        $templates_created = false;
1264
-        foreach ($active_messengers as $active_messenger) {
1265
-            $default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1266
-            $default_message_type_names_to_activate = array();
1267
-            // looping through each default message type reported by the messenger
1268
-            // and setup the actual message types to activate.
1269
-            foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1270
-                // if already active or has already been activated before we skip
1271
-                // (otherwise we might reactivate something user's intentionally deactivated.)
1272
-                // we also skip if the message type is not installed.
1273
-                if (
1274
-                    $message_resource_manager->has_message_type_been_activated_for_messenger(
1275
-                        $default_message_type_name_for_messenger,
1276
-                        $active_messenger->name
1277
-                    )
1278
-                    || $message_resource_manager->is_message_type_active_for_messenger(
1279
-                        $active_messenger->name,
1280
-                        $default_message_type_name_for_messenger
1281
-                    )
1282
-                    || ! isset($installed_message_types[$default_message_type_name_for_messenger])
1283
-                ) {
1284
-                    continue;
1285
-                }
1286
-                $default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1287
-            }
1288
-            //let's activate!
1289
-            $message_resource_manager->ensure_message_types_are_active(
1290
-                $default_message_type_names_to_activate,
1291
-                $active_messenger->name,
1292
-                false
1293
-            );
1294
-            //activate the templates for these message types
1295
-            if ( ! empty($default_message_type_names_to_activate)) {
1296
-                $templates_created = EEH_MSG_Template::generate_new_templates(
1297
-                    $active_messenger->name,
1298
-                    $default_message_type_names_for_messenger,
1299
-                    '',
1300
-                    true
1301
-                );
1302
-            }
1303
-        }
1304
-        return $templates_created;
1305
-    }
1306
-
1307
-
1308
-
1309
-    /**
1310
-     * This will activate and generate default messengers and default message types for those messengers.
1311
-     *
1312
-     * @param EE_message_Resource_Manager $message_resource_manager
1313
-     * @return array|bool  True means there were default messengers and message type templates generated.
1314
-     *                     False means that there were no templates generated
1315
-     *                     (which could simply mean there are no default message types for a messenger).
1316
-     * @throws EE_Error
1317
-     */
1318
-    protected static function _activate_and_generate_default_messengers_and_message_templates(
1319
-        EE_Message_Resource_Manager $message_resource_manager
1320
-    ) {
1321
-        /** @type EE_messenger[] $messengers_to_generate */
1322
-        $messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1323
-        $installed_message_types = $message_resource_manager->installed_message_types();
1324
-        $templates_generated = false;
1325
-        foreach ($messengers_to_generate as $messenger_to_generate) {
1326
-            $default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1327
-            //verify the default message types match an installed message type.
1328
-            foreach ($default_message_type_names_for_messenger as $key => $name) {
1329
-                if (
1330
-                    ! isset($installed_message_types[$name])
1331
-                    || $message_resource_manager->has_message_type_been_activated_for_messenger(
1332
-                        $name,
1333
-                        $messenger_to_generate->name
1334
-                    )
1335
-                ) {
1336
-                    unset($default_message_type_names_for_messenger[$key]);
1337
-                }
1338
-            }
1339
-            // in previous iterations, the active_messengers option in the db
1340
-            // needed updated before calling create templates. however with the changes this may not be necessary.
1341
-            // This comment is left here just in case we discover that we _do_ need to update before
1342
-            // passing off to create templates (after the refactor is done).
1343
-            // @todo remove this comment when determined not necessary.
1344
-            $message_resource_manager->activate_messenger(
1345
-                $messenger_to_generate->name,
1346
-                $default_message_type_names_for_messenger,
1347
-                false
1348
-            );
1349
-            //create any templates needing created (or will reactivate templates already generated as necessary).
1350
-            if ( ! empty($default_message_type_names_for_messenger)) {
1351
-                $templates_generated = EEH_MSG_Template::generate_new_templates(
1352
-                    $messenger_to_generate->name,
1353
-                    $default_message_type_names_for_messenger,
1354
-                    '',
1355
-                    true
1356
-                );
1357
-            }
1358
-        }
1359
-        return $templates_generated;
1360
-    }
1361
-
1362
-
1363
-    /**
1364
-     * This returns the default messengers to generate templates for on activation of EE.
1365
-     * It considers:
1366
-     * - whether a messenger is already active in the db.
1367
-     * - whether a messenger has been made active at any time in the past.
1368
-     *
1369
-     * @static
1370
-     * @param  EE_Message_Resource_Manager $message_resource_manager
1371
-     * @return EE_messenger[]
1372
-     */
1373
-    protected static function _get_default_messengers_to_generate_on_activation(
1374
-        EE_Message_Resource_Manager $message_resource_manager
1375
-    ) {
1376
-        $active_messengers    = $message_resource_manager->active_messengers();
1377
-        $installed_messengers = $message_resource_manager->installed_messengers();
1378
-        $has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1379
-
1380
-        $messengers_to_generate = array();
1381
-        foreach ($installed_messengers as $installed_messenger) {
1382
-            //if installed messenger is a messenger that should be activated on install
1383
-            //and is not already active
1384
-            //and has never been activated
1385
-            if (
1386
-                ! $installed_messenger->activate_on_install
1387
-                || isset($active_messengers[$installed_messenger->name])
1388
-                || isset($has_activated[$installed_messenger->name])
1389
-            ) {
1390
-                continue;
1391
-            }
1392
-            $messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1393
-        }
1394
-        return $messengers_to_generate;
1395
-    }
1396
-
1397
-
1398
-    /**
1399
-     * This simply validates active message types to ensure they actually match installed
1400
-     * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1401
-     * rows are set inactive.
1402
-     * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1403
-     * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1404
-     * are still handled in here.
1405
-     *
1406
-     * @since 4.3.1
1407
-     * @return void
1408
-     */
1409
-    public static function validate_messages_system()
1410
-    {
1411
-        /** @type EE_Message_Resource_Manager $message_resource_manager */
1412
-        $message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1413
-        $message_resource_manager->validate_active_message_types_are_installed();
1414
-        do_action('AHEE__EEH_Activation__validate_messages_system');
1415
-    }
1416
-
1417
-
1418
-    /**
1419
-     * create_no_ticket_prices_array
1420
-     *
1421
-     * @access public
1422
-     * @static
1423
-     * @return void
1424
-     */
1425
-    public static function create_no_ticket_prices_array()
1426
-    {
1427
-        // this creates an array for tracking events that have no active ticket prices created
1428
-        // this allows us to warn admins of the situation so that it can be corrected
1429
-        $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1430
-        if (! $espresso_no_ticket_prices) {
1431
-            add_option('ee_no_ticket_prices', array(), '', false);
1432
-        }
1433
-    }
1434
-
1435
-
1436
-    /**
1437
-     * plugin_deactivation
1438
-     *
1439
-     * @access public
1440
-     * @static
1441
-     * @return void
1442
-     */
1443
-    public static function plugin_deactivation()
1444
-    {
1445
-    }
1446
-
1447
-
1448
-    /**
1449
-     * Finds all our EE4 custom post types, and deletes them and their associated data
1450
-     * (like post meta or term relations)
1451
-     *
1452
-     * @global wpdb $wpdb
1453
-     * @throws \EE_Error
1454
-     */
1455
-    public static function delete_all_espresso_cpt_data()
1456
-    {
1457
-        global $wpdb;
1458
-        //get all the CPT post_types
1459
-        $ee_post_types = array();
1460
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1461
-            if (method_exists($model_name, 'instance')) {
1462
-                $model_obj = call_user_func(array($model_name, 'instance'));
1463
-                if ($model_obj instanceof EEM_CPT_Base) {
1464
-                    $ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1465
-                }
1466
-            }
1467
-        }
1468
-        //get all our CPTs
1469
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1470
-        $cpt_ids = $wpdb->get_col($query);
1471
-        //delete each post meta and term relations too
1472
-        foreach ($cpt_ids as $post_id) {
1473
-            wp_delete_post($post_id, true);
1474
-        }
1475
-    }
1476
-
1477
-    /**
1478
-     * Deletes all EE custom tables
1479
-     *
1480
-     * @return array
1481
-     */
1482
-    public static function drop_espresso_tables()
1483
-    {
1484
-        $tables = array();
1485
-        // load registry
1486
-        foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1487
-            if (method_exists($model_name, 'instance')) {
1488
-                $model_obj = call_user_func(array($model_name, 'instance'));
1489
-                if ($model_obj instanceof EEM_Base) {
1490
-                    foreach ($model_obj->get_tables() as $table) {
1491
-                        if (strpos($table->get_table_name(), 'esp_')
1492
-                            &&
1493
-                            (
1494
-                                is_main_site()//main site? nuke them all
1495
-                                || ! $table->is_global()//not main site,but not global either. nuke it
1496
-                            )
1497
-                        ) {
1498
-                            $tables[$table->get_table_name()] = $table->get_table_name();
1499
-                        }
1500
-                    }
1501
-                }
1502
-            }
1503
-        }
1504
-
1505
-        //there are some tables whose models were removed.
1506
-        //they should be removed when removing all EE core's data
1507
-        $tables_without_models = array(
1508
-            'esp_promotion',
1509
-            'esp_promotion_applied',
1510
-            'esp_promotion_object',
1511
-            'esp_promotion_rule',
1512
-            'esp_rule',
1513
-        );
1514
-        foreach ($tables_without_models as $table) {
1515
-            $tables[$table] = $table;
1516
-        }
1517
-        return \EEH_Activation::getTableManager()->dropTables($tables);
1518
-    }
1519
-
1520
-
1521
-
1522
-    /**
1523
-     * Drops all the tables mentioned in a single MYSQL query. Double-checks
1524
-     * each table name provided has a wpdb prefix attached, and that it exists.
1525
-     * Returns the list actually deleted
1526
-     *
1527
-     * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1528
-     * @global WPDB $wpdb
1529
-     * @param array $table_names
1530
-     * @return array of table names which we deleted
1531
-     */
1532
-    public static function drop_tables($table_names)
1533
-    {
1534
-        return \EEH_Activation::getTableManager()->dropTables($table_names);
1535
-    }
1536
-
1537
-
1538
-
1539
-    /**
1540
-     * plugin_uninstall
1541
-     *
1542
-     * @access public
1543
-     * @static
1544
-     * @param bool $remove_all
1545
-     * @return void
1546
-     */
1547
-    public static function delete_all_espresso_tables_and_data($remove_all = true)
1548
-    {
1549
-        global $wpdb;
1550
-        self::drop_espresso_tables();
1551
-        $wp_options_to_delete = array(
1552
-            'ee_no_ticket_prices'                => true,
1553
-            'ee_active_messengers'               => true,
1554
-            'ee_has_activated_messenger'         => true,
1555
-            'ee_flush_rewrite_rules'             => true,
1556
-            'ee_config'                          => false,
1557
-            'ee_data_migration_current_db_state' => true,
1558
-            'ee_data_migration_mapping_'         => false,
1559
-            'ee_data_migration_script_'          => false,
1560
-            'ee_data_migrations'                 => true,
1561
-            'ee_dms_map'                         => false,
1562
-            'ee_notices'                         => true,
1563
-            'lang_file_check_'                   => false,
1564
-            'ee_maintenance_mode'                => true,
1565
-            'ee_ueip_optin'                      => true,
1566
-            'ee_ueip_has_notified'               => true,
1567
-            'ee_plugin_activation_errors'        => true,
1568
-            'ee_id_mapping_from'                 => false,
1569
-            'espresso_persistent_admin_notices'  => true,
1570
-            'ee_encryption_key'                  => true,
1571
-            'pue_force_upgrade_'                 => false,
1572
-            'pue_json_error_'                    => false,
1573
-            'pue_install_key_'                   => false,
1574
-            'pue_verification_error_'            => false,
1575
-            'pu_dismissed_upgrade_'              => false,
1576
-            'external_updates-'                  => false,
1577
-            'ee_extra_data'                      => true,
1578
-            'ee_ssn_'                            => false,
1579
-            'ee_rss_'                            => false,
1580
-            'ee_rte_n_tx_'                       => false,
1581
-            'ee_pers_admin_notices'              => true,
1582
-            'ee_job_parameters_'                 => false,
1583
-            'ee_upload_directories_incomplete'   => true,
1584
-            'ee_verified_db_collations'          => true,
1585
-        );
1586
-        if (is_main_site()) {
1587
-            $wp_options_to_delete['ee_network_config'] = true;
1588
-        }
1589
-        $undeleted_options = array();
1590
-        foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1591
-            if ($no_wildcard) {
1592
-                if ( ! delete_option($option_name)) {
1593
-                    $undeleted_options[] = $option_name;
1594
-                }
1595
-            } else {
1596
-                $option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1597
-                foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1598
-                    if ( ! delete_option($option_name_from_wildcard)) {
1599
-                        $undeleted_options[] = $option_name_from_wildcard;
1600
-                    }
1601
-                }
1602
-            }
1603
-        }
1604
-        //also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1605
-        remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1606
-        if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1607
-            $db_update_sans_ee4 = array();
1608
-            foreach ($espresso_db_update as $version => $times_activated) {
1609
-                if ((string)$version[0] === '3') {//if its NON EE4
1610
-                    $db_update_sans_ee4[$version] = $times_activated;
1611
-                }
1612
-            }
1613
-            update_option('espresso_db_update', $db_update_sans_ee4);
1614
-        }
1615
-        $errors = '';
1616
-        if ( ! empty($undeleted_options)) {
1617
-            $errors .= sprintf(
1618
-                __('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1619
-                '<br/>',
1620
-                implode(',<br/>', $undeleted_options)
1621
-            );
1622
-        }
1623
-        if ( ! empty($errors)) {
1624
-            EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1625
-        }
1626
-    }
1627
-
1628
-    /**
1629
-     * Gets the mysql error code from the last used query by wpdb
1630
-     *
1631
-     * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1632
-     */
1633
-    public static function last_wpdb_error_code()
1634
-    {
1635
-        global $wpdb;
1636
-        if ($wpdb->use_mysqli) {
1637
-            return mysqli_errno($wpdb->dbh);
1638
-        } else {
1639
-            return mysql_errno($wpdb->dbh);
1640
-        }
1641
-    }
1642
-
1643
-    /**
1644
-     * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1645
-     *
1646
-     * @global wpdb  $wpdb
1647
-     * @deprecated instead use TableAnalysis::tableExists()
1648
-     * @param string $table_name with or without $wpdb->prefix
1649
-     * @return boolean
1650
-     */
1651
-    public static function table_exists($table_name)
1652
-    {
1653
-        return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1654
-    }
1655
-
1656
-    /**
1657
-     * Resets the cache on EEH_Activation
1658
-     */
1659
-    public static function reset()
1660
-    {
1661
-        self::$_default_creator_id                             = null;
1662
-        self::$_initialized_db_content_already_in_this_request = false;
1663
-    }
1233
+		$new_templates_created_for_messenger = self::_activate_and_generate_default_messengers_and_message_templates(
1234
+			$message_resource_manager
1235
+		);
1236
+		/**
1237
+		 * This method is verifying there are no NEW default message types
1238
+		 * for ACTIVE messengers that need activated (and corresponding templates setup).
1239
+		 */
1240
+		$new_templates_created_for_message_type = self::_activate_new_message_types_for_active_messengers_and_generate_default_templates(
1241
+			$message_resource_manager
1242
+		);
1243
+		//after all is done, let's persist these changes to the db.
1244
+		$message_resource_manager->update_has_activated_messengers_option();
1245
+		$message_resource_manager->update_active_messengers_option();
1246
+		// will return true if either of these are true.  Otherwise will return false.
1247
+		return $new_templates_created_for_message_type || $new_templates_created_for_messenger;
1248
+	}
1249
+
1250
+
1251
+
1252
+	/**
1253
+	 * @param \EE_Message_Resource_Manager $message_resource_manager
1254
+	 * @return array|bool
1255
+	 * @throws \EE_Error
1256
+	 */
1257
+	protected static function _activate_new_message_types_for_active_messengers_and_generate_default_templates(
1258
+		EE_Message_Resource_Manager $message_resource_manager
1259
+	) {
1260
+		/** @type EE_messenger[] $active_messengers */
1261
+		$active_messengers = $message_resource_manager->active_messengers();
1262
+		$installed_message_types = $message_resource_manager->installed_message_types();
1263
+		$templates_created = false;
1264
+		foreach ($active_messengers as $active_messenger) {
1265
+			$default_message_type_names_for_messenger = $active_messenger->get_default_message_types();
1266
+			$default_message_type_names_to_activate = array();
1267
+			// looping through each default message type reported by the messenger
1268
+			// and setup the actual message types to activate.
1269
+			foreach ($default_message_type_names_for_messenger as $default_message_type_name_for_messenger) {
1270
+				// if already active or has already been activated before we skip
1271
+				// (otherwise we might reactivate something user's intentionally deactivated.)
1272
+				// we also skip if the message type is not installed.
1273
+				if (
1274
+					$message_resource_manager->has_message_type_been_activated_for_messenger(
1275
+						$default_message_type_name_for_messenger,
1276
+						$active_messenger->name
1277
+					)
1278
+					|| $message_resource_manager->is_message_type_active_for_messenger(
1279
+						$active_messenger->name,
1280
+						$default_message_type_name_for_messenger
1281
+					)
1282
+					|| ! isset($installed_message_types[$default_message_type_name_for_messenger])
1283
+				) {
1284
+					continue;
1285
+				}
1286
+				$default_message_type_names_to_activate[] = $default_message_type_name_for_messenger;
1287
+			}
1288
+			//let's activate!
1289
+			$message_resource_manager->ensure_message_types_are_active(
1290
+				$default_message_type_names_to_activate,
1291
+				$active_messenger->name,
1292
+				false
1293
+			);
1294
+			//activate the templates for these message types
1295
+			if ( ! empty($default_message_type_names_to_activate)) {
1296
+				$templates_created = EEH_MSG_Template::generate_new_templates(
1297
+					$active_messenger->name,
1298
+					$default_message_type_names_for_messenger,
1299
+					'',
1300
+					true
1301
+				);
1302
+			}
1303
+		}
1304
+		return $templates_created;
1305
+	}
1306
+
1307
+
1308
+
1309
+	/**
1310
+	 * This will activate and generate default messengers and default message types for those messengers.
1311
+	 *
1312
+	 * @param EE_message_Resource_Manager $message_resource_manager
1313
+	 * @return array|bool  True means there were default messengers and message type templates generated.
1314
+	 *                     False means that there were no templates generated
1315
+	 *                     (which could simply mean there are no default message types for a messenger).
1316
+	 * @throws EE_Error
1317
+	 */
1318
+	protected static function _activate_and_generate_default_messengers_and_message_templates(
1319
+		EE_Message_Resource_Manager $message_resource_manager
1320
+	) {
1321
+		/** @type EE_messenger[] $messengers_to_generate */
1322
+		$messengers_to_generate = self::_get_default_messengers_to_generate_on_activation($message_resource_manager);
1323
+		$installed_message_types = $message_resource_manager->installed_message_types();
1324
+		$templates_generated = false;
1325
+		foreach ($messengers_to_generate as $messenger_to_generate) {
1326
+			$default_message_type_names_for_messenger = $messenger_to_generate->get_default_message_types();
1327
+			//verify the default message types match an installed message type.
1328
+			foreach ($default_message_type_names_for_messenger as $key => $name) {
1329
+				if (
1330
+					! isset($installed_message_types[$name])
1331
+					|| $message_resource_manager->has_message_type_been_activated_for_messenger(
1332
+						$name,
1333
+						$messenger_to_generate->name
1334
+					)
1335
+				) {
1336
+					unset($default_message_type_names_for_messenger[$key]);
1337
+				}
1338
+			}
1339
+			// in previous iterations, the active_messengers option in the db
1340
+			// needed updated before calling create templates. however with the changes this may not be necessary.
1341
+			// This comment is left here just in case we discover that we _do_ need to update before
1342
+			// passing off to create templates (after the refactor is done).
1343
+			// @todo remove this comment when determined not necessary.
1344
+			$message_resource_manager->activate_messenger(
1345
+				$messenger_to_generate->name,
1346
+				$default_message_type_names_for_messenger,
1347
+				false
1348
+			);
1349
+			//create any templates needing created (or will reactivate templates already generated as necessary).
1350
+			if ( ! empty($default_message_type_names_for_messenger)) {
1351
+				$templates_generated = EEH_MSG_Template::generate_new_templates(
1352
+					$messenger_to_generate->name,
1353
+					$default_message_type_names_for_messenger,
1354
+					'',
1355
+					true
1356
+				);
1357
+			}
1358
+		}
1359
+		return $templates_generated;
1360
+	}
1361
+
1362
+
1363
+	/**
1364
+	 * This returns the default messengers to generate templates for on activation of EE.
1365
+	 * It considers:
1366
+	 * - whether a messenger is already active in the db.
1367
+	 * - whether a messenger has been made active at any time in the past.
1368
+	 *
1369
+	 * @static
1370
+	 * @param  EE_Message_Resource_Manager $message_resource_manager
1371
+	 * @return EE_messenger[]
1372
+	 */
1373
+	protected static function _get_default_messengers_to_generate_on_activation(
1374
+		EE_Message_Resource_Manager $message_resource_manager
1375
+	) {
1376
+		$active_messengers    = $message_resource_manager->active_messengers();
1377
+		$installed_messengers = $message_resource_manager->installed_messengers();
1378
+		$has_activated        = $message_resource_manager->get_has_activated_messengers_option();
1379
+
1380
+		$messengers_to_generate = array();
1381
+		foreach ($installed_messengers as $installed_messenger) {
1382
+			//if installed messenger is a messenger that should be activated on install
1383
+			//and is not already active
1384
+			//and has never been activated
1385
+			if (
1386
+				! $installed_messenger->activate_on_install
1387
+				|| isset($active_messengers[$installed_messenger->name])
1388
+				|| isset($has_activated[$installed_messenger->name])
1389
+			) {
1390
+				continue;
1391
+			}
1392
+			$messengers_to_generate[$installed_messenger->name] = $installed_messenger;
1393
+		}
1394
+		return $messengers_to_generate;
1395
+	}
1396
+
1397
+
1398
+	/**
1399
+	 * This simply validates active message types to ensure they actually match installed
1400
+	 * message types.  If there's a mismatch then we deactivate the message type and ensure all related db
1401
+	 * rows are set inactive.
1402
+	 * Note: Messengers are no longer validated here as of 4.9.0 because they get validated automatically whenever
1403
+	 * EE_Messenger_Resource_Manager is constructed.  Message Types are a bit more resource heavy for validation so they
1404
+	 * are still handled in here.
1405
+	 *
1406
+	 * @since 4.3.1
1407
+	 * @return void
1408
+	 */
1409
+	public static function validate_messages_system()
1410
+	{
1411
+		/** @type EE_Message_Resource_Manager $message_resource_manager */
1412
+		$message_resource_manager = EE_Registry::instance()->load_lib('Message_Resource_Manager');
1413
+		$message_resource_manager->validate_active_message_types_are_installed();
1414
+		do_action('AHEE__EEH_Activation__validate_messages_system');
1415
+	}
1416
+
1417
+
1418
+	/**
1419
+	 * create_no_ticket_prices_array
1420
+	 *
1421
+	 * @access public
1422
+	 * @static
1423
+	 * @return void
1424
+	 */
1425
+	public static function create_no_ticket_prices_array()
1426
+	{
1427
+		// this creates an array for tracking events that have no active ticket prices created
1428
+		// this allows us to warn admins of the situation so that it can be corrected
1429
+		$espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1430
+		if (! $espresso_no_ticket_prices) {
1431
+			add_option('ee_no_ticket_prices', array(), '', false);
1432
+		}
1433
+	}
1434
+
1435
+
1436
+	/**
1437
+	 * plugin_deactivation
1438
+	 *
1439
+	 * @access public
1440
+	 * @static
1441
+	 * @return void
1442
+	 */
1443
+	public static function plugin_deactivation()
1444
+	{
1445
+	}
1446
+
1447
+
1448
+	/**
1449
+	 * Finds all our EE4 custom post types, and deletes them and their associated data
1450
+	 * (like post meta or term relations)
1451
+	 *
1452
+	 * @global wpdb $wpdb
1453
+	 * @throws \EE_Error
1454
+	 */
1455
+	public static function delete_all_espresso_cpt_data()
1456
+	{
1457
+		global $wpdb;
1458
+		//get all the CPT post_types
1459
+		$ee_post_types = array();
1460
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1461
+			if (method_exists($model_name, 'instance')) {
1462
+				$model_obj = call_user_func(array($model_name, 'instance'));
1463
+				if ($model_obj instanceof EEM_CPT_Base) {
1464
+					$ee_post_types[] = $wpdb->prepare("%s", $model_obj->post_type());
1465
+				}
1466
+			}
1467
+		}
1468
+		//get all our CPTs
1469
+		$query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1470
+		$cpt_ids = $wpdb->get_col($query);
1471
+		//delete each post meta and term relations too
1472
+		foreach ($cpt_ids as $post_id) {
1473
+			wp_delete_post($post_id, true);
1474
+		}
1475
+	}
1476
+
1477
+	/**
1478
+	 * Deletes all EE custom tables
1479
+	 *
1480
+	 * @return array
1481
+	 */
1482
+	public static function drop_espresso_tables()
1483
+	{
1484
+		$tables = array();
1485
+		// load registry
1486
+		foreach (EE_Registry::instance()->non_abstract_db_models as $model_name) {
1487
+			if (method_exists($model_name, 'instance')) {
1488
+				$model_obj = call_user_func(array($model_name, 'instance'));
1489
+				if ($model_obj instanceof EEM_Base) {
1490
+					foreach ($model_obj->get_tables() as $table) {
1491
+						if (strpos($table->get_table_name(), 'esp_')
1492
+							&&
1493
+							(
1494
+								is_main_site()//main site? nuke them all
1495
+								|| ! $table->is_global()//not main site,but not global either. nuke it
1496
+							)
1497
+						) {
1498
+							$tables[$table->get_table_name()] = $table->get_table_name();
1499
+						}
1500
+					}
1501
+				}
1502
+			}
1503
+		}
1504
+
1505
+		//there are some tables whose models were removed.
1506
+		//they should be removed when removing all EE core's data
1507
+		$tables_without_models = array(
1508
+			'esp_promotion',
1509
+			'esp_promotion_applied',
1510
+			'esp_promotion_object',
1511
+			'esp_promotion_rule',
1512
+			'esp_rule',
1513
+		);
1514
+		foreach ($tables_without_models as $table) {
1515
+			$tables[$table] = $table;
1516
+		}
1517
+		return \EEH_Activation::getTableManager()->dropTables($tables);
1518
+	}
1519
+
1520
+
1521
+
1522
+	/**
1523
+	 * Drops all the tables mentioned in a single MYSQL query. Double-checks
1524
+	 * each table name provided has a wpdb prefix attached, and that it exists.
1525
+	 * Returns the list actually deleted
1526
+	 *
1527
+	 * @deprecated in 4.9.13. Instead use TableManager::dropTables()
1528
+	 * @global WPDB $wpdb
1529
+	 * @param array $table_names
1530
+	 * @return array of table names which we deleted
1531
+	 */
1532
+	public static function drop_tables($table_names)
1533
+	{
1534
+		return \EEH_Activation::getTableManager()->dropTables($table_names);
1535
+	}
1536
+
1537
+
1538
+
1539
+	/**
1540
+	 * plugin_uninstall
1541
+	 *
1542
+	 * @access public
1543
+	 * @static
1544
+	 * @param bool $remove_all
1545
+	 * @return void
1546
+	 */
1547
+	public static function delete_all_espresso_tables_and_data($remove_all = true)
1548
+	{
1549
+		global $wpdb;
1550
+		self::drop_espresso_tables();
1551
+		$wp_options_to_delete = array(
1552
+			'ee_no_ticket_prices'                => true,
1553
+			'ee_active_messengers'               => true,
1554
+			'ee_has_activated_messenger'         => true,
1555
+			'ee_flush_rewrite_rules'             => true,
1556
+			'ee_config'                          => false,
1557
+			'ee_data_migration_current_db_state' => true,
1558
+			'ee_data_migration_mapping_'         => false,
1559
+			'ee_data_migration_script_'          => false,
1560
+			'ee_data_migrations'                 => true,
1561
+			'ee_dms_map'                         => false,
1562
+			'ee_notices'                         => true,
1563
+			'lang_file_check_'                   => false,
1564
+			'ee_maintenance_mode'                => true,
1565
+			'ee_ueip_optin'                      => true,
1566
+			'ee_ueip_has_notified'               => true,
1567
+			'ee_plugin_activation_errors'        => true,
1568
+			'ee_id_mapping_from'                 => false,
1569
+			'espresso_persistent_admin_notices'  => true,
1570
+			'ee_encryption_key'                  => true,
1571
+			'pue_force_upgrade_'                 => false,
1572
+			'pue_json_error_'                    => false,
1573
+			'pue_install_key_'                   => false,
1574
+			'pue_verification_error_'            => false,
1575
+			'pu_dismissed_upgrade_'              => false,
1576
+			'external_updates-'                  => false,
1577
+			'ee_extra_data'                      => true,
1578
+			'ee_ssn_'                            => false,
1579
+			'ee_rss_'                            => false,
1580
+			'ee_rte_n_tx_'                       => false,
1581
+			'ee_pers_admin_notices'              => true,
1582
+			'ee_job_parameters_'                 => false,
1583
+			'ee_upload_directories_incomplete'   => true,
1584
+			'ee_verified_db_collations'          => true,
1585
+		);
1586
+		if (is_main_site()) {
1587
+			$wp_options_to_delete['ee_network_config'] = true;
1588
+		}
1589
+		$undeleted_options = array();
1590
+		foreach ($wp_options_to_delete as $option_name => $no_wildcard) {
1591
+			if ($no_wildcard) {
1592
+				if ( ! delete_option($option_name)) {
1593
+					$undeleted_options[] = $option_name;
1594
+				}
1595
+			} else {
1596
+				$option_names_to_delete_from_wildcard = $wpdb->get_col("SELECT option_name FROM $wpdb->options WHERE option_name LIKE '%$option_name%'");
1597
+				foreach ($option_names_to_delete_from_wildcard as $option_name_from_wildcard) {
1598
+					if ( ! delete_option($option_name_from_wildcard)) {
1599
+						$undeleted_options[] = $option_name_from_wildcard;
1600
+					}
1601
+				}
1602
+			}
1603
+		}
1604
+		//also, let's make sure the "ee_config_option_names" wp option stays out by removing the action that adds it
1605
+		remove_action('shutdown', array(EE_Config::instance(), 'shutdown'), 10);
1606
+		if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1607
+			$db_update_sans_ee4 = array();
1608
+			foreach ($espresso_db_update as $version => $times_activated) {
1609
+				if ((string)$version[0] === '3') {//if its NON EE4
1610
+					$db_update_sans_ee4[$version] = $times_activated;
1611
+				}
1612
+			}
1613
+			update_option('espresso_db_update', $db_update_sans_ee4);
1614
+		}
1615
+		$errors = '';
1616
+		if ( ! empty($undeleted_options)) {
1617
+			$errors .= sprintf(
1618
+				__('The following wp-options could not be deleted: %s%s', 'event_espresso'),
1619
+				'<br/>',
1620
+				implode(',<br/>', $undeleted_options)
1621
+			);
1622
+		}
1623
+		if ( ! empty($errors)) {
1624
+			EE_Error::add_attention($errors, __FILE__, __FUNCTION__, __LINE__);
1625
+		}
1626
+	}
1627
+
1628
+	/**
1629
+	 * Gets the mysql error code from the last used query by wpdb
1630
+	 *
1631
+	 * @return int mysql error code, see https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
1632
+	 */
1633
+	public static function last_wpdb_error_code()
1634
+	{
1635
+		global $wpdb;
1636
+		if ($wpdb->use_mysqli) {
1637
+			return mysqli_errno($wpdb->dbh);
1638
+		} else {
1639
+			return mysql_errno($wpdb->dbh);
1640
+		}
1641
+	}
1642
+
1643
+	/**
1644
+	 * Checks that the database table exists. Also works on temporary tables (for unit tests mostly).
1645
+	 *
1646
+	 * @global wpdb  $wpdb
1647
+	 * @deprecated instead use TableAnalysis::tableExists()
1648
+	 * @param string $table_name with or without $wpdb->prefix
1649
+	 * @return boolean
1650
+	 */
1651
+	public static function table_exists($table_name)
1652
+	{
1653
+		return \EEH_Activation::getTableAnalysis()->tableExists($table_name);
1654
+	}
1655
+
1656
+	/**
1657
+	 * Resets the cache on EEH_Activation
1658
+	 */
1659
+	public static function reset()
1660
+	{
1661
+		self::$_default_creator_id                             = null;
1662
+		self::$_initialized_db_content_already_in_this_request = false;
1663
+	}
1664 1664
 }
1665 1665
 // End of file EEH_Activation.helper.php
1666 1666
 // Location: /helpers/EEH_Activation.core.php
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
      */
58 58
     public static function getTableAnalysis()
59 59
     {
60
-        if (! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
60
+        if ( ! self::$table_analysis instanceof \EventEspresso\core\services\database\TableAnalysis) {
61 61
             self::$table_analysis = EE_Registry::instance()->create('TableAnalysis', array(), true);
62 62
         }
63 63
         return self::$table_analysis;
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
      */
70 70
     public static function getTableManager()
71 71
     {
72
-        if (! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
72
+        if ( ! self::$table_manager instanceof \EventEspresso\core\services\database\TableManager) {
73 73
             self::$table_manager = EE_Registry::instance()->create('TableManager', array(), true);
74 74
         }
75 75
         return self::$table_manager;
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
         if ($which_to_include === 'old') {
184 184
             $cron_tasks = array_filter(
185 185
                 $cron_tasks,
186
-                function ($value) {
186
+                function($value) {
187 187
                     return $value === EEH_Activation::cron_task_no_longer_in_use;
188 188
                 }
189 189
             );
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
     {
214 214
 
215 215
         foreach (EEH_Activation::get_cron_tasks('current') as $hook_name => $frequency) {
216
-            if (! wp_next_scheduled($hook_name)) {
216
+            if ( ! wp_next_scheduled($hook_name)) {
217 217
                 /**
218 218
                  * This allows client code to define the initial start timestamp for this schedule.
219 219
                  */
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
             3
319 319
         );
320 320
         //EE_Config::reset();
321
-        if (! EE_Config::logging_enabled()) {
321
+        if ( ! EE_Config::logging_enabled()) {
322 322
             delete_option(EE_Config::LOG_NAME);
323 323
         }
324 324
     }
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
     public static function load_calendar_config()
334 334
     {
335 335
         // grab array of all plugin folders and loop thru it
336
-        $plugins = glob(WP_PLUGIN_DIR . DS . '*', GLOB_ONLYDIR);
336
+        $plugins = glob(WP_PLUGIN_DIR.DS.'*', GLOB_ONLYDIR);
337 337
         if (empty($plugins)) {
338 338
             return;
339 339
         }
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
                 || strpos($plugin, 'calendar') !== false
351 351
             ) {
352 352
                 // this is what we are looking for
353
-                $calendar_config = $plugin_path . DS . 'EE_Calendar_Config.php';
353
+                $calendar_config = $plugin_path.DS.'EE_Calendar_Config.php';
354 354
                 // does it exist in this folder ?
355 355
                 if (is_readable($calendar_config)) {
356 356
                     // YEAH! let's load it
@@ -478,7 +478,7 @@  discard block
 block discarded – undo
478 478
             ) {
479 479
                 //update Config with post ID
480 480
                 $EE_Core_Config->{$critical_page['id']} = $critical_page['post']->ID;
481
-                if (! EE_Config::instance()->update_espresso_config(false, false)) {
481
+                if ( ! EE_Config::instance()->update_espresso_config(false, false)) {
482 482
                     $msg = __(
483 483
                         'The Event Espresso critical page configuration settings could not be updated.',
484 484
                         'event_espresso'
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
                         'A potential issue has been detected with one or more of your Event Espresso pages. Go to %s to view your Event Espresso pages.',
502 502
                         'event_espresso'
503 503
                     ),
504
-                    '<a href="' . admin_url('admin.php?page=espresso_general_settings&action=critical_pages') . '">'
504
+                    '<a href="'.admin_url('admin.php?page=espresso_general_settings&action=critical_pages').'">'
505 505
                     . __('Event Espresso Critical Pages Settings', 'event_espresso')
506 506
                     . '</a>'
507 507
                 )
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
     public static function get_page_by_ee_shortcode($ee_shortcode)
528 528
     {
529 529
         global $wpdb;
530
-        $shortcode_and_opening_bracket = '[' . $ee_shortcode;
530
+        $shortcode_and_opening_bracket = '['.$ee_shortcode;
531 531
         $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%$shortcode_and_opening_bracket%' LIMIT 1");
532 532
         if ($post_id) {
533 533
             return get_post($post_id);
@@ -553,11 +553,11 @@  discard block
 block discarded – undo
553 553
             'post_status'    => 'publish',
554 554
             'post_type'      => 'page',
555 555
             'comment_status' => 'closed',
556
-            'post_content'   => '[' . $critical_page['code'] . ']',
556
+            'post_content'   => '['.$critical_page['code'].']',
557 557
         );
558 558
 
559 559
         $post_id = wp_insert_post($post_args);
560
-        if (! $post_id) {
560
+        if ( ! $post_id) {
561 561
             $msg = sprintf(
562 562
                 __('The Event Espresso  critical page entitled "%s" could not be created.', 'event_espresso'),
563 563
                 $critical_page['name']
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
             return $critical_page;
567 567
         }
568 568
         // get newly created post's details
569
-        if (! $critical_page['post'] = get_post($post_id)) {
569
+        if ( ! $critical_page['post'] = get_post($post_id)) {
570 570
             $msg = sprintf(
571 571
                 __('The Event Espresso critical page entitled "%s" could not be retrieved.', 'event_espresso'),
572 572
                 $critical_page['name']
@@ -603,17 +603,17 @@  discard block
 block discarded – undo
603 603
             $role_to_check
604 604
         );
605 605
         if ($pre_filtered_id !== false) {
606
-            return (int)$pre_filtered_id;
606
+            return (int) $pre_filtered_id;
607 607
         }
608 608
         $capabilities_key = \EEH_Activation::getTableAnalysis()->ensureTableNameHasPrefix('capabilities');
609 609
         $query = $wpdb->prepare(
610 610
             "SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$capabilities_key' AND meta_value LIKE %s ORDER BY user_id ASC LIMIT 0,1",
611
-            '%' . $role_to_check . '%'
611
+            '%'.$role_to_check.'%'
612 612
         );
613 613
         $user_id = $wpdb->get_var($query);
614 614
         $user_id = apply_filters('FHEE__EEH_Activation_Helper__get_default_creator_id__user_id', $user_id);
615
-        if ($user_id && (int)$user_id) {
616
-            self::$_default_creator_id = (int)$user_id;
615
+        if ($user_id && (int) $user_id) {
616
+            self::$_default_creator_id = (int) $user_id;
617 617
             return self::$_default_creator_id;
618 618
         } else {
619 619
             return null;
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
         }
649 649
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
650 650
         if ( ! function_exists('dbDelta')) {
651
-            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
651
+            require_once(ABSPATH.'wp-admin/includes/upgrade.php');
652 652
         }
653 653
         $tableAnalysis = \EEH_Activation::getTableAnalysis();
654 654
         $wp_table_name = $tableAnalysis->ensureTableNameHasPrefix($table_name);
@@ -859,13 +859,13 @@  discard block
 block discarded – undo
859 859
             // reset values array
860 860
             $QSG_values = array();
861 861
             // if we don't have what we should have (but use $QST_system as as string because that's what we got from the db)
862
-            if (! in_array("$QSG_system", $question_groups)) {
862
+            if ( ! in_array("$QSG_system", $question_groups)) {
863 863
                 // add it
864 864
                 switch ($QSG_system) {
865 865
                     case 1:
866 866
                         $QSG_values = array(
867 867
                             'QSG_name'            => __('Personal Information', 'event_espresso'),
868
-                            'QSG_identifier'      => 'personal-information-' . time(),
868
+                            'QSG_identifier'      => 'personal-information-'.time(),
869 869
                             'QSG_desc'            => '',
870 870
                             'QSG_order'           => 1,
871 871
                             'QSG_show_group_name' => 1,
@@ -877,7 +877,7 @@  discard block
 block discarded – undo
877 877
                     case 2:
878 878
                         $QSG_values = array(
879 879
                             'QSG_name'            => __('Address Information', 'event_espresso'),
880
-                            'QSG_identifier'      => 'address-information-' . time(),
880
+                            'QSG_identifier'      => 'address-information-'.time(),
881 881
                             'QSG_desc'            => '',
882 882
                             'QSG_order'           => 2,
883 883
                             'QSG_show_group_name' => 1,
@@ -888,7 +888,7 @@  discard block
 block discarded – undo
888 888
                         break;
889 889
                 }
890 890
                 // make sure we have some values before inserting them
891
-                if (! empty($QSG_values)) {
891
+                if ( ! empty($QSG_values)) {
892 892
                     // insert system question
893 893
                     $wpdb->insert(
894 894
                         $table_name,
@@ -925,7 +925,7 @@  discard block
 block discarded – undo
925 925
             // reset values array
926 926
             $QST_values = array();
927 927
             // if we don't have what we should have
928
-            if (! in_array($QST_system, $questions)) {
928
+            if ( ! in_array($QST_system, $questions)) {
929 929
                 // add it
930 930
                 switch ($QST_system) {
931 931
                     case 'fname':
@@ -1077,7 +1077,7 @@  discard block
 block discarded – undo
1077 1077
                         );
1078 1078
                         break;
1079 1079
                 }
1080
-                if (! empty($QST_values)) {
1080
+                if ( ! empty($QST_values)) {
1081 1081
                     // insert system question
1082 1082
                     $wpdb->insert(
1083 1083
                         $table_name,
@@ -1138,7 +1138,7 @@  discard block
 block discarded – undo
1138 1138
      */
1139 1139
     public static function insert_default_payment_methods()
1140 1140
     {
1141
-        if (! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1141
+        if ( ! EEM_Payment_Method::instance()->count_active(EEM_Payment_Method::scope_cart)) {
1142 1142
             EE_Registry::instance()->load_lib('Payment_Method_Manager');
1143 1143
             EE_Payment_Method_Manager::instance()->activate_a_payment_method_of_type('Invoice');
1144 1144
         } else {
@@ -1427,7 +1427,7 @@  discard block
 block discarded – undo
1427 1427
         // this creates an array for tracking events that have no active ticket prices created
1428 1428
         // this allows us to warn admins of the situation so that it can be corrected
1429 1429
         $espresso_no_ticket_prices = get_option('ee_no_ticket_prices', false);
1430
-        if (! $espresso_no_ticket_prices) {
1430
+        if ( ! $espresso_no_ticket_prices) {
1431 1431
             add_option('ee_no_ticket_prices', array(), '', false);
1432 1432
         }
1433 1433
     }
@@ -1466,7 +1466,7 @@  discard block
 block discarded – undo
1466 1466
             }
1467 1467
         }
1468 1468
         //get all our CPTs
1469
-        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (" . implode(",", $ee_post_types) . ")";
1469
+        $query   = "SELECT ID FROM {$wpdb->posts} WHERE post_type IN (".implode(",", $ee_post_types).")";
1470 1470
         $cpt_ids = $wpdb->get_col($query);
1471 1471
         //delete each post meta and term relations too
1472 1472
         foreach ($cpt_ids as $post_id) {
@@ -1606,7 +1606,7 @@  discard block
 block discarded – undo
1606 1606
         if ($remove_all && $espresso_db_update = get_option('espresso_db_update')) {
1607 1607
             $db_update_sans_ee4 = array();
1608 1608
             foreach ($espresso_db_update as $version => $times_activated) {
1609
-                if ((string)$version[0] === '3') {//if its NON EE4
1609
+                if ((string) $version[0] === '3') {//if its NON EE4
1610 1610
                     $db_update_sans_ee4[$version] = $times_activated;
1611 1611
                 }
1612 1612
             }
Please login to merge, or discard this patch.
core/EE_System.core.php 1 patch
Indentation   +1249 added lines, -1249 removed lines patch added patch discarded remove patch
@@ -24,1255 +24,1255 @@
 block discarded – undo
24 24
 {
25 25
 
26 26
 
27
-    /**
28
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
29
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
30
-     */
31
-    const req_type_normal = 0;
32
-
33
-    /**
34
-     * Indicates this is a brand new installation of EE so we should install
35
-     * tables and default data etc
36
-     */
37
-    const req_type_new_activation = 1;
38
-
39
-    /**
40
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
41
-     * and we just exited maintenance mode). We MUST check the database is setup properly
42
-     * and that default data is setup too
43
-     */
44
-    const req_type_reactivation = 2;
45
-
46
-    /**
47
-     * indicates that EE has been upgraded since its previous request.
48
-     * We may have data migration scripts to call and will want to trigger maintenance mode
49
-     */
50
-    const req_type_upgrade = 3;
51
-
52
-    /**
53
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
54
-     */
55
-    const req_type_downgrade = 4;
56
-
57
-    /**
58
-     * @deprecated since version 4.6.0.dev.006
59
-     * Now whenever a new_activation is detected the request type is still just
60
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
61
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
62
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
63
-     * (Specifically, when the migration manager indicates migrations are finished
64
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
65
-     */
66
-    const req_type_activation_but_not_installed = 5;
67
-
68
-    /**
69
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
70
-     */
71
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
72
-
73
-
74
-    /**
75
-     * @var EE_System $_instance
76
-     */
77
-    private static $_instance;
78
-
79
-    /**
80
-     * @var EE_Registry $registry
81
-     */
82
-    private $registry;
83
-
84
-    /**
85
-     * @var LoaderInterface $loader
86
-     */
87
-    private $loader;
88
-
89
-    /**
90
-     * @var EE_Capabilities $capabilities
91
-     */
92
-    private $capabilities;
93
-
94
-    /**
95
-     * @var RequestInterface $request
96
-     */
97
-    private $request;
98
-
99
-    /**
100
-     * @var EE_Maintenance_Mode $maintenance_mode
101
-     */
102
-    private $maintenance_mode;
103
-
104
-    /**
105
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
106
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
107
-     *
108
-     * @var int $_req_type
109
-     */
110
-    private $_req_type;
111
-
112
-    /**
113
-     * Whether or not there was a non-micro version change in EE core version during this request
114
-     *
115
-     * @var boolean $_major_version_change
116
-     */
117
-    private $_major_version_change = false;
118
-
119
-    /**
120
-     * A Context DTO dedicated solely to identifying the current request type.
121
-     *
122
-     * @var RequestTypeContextCheckerInterface $request_type
123
-     */
124
-    private $request_type;
125
-
126
-
127
-
128
-    /**
129
-     * @singleton method used to instantiate class object
130
-     * @param EE_Registry|null         $registry
131
-     * @param LoaderInterface|null     $loader
132
-     * @param RequestInterface|null          $request
133
-     * @param EE_Maintenance_Mode|null $maintenance_mode
134
-     * @return EE_System
135
-     */
136
-    public static function instance(
137
-        EE_Registry $registry = null,
138
-        LoaderInterface $loader = null,
139
-        RequestInterface $request = null,
140
-        EE_Maintenance_Mode $maintenance_mode = null
141
-    ) {
142
-        // check if class object is instantiated
143
-        if (! self::$_instance instanceof EE_System) {
144
-            self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
145
-        }
146
-        return self::$_instance;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * resets the instance and returns it
153
-     *
154
-     * @return EE_System
155
-     */
156
-    public static function reset()
157
-    {
158
-        self::$_instance->_req_type = null;
159
-        //make sure none of the old hooks are left hanging around
160
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
161
-        //we need to reset the migration manager in order for it to detect DMSs properly
162
-        EE_Data_Migration_Manager::reset();
163
-        self::instance()->detect_activations_or_upgrades();
164
-        self::instance()->perform_activations_upgrades_and_migrations();
165
-        return self::instance();
166
-    }
167
-
168
-
169
-
170
-    /**
171
-     * sets hooks for running rest of system
172
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
173
-     * starting EE Addons from any other point may lead to problems
174
-     *
175
-     * @param EE_Registry         $registry
176
-     * @param LoaderInterface     $loader
177
-     * @param RequestInterface          $request
178
-     * @param EE_Maintenance_Mode $maintenance_mode
179
-     */
180
-    private function __construct(
181
-        EE_Registry $registry,
182
-        LoaderInterface $loader,
183
-        RequestInterface $request,
184
-        EE_Maintenance_Mode $maintenance_mode
185
-    ) {
186
-        $this->registry         = $registry;
187
-        $this->loader           = $loader;
188
-        $this->request          = $request;
189
-        $this->maintenance_mode = $maintenance_mode;
190
-        do_action('AHEE__EE_System__construct__begin', $this);
191
-        add_action(
192
-            'AHEE__EE_Bootstrap__load_espresso_addons',
193
-            array($this, 'loadCapabilities'),
194
-            5
195
-        );
196
-        add_action(
197
-            'AHEE__EE_Bootstrap__load_espresso_addons',
198
-            array($this, 'loadCommandBus'),
199
-            7
200
-        );
201
-        add_action(
202
-            'AHEE__EE_Bootstrap__load_espresso_addons',
203
-            array($this, 'loadPluginApi'),
204
-            9
205
-        );
206
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
207
-        add_action(
208
-            'AHEE__EE_Bootstrap__load_espresso_addons',
209
-            array($this, 'load_espresso_addons')
210
-        );
211
-        // when an ee addon is activated, we want to call the core hook(s) again
212
-        // because the newly-activated addon didn't get a chance to run at all
213
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
214
-        // detect whether install or upgrade
215
-        add_action(
216
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
217
-            array($this, 'detect_activations_or_upgrades'),
218
-            3
219
-        );
220
-        // load EE_Config, EE_Textdomain, etc
221
-        add_action(
222
-            'AHEE__EE_Bootstrap__load_core_configuration',
223
-            array($this, 'load_core_configuration'),
224
-            5
225
-        );
226
-        // load EE_Config, EE_Textdomain, etc
227
-        add_action(
228
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
229
-            array($this, 'register_shortcodes_modules_and_widgets'),
230
-            7
231
-        );
232
-        // you wanna get going? I wanna get going... let's get going!
233
-        add_action(
234
-            'AHEE__EE_Bootstrap__brew_espresso',
235
-            array($this, 'brew_espresso'),
236
-            9
237
-        );
238
-        //other housekeeping
239
-        //exclude EE critical pages from wp_list_pages
240
-        add_filter(
241
-            'wp_list_pages_excludes',
242
-            array($this, 'remove_pages_from_wp_list_pages'),
243
-            10
244
-        );
245
-        // ALL EE Addons should use the following hook point to attach their initial setup too
246
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
247
-        do_action('AHEE__EE_System__construct__complete', $this);
248
-    }
249
-
250
-
251
-    /**
252
-     * load and setup EE_Capabilities
253
-     *
254
-     * @return void
255
-     * @throws EE_Error
256
-     */
257
-    public function loadCapabilities()
258
-    {
259
-        $this->capabilities = $this->loader->getShared('EE_Capabilities');
260
-        add_action(
261
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
262
-            function ()
263
-            {
264
-                LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
265
-            }
266
-        );
267
-    }
268
-
269
-
270
-
271
-    /**
272
-     * create and cache the CommandBus, and also add middleware
273
-     * The CapChecker middleware requires the use of EE_Capabilities
274
-     * which is why we need to load the CommandBus after Caps are set up
275
-     *
276
-     * @return void
277
-     * @throws EE_Error
278
-     */
279
-    public function loadCommandBus()
280
-    {
281
-        $this->loader->getShared(
282
-            'CommandBusInterface',
283
-            array(
284
-                null,
285
-                apply_filters(
286
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
287
-                    array(
288
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
289
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
290
-                    )
291
-                ),
292
-            )
293
-        );
294
-    }
295
-
296
-
297
-
298
-    /**
299
-     * @return void
300
-     * @throws EE_Error
301
-     */
302
-    public function loadPluginApi()
303
-    {
304
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
305
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
306
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
307
-        $this->loader->getShared('EE_Request_Handler');
308
-    }
309
-
310
-
311
-    /**
312
-     * @param string $addon_name
313
-     * @param string $version_constant
314
-     * @param string $min_version_required
315
-     * @param string $load_callback
316
-     * @param string $plugin_file_constant
317
-     * @return void
318
-     */
319
-    private function deactivateIncompatibleAddon(
320
-        $addon_name,
321
-        $version_constant,
322
-        $min_version_required,
323
-        $load_callback,
324
-        $plugin_file_constant
325
-    ) {
326
-        if (! defined($version_constant)) {
327
-            return;
328
-        }
329
-        $addon_version = constant($version_constant);
330
-        if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
331
-            remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
332
-            if (! function_exists('deactivate_plugins')) {
333
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
334
-            }
335
-            deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
336
-            unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
337
-            EE_Error::add_error(
338
-                sprintf(
339
-                    esc_html__(
340
-                        'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
341
-                        'event_espresso'
342
-                    ),
343
-                    $addon_name,
344
-                    $min_version_required
345
-                ),
346
-                __FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
347
-            );
348
-            EE_Error::get_notices(false, true);
349
-        }
350
-    }
351
-
352
-
353
-    /**
354
-     * load_espresso_addons
355
-     * allow addons to load first so that they can set hooks for running DMS's, etc
356
-     * this is hooked into both:
357
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
358
-     *        which runs during the WP 'plugins_loaded' action at priority 5
359
-     *    and the WP 'activate_plugin' hook point
360
-     *
361
-     * @access public
362
-     * @return void
363
-     */
364
-    public function load_espresso_addons()
365
-    {
366
-        $this->deactivateIncompatibleAddon(
367
-            'Wait Lists',
368
-            'EE_WAIT_LISTS_VERSION',
369
-            '1.0.0.beta.074',
370
-            'load_espresso_wait_lists',
371
-            'EE_WAIT_LISTS_PLUGIN_FILE'
372
-        );
373
-        $this->deactivateIncompatibleAddon(
374
-            'Automated Upcoming Event Notifications',
375
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
376
-            '1.0.0.beta.091',
377
-            'load_espresso_automated_upcoming_event_notification',
378
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
379
-        );
380
-        do_action('AHEE__EE_System__load_espresso_addons');
381
-        //if the WP API basic auth plugin isn't already loaded, load it now.
382
-        //We want it for mobile apps. Just include the entire plugin
383
-        //also, don't load the basic auth when a plugin is getting activated, because
384
-        //it could be the basic auth plugin, and it doesn't check if its methods are already defined
385
-        //and causes a fatal error
386
-        if (
387
-            $this->request->getRequestParam('activate') !== 'true'
388
-            && ! function_exists('json_basic_auth_handler')
389
-            && ! function_exists('json_basic_auth_error')
390
-            && ! in_array(
391
-                $this->request->getRequestParam('action'),
392
-                array('activate', 'activate-selected'),
393
-                true
394
-            )
395
-        ) {
396
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
397
-        }
398
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
399
-    }
400
-
401
-
402
-
403
-    /**
404
-     * detect_activations_or_upgrades
405
-     * Checks for activation or upgrade of core first;
406
-     * then also checks if any registered addons have been activated or upgraded
407
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
408
-     * which runs during the WP 'plugins_loaded' action at priority 3
409
-     *
410
-     * @access public
411
-     * @return void
412
-     */
413
-    public function detect_activations_or_upgrades()
414
-    {
415
-        //first off: let's make sure to handle core
416
-        $this->detect_if_activation_or_upgrade();
417
-        foreach ($this->registry->addons as $addon) {
418
-            if ($addon instanceof EE_Addon) {
419
-                //detect teh request type for that addon
420
-                $addon->detect_activation_or_upgrade();
421
-            }
422
-        }
423
-    }
424
-
425
-
426
-
427
-    /**
428
-     * detect_if_activation_or_upgrade
429
-     * Takes care of detecting whether this is a brand new install or code upgrade,
430
-     * and either setting up the DB or setting up maintenance mode etc.
431
-     *
432
-     * @access public
433
-     * @return void
434
-     */
435
-    public function detect_if_activation_or_upgrade()
436
-    {
437
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
438
-        // check if db has been updated, or if its a brand-new installation
439
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
440
-        $request_type       = $this->detect_req_type($espresso_db_update);
441
-        //EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
442
-        switch ($request_type) {
443
-            case EE_System::req_type_new_activation:
444
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
445
-                $this->_handle_core_version_change($espresso_db_update);
446
-                break;
447
-            case EE_System::req_type_reactivation:
448
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
449
-                $this->_handle_core_version_change($espresso_db_update);
450
-                break;
451
-            case EE_System::req_type_upgrade:
452
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
453
-                //migrations may be required now that we've upgraded
454
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
455
-                $this->_handle_core_version_change($espresso_db_update);
456
-                //				echo "done upgrade";die;
457
-                break;
458
-            case EE_System::req_type_downgrade:
459
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
460
-                //its possible migrations are no longer required
461
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
462
-                $this->_handle_core_version_change($espresso_db_update);
463
-                break;
464
-            case EE_System::req_type_normal:
465
-            default:
466
-                break;
467
-        }
468
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
469
-    }
470
-
471
-
472
-
473
-    /**
474
-     * Updates the list of installed versions and sets hooks for
475
-     * initializing the database later during the request
476
-     *
477
-     * @param array $espresso_db_update
478
-     */
479
-    private function _handle_core_version_change($espresso_db_update)
480
-    {
481
-        $this->update_list_of_installed_versions($espresso_db_update);
482
-        //get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
483
-        add_action(
484
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
485
-            array($this, 'initialize_db_if_no_migrations_required')
486
-        );
487
-    }
488
-
489
-
490
-
491
-    /**
492
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
493
-     * information about what versions of EE have been installed and activated,
494
-     * NOT necessarily the state of the database
495
-     *
496
-     * @param mixed $espresso_db_update           the value of the WordPress option.
497
-     *                                            If not supplied, fetches it from the options table
498
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
499
-     */
500
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
501
-    {
502
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
503
-        if (! $espresso_db_update) {
504
-            $espresso_db_update = get_option('espresso_db_update');
505
-        }
506
-        // check that option is an array
507
-        if (! is_array($espresso_db_update)) {
508
-            // if option is FALSE, then it never existed
509
-            if ($espresso_db_update === false) {
510
-                // make $espresso_db_update an array and save option with autoload OFF
511
-                $espresso_db_update = array();
512
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
513
-            } else {
514
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
515
-                $espresso_db_update = array($espresso_db_update => array());
516
-                update_option('espresso_db_update', $espresso_db_update);
517
-            }
518
-        } else {
519
-            $corrected_db_update = array();
520
-            //if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
521
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
522
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
523
-                    //the key is an int, and the value IS NOT an array
524
-                    //so it must be numerically-indexed, where values are versions installed...
525
-                    //fix it!
526
-                    $version_string                         = $should_be_array;
527
-                    $corrected_db_update[ $version_string ] = array('unknown-date');
528
-                } else {
529
-                    //ok it checks out
530
-                    $corrected_db_update[ $should_be_version_string ] = $should_be_array;
531
-                }
532
-            }
533
-            $espresso_db_update = $corrected_db_update;
534
-            update_option('espresso_db_update', $espresso_db_update);
535
-        }
536
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
537
-        return $espresso_db_update;
538
-    }
539
-
540
-
541
-
542
-    /**
543
-     * Does the traditional work of setting up the plugin's database and adding default data.
544
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
545
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
546
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
547
-     * so that it will be done when migrations are finished
548
-     *
549
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
550
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
551
-     *                                       This is a resource-intensive job
552
-     *                                       so we prefer to only do it when necessary
553
-     * @return void
554
-     * @throws EE_Error
555
-     */
556
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
557
-    {
558
-        $request_type = $this->detect_req_type();
559
-        //only initialize system if we're not in maintenance mode.
560
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
561
-            update_option('ee_flush_rewrite_rules', true);
562
-            if ($verify_schema) {
563
-                EEH_Activation::initialize_db_and_folders();
564
-            }
565
-            EEH_Activation::initialize_db_content();
566
-            EEH_Activation::system_initialization();
567
-            if ($initialize_addons_too) {
568
-                $this->initialize_addons();
569
-            }
570
-        } else {
571
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
572
-        }
573
-        if ($request_type === EE_System::req_type_new_activation
574
-            || $request_type === EE_System::req_type_reactivation
575
-            || (
576
-                $request_type === EE_System::req_type_upgrade
577
-                && $this->is_major_version_change()
578
-            )
579
-        ) {
580
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
581
-        }
582
-    }
583
-
584
-
585
-
586
-    /**
587
-     * Initializes the db for all registered addons
588
-     *
589
-     * @throws EE_Error
590
-     */
591
-    public function initialize_addons()
592
-    {
593
-        //foreach registered addon, make sure its db is up-to-date too
594
-        foreach ($this->registry->addons as $addon) {
595
-            if ($addon instanceof EE_Addon) {
596
-                $addon->initialize_db_if_no_migrations_required();
597
-            }
598
-        }
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
605
-     *
606
-     * @param    array  $version_history
607
-     * @param    string $current_version_to_add version to be added to the version history
608
-     * @return    boolean success as to whether or not this option was changed
609
-     */
610
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
611
-    {
612
-        if (! $version_history) {
613
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
614
-        }
615
-        if ($current_version_to_add === null) {
616
-            $current_version_to_add = espresso_version();
617
-        }
618
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
619
-        // re-save
620
-        return update_option('espresso_db_update', $version_history);
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * Detects if the current version indicated in the has existed in the list of
627
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
628
-     *
629
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
630
-     *                                  If not supplied, fetches it from the options table.
631
-     *                                  Also, caches its result so later parts of the code can also know whether
632
-     *                                  there's been an update or not. This way we can add the current version to
633
-     *                                  espresso_db_update, but still know if this is a new install or not
634
-     * @return int one of the constants on EE_System::req_type_
635
-     */
636
-    public function detect_req_type($espresso_db_update = null)
637
-    {
638
-        if ($this->_req_type === null) {
639
-            $espresso_db_update          = ! empty($espresso_db_update)
640
-                ? $espresso_db_update
641
-                : $this->fix_espresso_db_upgrade_option();
642
-            $this->_req_type             = EE_System::detect_req_type_given_activation_history(
643
-                $espresso_db_update,
644
-                'ee_espresso_activation', espresso_version()
645
-            );
646
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
647
-            $this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
648
-        }
649
-        return $this->_req_type;
650
-    }
651
-
652
-
653
-
654
-    /**
655
-     * Returns whether or not there was a non-micro version change (ie, change in either
656
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
657
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
658
-     *
659
-     * @param $activation_history
660
-     * @return bool
661
-     */
662
-    private function _detect_major_version_change($activation_history)
663
-    {
664
-        $previous_version       = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
665
-        $previous_version_parts = explode('.', $previous_version);
666
-        $current_version_parts  = explode('.', espresso_version());
667
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
668
-               && ($previous_version_parts[0] !== $current_version_parts[0]
669
-                   || $previous_version_parts[1] !== $current_version_parts[1]
670
-               );
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * Returns true if either the major or minor version of EE changed during this request.
677
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
678
-     *
679
-     * @return bool
680
-     */
681
-    public function is_major_version_change()
682
-    {
683
-        return $this->_major_version_change;
684
-    }
685
-
686
-
687
-
688
-    /**
689
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
690
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
691
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
692
-     * just activated to (for core that will always be espresso_version())
693
-     *
694
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
695
-     *                                                 ee plugin. for core that's 'espresso_db_update'
696
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
697
-     *                                                 indicate that this plugin was just activated
698
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
699
-     *                                                 espresso_version())
700
-     * @return int one of the constants on EE_System::req_type_*
701
-     */
702
-    public static function detect_req_type_given_activation_history(
703
-        $activation_history_for_addon,
704
-        $activation_indicator_option_name,
705
-        $version_to_upgrade_to
706
-    ) {
707
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
708
-        if ($activation_history_for_addon) {
709
-            //it exists, so this isn't a completely new install
710
-            //check if this version already in that list of previously installed versions
711
-            if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
712
-                //it a version we haven't seen before
713
-                if ($version_is_higher === 1) {
714
-                    $req_type = EE_System::req_type_upgrade;
715
-                } else {
716
-                    $req_type = EE_System::req_type_downgrade;
717
-                }
718
-                delete_option($activation_indicator_option_name);
719
-            } else {
720
-                // its not an update. maybe a reactivation?
721
-                if (get_option($activation_indicator_option_name, false)) {
722
-                    if ($version_is_higher === -1) {
723
-                        $req_type = EE_System::req_type_downgrade;
724
-                    } elseif ($version_is_higher === 0) {
725
-                        //we've seen this version before, but it's an activation. must be a reactivation
726
-                        $req_type = EE_System::req_type_reactivation;
727
-                    } else {//$version_is_higher === 1
728
-                        $req_type = EE_System::req_type_upgrade;
729
-                    }
730
-                    delete_option($activation_indicator_option_name);
731
-                } else {
732
-                    //we've seen this version before and the activation indicate doesn't show it was just activated
733
-                    if ($version_is_higher === -1) {
734
-                        $req_type = EE_System::req_type_downgrade;
735
-                    } elseif ($version_is_higher === 0) {
736
-                        //we've seen this version before and it's not an activation. its normal request
737
-                        $req_type = EE_System::req_type_normal;
738
-                    } else {//$version_is_higher === 1
739
-                        $req_type = EE_System::req_type_upgrade;
740
-                    }
741
-                }
742
-            }
743
-        } else {
744
-            //brand new install
745
-            $req_type = EE_System::req_type_new_activation;
746
-            delete_option($activation_indicator_option_name);
747
-        }
748
-        return $req_type;
749
-    }
750
-
751
-
752
-
753
-    /**
754
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
755
-     * the $activation_history_for_addon
756
-     *
757
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
758
-     *                                             sometimes containing 'unknown-date'
759
-     * @param string $version_to_upgrade_to        (current version)
760
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
761
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
762
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
763
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
764
-     */
765
-    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
766
-    {
767
-        //find the most recently-activated version
768
-        $most_recently_active_version =
769
-            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
770
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
771
-    }
772
-
773
-
774
-
775
-    /**
776
-     * Gets the most recently active version listed in the activation history,
777
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
778
-     *
779
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
780
-     *                                   sometimes containing 'unknown-date'
781
-     * @return string
782
-     */
783
-    private static function _get_most_recently_active_version_from_activation_history($activation_history)
784
-    {
785
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
786
-        $most_recently_active_version            = '0.0.0.dev.000';
787
-        if (is_array($activation_history)) {
788
-            foreach ($activation_history as $version => $times_activated) {
789
-                //check there is a record of when this version was activated. Otherwise,
790
-                //mark it as unknown
791
-                if (! $times_activated) {
792
-                    $times_activated = array('unknown-date');
793
-                }
794
-                if (is_string($times_activated)) {
795
-                    $times_activated = array($times_activated);
796
-                }
797
-                foreach ($times_activated as $an_activation) {
798
-                    if ($an_activation !== 'unknown-date'
799
-                        && $an_activation
800
-                           > $most_recently_active_version_activation) {
801
-                        $most_recently_active_version            = $version;
802
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
803
-                            ? '1970-01-01 00:00:00'
804
-                            : $an_activation;
805
-                    }
806
-                }
807
-            }
808
-        }
809
-        return $most_recently_active_version;
810
-    }
811
-
812
-
813
-
814
-    /**
815
-     * This redirects to the about EE page after activation
816
-     *
817
-     * @return void
818
-     */
819
-    public function redirect_to_about_ee()
820
-    {
821
-        $notices = EE_Error::get_notices(false);
822
-        //if current user is an admin and it's not an ajax or rest request
823
-        if (
824
-            ! isset($notices['errors'])
825
-            && $this->request->isAdmin()
826
-            && apply_filters(
827
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
828
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
829
-            )
830
-        ) {
831
-            $query_params = array('page' => 'espresso_about');
832
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
833
-                $query_params['new_activation'] = true;
834
-            }
835
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
836
-                $query_params['reactivation'] = true;
837
-            }
838
-            $url = add_query_arg($query_params, admin_url('admin.php'));
839
-            wp_safe_redirect($url);
840
-            exit();
841
-        }
842
-    }
843
-
844
-
845
-
846
-    /**
847
-     * load_core_configuration
848
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
849
-     * which runs during the WP 'plugins_loaded' action at priority 5
850
-     *
851
-     * @return void
852
-     * @throws ReflectionException
853
-     */
854
-    public function load_core_configuration()
855
-    {
856
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
857
-        $this->loader->getShared('EE_Load_Textdomain');
858
-        //load textdomain
859
-        EE_Load_Textdomain::load_textdomain();
860
-        // load and setup EE_Config and EE_Network_Config
861
-        $config = $this->loader->getShared('EE_Config');
862
-        $this->loader->getShared('EE_Network_Config');
863
-        // setup autoloaders
864
-        // enable logging?
865
-        if ($config->admin->use_full_logging) {
866
-            $this->loader->getShared('EE_Log');
867
-        }
868
-        // check for activation errors
869
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
870
-        if ($activation_errors) {
871
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
872
-            update_option('ee_plugin_activation_errors', false);
873
-        }
874
-        // get model names
875
-        $this->_parse_model_names();
876
-        //load caf stuff a chance to play during the activation process too.
877
-        $this->_maybe_brew_regular();
878
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
879
-    }
880
-
881
-
882
-
883
-    /**
884
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
885
-     *
886
-     * @return void
887
-     * @throws ReflectionException
888
-     */
889
-    private function _parse_model_names()
890
-    {
891
-        //get all the files in the EE_MODELS folder that end in .model.php
892
-        $models                 = glob(EE_MODELS . '*.model.php');
893
-        $model_names            = array();
894
-        $non_abstract_db_models = array();
895
-        foreach ($models as $model) {
896
-            // get model classname
897
-            $classname       = EEH_File::get_classname_from_filepath_with_standard_filename($model);
898
-            $short_name      = str_replace('EEM_', '', $classname);
899
-            $reflectionClass = new ReflectionClass($classname);
900
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
901
-                $non_abstract_db_models[ $short_name ] = $classname;
902
-            }
903
-            $model_names[ $short_name ] = $classname;
904
-        }
905
-        $this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
906
-        $this->registry->non_abstract_db_models = apply_filters(
907
-            'FHEE__EE_System__parse_implemented_model_names',
908
-            $non_abstract_db_models
909
-        );
910
-    }
911
-
912
-
913
-
914
-    /**
915
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
916
-     * that need to be setup before our EE_System launches.
917
-     *
918
-     * @return void
919
-     */
920
-    private function _maybe_brew_regular()
921
-    {
922
-        if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
923
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
924
-        }
925
-    }
926
-
927
-
928
-
929
-    /**
930
-     * register_shortcodes_modules_and_widgets
931
-     * generate lists of shortcodes and modules, then verify paths and classes
932
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
933
-     * which runs during the WP 'plugins_loaded' action at priority 7
934
-     *
935
-     * @access public
936
-     * @return void
937
-     * @throws Exception
938
-     */
939
-    public function register_shortcodes_modules_and_widgets()
940
-    {
941
-        if ($this->request->isFrontend() || $this->request->isIframe()) {
942
-            try {
943
-                // load, register, and add shortcodes the new way
944
-                $this->loader->getShared(
945
-                    'EventEspresso\core\services\shortcodes\ShortcodesManager',
946
-                    array(
947
-                        // and the old way, but we'll put it under control of the new system
948
-                        EE_Config::getLegacyShortcodesManager(),
949
-                    )
950
-                );
951
-            } catch (Exception $exception) {
952
-                new ExceptionStackTraceDisplay($exception);
953
-            }
954
-        }
955
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
956
-        // check for addons using old hook point
957
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
958
-            $this->_incompatible_addon_error();
959
-        }
960
-    }
961
-
962
-
963
-
964
-    /**
965
-     * _incompatible_addon_error
966
-     *
967
-     * @access public
968
-     * @return void
969
-     */
970
-    private function _incompatible_addon_error()
971
-    {
972
-        // get array of classes hooking into here
973
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
974
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
975
-        );
976
-        if (! empty($class_names)) {
977
-            $msg = __(
978
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
979
-                'event_espresso'
980
-            );
981
-            $msg .= '<ul>';
982
-            foreach ($class_names as $class_name) {
983
-                $msg .= '<li><b>Event Espresso - ' . str_replace(
984
-                        array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
985
-                        $class_name
986
-                    ) . '</b></li>';
987
-            }
988
-            $msg .= '</ul>';
989
-            $msg .= __(
990
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
991
-                'event_espresso'
992
-            );
993
-            // save list of incompatible addons to wp-options for later use
994
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
995
-            if (is_admin()) {
996
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
997
-            }
998
-        }
999
-    }
1000
-
1001
-
1002
-
1003
-    /**
1004
-     * brew_espresso
1005
-     * begins the process of setting hooks for initializing EE in the correct order
1006
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1007
-     * which runs during the WP 'plugins_loaded' action at priority 9
1008
-     *
1009
-     * @return void
1010
-     */
1011
-    public function brew_espresso()
1012
-    {
1013
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
1014
-        // load some final core systems
1015
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
1016
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1017
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
1018
-        add_action('init', array($this, 'load_controllers'), 7);
1019
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
1020
-        add_action('init', array($this, 'initialize'), 10);
1021
-        add_action('init', array($this, 'initialize_last'), 100);
1022
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1023
-            // pew pew pew
1024
-            $this->loader->getShared('EE_PUE');
1025
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1026
-        }
1027
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
1028
-    }
1029
-
1030
-
1031
-
1032
-    /**
1033
-     *    set_hooks_for_core
1034
-     *
1035
-     * @access public
1036
-     * @return    void
1037
-     * @throws EE_Error
1038
-     */
1039
-    public function set_hooks_for_core()
1040
-    {
1041
-        $this->_deactivate_incompatible_addons();
1042
-        do_action('AHEE__EE_System__set_hooks_for_core');
1043
-        //caps need to be initialized on every request so that capability maps are set.
1044
-        //@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1045
-        $this->registry->CAP->init_caps();
1046
-    }
1047
-
1048
-
1049
-
1050
-    /**
1051
-     * Using the information gathered in EE_System::_incompatible_addon_error,
1052
-     * deactivates any addons considered incompatible with the current version of EE
1053
-     */
1054
-    private function _deactivate_incompatible_addons()
1055
-    {
1056
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
1057
-        if (! empty($incompatible_addons)) {
1058
-            $active_plugins = get_option('active_plugins', array());
1059
-            foreach ($active_plugins as $active_plugin) {
1060
-                foreach ($incompatible_addons as $incompatible_addon) {
1061
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1062
-                        unset($_GET['activate']);
1063
-                        espresso_deactivate_plugin($active_plugin);
1064
-                    }
1065
-                }
1066
-            }
1067
-        }
1068
-    }
1069
-
1070
-
1071
-
1072
-    /**
1073
-     *    perform_activations_upgrades_and_migrations
1074
-     *
1075
-     * @access public
1076
-     * @return    void
1077
-     */
1078
-    public function perform_activations_upgrades_and_migrations()
1079
-    {
1080
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1081
-    }
1082
-
1083
-
1084
-
1085
-    /**
1086
-     *    load_CPTs_and_session
1087
-     *
1088
-     * @access public
1089
-     * @return    void
1090
-     */
1091
-    public function load_CPTs_and_session()
1092
-    {
1093
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1094
-        // register Custom Post Types
1095
-        $this->loader->getShared('EE_Register_CPTs');
1096
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1097
-    }
1098
-
1099
-
1100
-
1101
-    /**
1102
-     * load_controllers
1103
-     * this is the best place to load any additional controllers that needs access to EE core.
1104
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1105
-     * time
1106
-     *
1107
-     * @access public
1108
-     * @return void
1109
-     */
1110
-    public function load_controllers()
1111
-    {
1112
-        do_action('AHEE__EE_System__load_controllers__start');
1113
-        // let's get it started
1114
-        if (
1115
-            ! $this->maintenance_mode->level()
1116
-            && ($this->request->isFrontend() || $this->request->isFrontAjax())
1117
-        ) {
1118
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1119
-            $this->loader->getShared('EE_Front_Controller');
1120
-        } elseif ($this->request->isAdmin() || $this->request->isAdminAjax()) {
1121
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1122
-            $this->loader->getShared('EE_Admin');
1123
-        }
1124
-        do_action('AHEE__EE_System__load_controllers__complete');
1125
-    }
1126
-
1127
-
1128
-
1129
-    /**
1130
-     * core_loaded_and_ready
1131
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1132
-     *
1133
-     * @access public
1134
-     * @return void
1135
-     */
1136
-    public function core_loaded_and_ready()
1137
-    {
1138
-        if (
1139
-            $this->request->isAdmin()
1140
-            || $this->request->isEeAjax()
1141
-            || $this->request->isFrontend()
1142
-        ) {
1143
-            $this->loader->getShared('EE_Session');
1144
-        }
1145
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1146
-        // load_espresso_template_tags
1147
-        if (
1148
-            is_readable(EE_PUBLIC . 'template_tags.php')
1149
-            && ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isFeed())
1150
-        ) {
1151
-            require_once EE_PUBLIC . 'template_tags.php';
1152
-        }
1153
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1154
-        if ($this->request->isAdmin() || $this->request->isFrontend() || $this->request->isIframe()) {
1155
-            $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1156
-        }
1157
-    }
1158
-
1159
-
1160
-
1161
-    /**
1162
-     * initialize
1163
-     * this is the best place to begin initializing client code
1164
-     *
1165
-     * @access public
1166
-     * @return void
1167
-     */
1168
-    public function initialize()
1169
-    {
1170
-        do_action('AHEE__EE_System__initialize');
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * initialize_last
1177
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1178
-     * initialize has done so
1179
-     *
1180
-     * @access public
1181
-     * @return void
1182
-     */
1183
-    public function initialize_last()
1184
-    {
1185
-        do_action('AHEE__EE_System__initialize_last');
1186
-        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1187
-    }
1188
-
1189
-
1190
-
1191
-    /**
1192
-     * @return void
1193
-     * @throws EE_Error
1194
-     */
1195
-    public function addEspressoToolbar()
1196
-    {
1197
-        $this->loader->getShared(
1198
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1199
-            array($this->registry->CAP)
1200
-        );
1201
-    }
1202
-
1203
-
1204
-
1205
-    /**
1206
-     * do_not_cache
1207
-     * sets no cache headers and defines no cache constants for WP plugins
1208
-     *
1209
-     * @access public
1210
-     * @return void
1211
-     */
1212
-    public static function do_not_cache()
1213
-    {
1214
-        // set no cache constants
1215
-        if (! defined('DONOTCACHEPAGE')) {
1216
-            define('DONOTCACHEPAGE', true);
1217
-        }
1218
-        if (! defined('DONOTCACHCEOBJECT')) {
1219
-            define('DONOTCACHCEOBJECT', true);
1220
-        }
1221
-        if (! defined('DONOTCACHEDB')) {
1222
-            define('DONOTCACHEDB', true);
1223
-        }
1224
-        // add no cache headers
1225
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1226
-        // plus a little extra for nginx and Google Chrome
1227
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1228
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1229
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1230
-    }
1231
-
1232
-
1233
-
1234
-    /**
1235
-     *    extra_nocache_headers
1236
-     *
1237
-     * @access    public
1238
-     * @param $headers
1239
-     * @return    array
1240
-     */
1241
-    public static function extra_nocache_headers($headers)
1242
-    {
1243
-        // for NGINX
1244
-        $headers['X-Accel-Expires'] = 0;
1245
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1246
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1247
-        return $headers;
1248
-    }
1249
-
1250
-
1251
-
1252
-    /**
1253
-     *    nocache_headers
1254
-     *
1255
-     * @access    public
1256
-     * @return    void
1257
-     */
1258
-    public static function nocache_headers()
1259
-    {
1260
-        nocache_headers();
1261
-    }
1262
-
1263
-
1264
-
1265
-    /**
1266
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1267
-     * never returned with the function.
1268
-     *
1269
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1270
-     * @return array
1271
-     */
1272
-    public function remove_pages_from_wp_list_pages($exclude_array)
1273
-    {
1274
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1275
-    }
27
+	/**
28
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
29
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
30
+	 */
31
+	const req_type_normal = 0;
32
+
33
+	/**
34
+	 * Indicates this is a brand new installation of EE so we should install
35
+	 * tables and default data etc
36
+	 */
37
+	const req_type_new_activation = 1;
38
+
39
+	/**
40
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
41
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
42
+	 * and that default data is setup too
43
+	 */
44
+	const req_type_reactivation = 2;
45
+
46
+	/**
47
+	 * indicates that EE has been upgraded since its previous request.
48
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
49
+	 */
50
+	const req_type_upgrade = 3;
51
+
52
+	/**
53
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
54
+	 */
55
+	const req_type_downgrade = 4;
56
+
57
+	/**
58
+	 * @deprecated since version 4.6.0.dev.006
59
+	 * Now whenever a new_activation is detected the request type is still just
60
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
61
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
62
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
63
+	 * (Specifically, when the migration manager indicates migrations are finished
64
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
65
+	 */
66
+	const req_type_activation_but_not_installed = 5;
67
+
68
+	/**
69
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
70
+	 */
71
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
72
+
73
+
74
+	/**
75
+	 * @var EE_System $_instance
76
+	 */
77
+	private static $_instance;
78
+
79
+	/**
80
+	 * @var EE_Registry $registry
81
+	 */
82
+	private $registry;
83
+
84
+	/**
85
+	 * @var LoaderInterface $loader
86
+	 */
87
+	private $loader;
88
+
89
+	/**
90
+	 * @var EE_Capabilities $capabilities
91
+	 */
92
+	private $capabilities;
93
+
94
+	/**
95
+	 * @var RequestInterface $request
96
+	 */
97
+	private $request;
98
+
99
+	/**
100
+	 * @var EE_Maintenance_Mode $maintenance_mode
101
+	 */
102
+	private $maintenance_mode;
103
+
104
+	/**
105
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
106
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
107
+	 *
108
+	 * @var int $_req_type
109
+	 */
110
+	private $_req_type;
111
+
112
+	/**
113
+	 * Whether or not there was a non-micro version change in EE core version during this request
114
+	 *
115
+	 * @var boolean $_major_version_change
116
+	 */
117
+	private $_major_version_change = false;
118
+
119
+	/**
120
+	 * A Context DTO dedicated solely to identifying the current request type.
121
+	 *
122
+	 * @var RequestTypeContextCheckerInterface $request_type
123
+	 */
124
+	private $request_type;
125
+
126
+
127
+
128
+	/**
129
+	 * @singleton method used to instantiate class object
130
+	 * @param EE_Registry|null         $registry
131
+	 * @param LoaderInterface|null     $loader
132
+	 * @param RequestInterface|null          $request
133
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
134
+	 * @return EE_System
135
+	 */
136
+	public static function instance(
137
+		EE_Registry $registry = null,
138
+		LoaderInterface $loader = null,
139
+		RequestInterface $request = null,
140
+		EE_Maintenance_Mode $maintenance_mode = null
141
+	) {
142
+		// check if class object is instantiated
143
+		if (! self::$_instance instanceof EE_System) {
144
+			self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
145
+		}
146
+		return self::$_instance;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * resets the instance and returns it
153
+	 *
154
+	 * @return EE_System
155
+	 */
156
+	public static function reset()
157
+	{
158
+		self::$_instance->_req_type = null;
159
+		//make sure none of the old hooks are left hanging around
160
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
161
+		//we need to reset the migration manager in order for it to detect DMSs properly
162
+		EE_Data_Migration_Manager::reset();
163
+		self::instance()->detect_activations_or_upgrades();
164
+		self::instance()->perform_activations_upgrades_and_migrations();
165
+		return self::instance();
166
+	}
167
+
168
+
169
+
170
+	/**
171
+	 * sets hooks for running rest of system
172
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
173
+	 * starting EE Addons from any other point may lead to problems
174
+	 *
175
+	 * @param EE_Registry         $registry
176
+	 * @param LoaderInterface     $loader
177
+	 * @param RequestInterface          $request
178
+	 * @param EE_Maintenance_Mode $maintenance_mode
179
+	 */
180
+	private function __construct(
181
+		EE_Registry $registry,
182
+		LoaderInterface $loader,
183
+		RequestInterface $request,
184
+		EE_Maintenance_Mode $maintenance_mode
185
+	) {
186
+		$this->registry         = $registry;
187
+		$this->loader           = $loader;
188
+		$this->request          = $request;
189
+		$this->maintenance_mode = $maintenance_mode;
190
+		do_action('AHEE__EE_System__construct__begin', $this);
191
+		add_action(
192
+			'AHEE__EE_Bootstrap__load_espresso_addons',
193
+			array($this, 'loadCapabilities'),
194
+			5
195
+		);
196
+		add_action(
197
+			'AHEE__EE_Bootstrap__load_espresso_addons',
198
+			array($this, 'loadCommandBus'),
199
+			7
200
+		);
201
+		add_action(
202
+			'AHEE__EE_Bootstrap__load_espresso_addons',
203
+			array($this, 'loadPluginApi'),
204
+			9
205
+		);
206
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
207
+		add_action(
208
+			'AHEE__EE_Bootstrap__load_espresso_addons',
209
+			array($this, 'load_espresso_addons')
210
+		);
211
+		// when an ee addon is activated, we want to call the core hook(s) again
212
+		// because the newly-activated addon didn't get a chance to run at all
213
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
214
+		// detect whether install or upgrade
215
+		add_action(
216
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
217
+			array($this, 'detect_activations_or_upgrades'),
218
+			3
219
+		);
220
+		// load EE_Config, EE_Textdomain, etc
221
+		add_action(
222
+			'AHEE__EE_Bootstrap__load_core_configuration',
223
+			array($this, 'load_core_configuration'),
224
+			5
225
+		);
226
+		// load EE_Config, EE_Textdomain, etc
227
+		add_action(
228
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
229
+			array($this, 'register_shortcodes_modules_and_widgets'),
230
+			7
231
+		);
232
+		// you wanna get going? I wanna get going... let's get going!
233
+		add_action(
234
+			'AHEE__EE_Bootstrap__brew_espresso',
235
+			array($this, 'brew_espresso'),
236
+			9
237
+		);
238
+		//other housekeeping
239
+		//exclude EE critical pages from wp_list_pages
240
+		add_filter(
241
+			'wp_list_pages_excludes',
242
+			array($this, 'remove_pages_from_wp_list_pages'),
243
+			10
244
+		);
245
+		// ALL EE Addons should use the following hook point to attach their initial setup too
246
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
247
+		do_action('AHEE__EE_System__construct__complete', $this);
248
+	}
249
+
250
+
251
+	/**
252
+	 * load and setup EE_Capabilities
253
+	 *
254
+	 * @return void
255
+	 * @throws EE_Error
256
+	 */
257
+	public function loadCapabilities()
258
+	{
259
+		$this->capabilities = $this->loader->getShared('EE_Capabilities');
260
+		add_action(
261
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
262
+			function ()
263
+			{
264
+				LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
265
+			}
266
+		);
267
+	}
268
+
269
+
270
+
271
+	/**
272
+	 * create and cache the CommandBus, and also add middleware
273
+	 * The CapChecker middleware requires the use of EE_Capabilities
274
+	 * which is why we need to load the CommandBus after Caps are set up
275
+	 *
276
+	 * @return void
277
+	 * @throws EE_Error
278
+	 */
279
+	public function loadCommandBus()
280
+	{
281
+		$this->loader->getShared(
282
+			'CommandBusInterface',
283
+			array(
284
+				null,
285
+				apply_filters(
286
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
287
+					array(
288
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
289
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
290
+					)
291
+				),
292
+			)
293
+		);
294
+	}
295
+
296
+
297
+
298
+	/**
299
+	 * @return void
300
+	 * @throws EE_Error
301
+	 */
302
+	public function loadPluginApi()
303
+	{
304
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
305
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
306
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
307
+		$this->loader->getShared('EE_Request_Handler');
308
+	}
309
+
310
+
311
+	/**
312
+	 * @param string $addon_name
313
+	 * @param string $version_constant
314
+	 * @param string $min_version_required
315
+	 * @param string $load_callback
316
+	 * @param string $plugin_file_constant
317
+	 * @return void
318
+	 */
319
+	private function deactivateIncompatibleAddon(
320
+		$addon_name,
321
+		$version_constant,
322
+		$min_version_required,
323
+		$load_callback,
324
+		$plugin_file_constant
325
+	) {
326
+		if (! defined($version_constant)) {
327
+			return;
328
+		}
329
+		$addon_version = constant($version_constant);
330
+		if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
331
+			remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
332
+			if (! function_exists('deactivate_plugins')) {
333
+				require_once ABSPATH . 'wp-admin/includes/plugin.php';
334
+			}
335
+			deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
336
+			unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
337
+			EE_Error::add_error(
338
+				sprintf(
339
+					esc_html__(
340
+						'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
341
+						'event_espresso'
342
+					),
343
+					$addon_name,
344
+					$min_version_required
345
+				),
346
+				__FILE__, __FUNCTION__ . "({$addon_name})", __LINE__
347
+			);
348
+			EE_Error::get_notices(false, true);
349
+		}
350
+	}
351
+
352
+
353
+	/**
354
+	 * load_espresso_addons
355
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
356
+	 * this is hooked into both:
357
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
358
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
359
+	 *    and the WP 'activate_plugin' hook point
360
+	 *
361
+	 * @access public
362
+	 * @return void
363
+	 */
364
+	public function load_espresso_addons()
365
+	{
366
+		$this->deactivateIncompatibleAddon(
367
+			'Wait Lists',
368
+			'EE_WAIT_LISTS_VERSION',
369
+			'1.0.0.beta.074',
370
+			'load_espresso_wait_lists',
371
+			'EE_WAIT_LISTS_PLUGIN_FILE'
372
+		);
373
+		$this->deactivateIncompatibleAddon(
374
+			'Automated Upcoming Event Notifications',
375
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
376
+			'1.0.0.beta.091',
377
+			'load_espresso_automated_upcoming_event_notification',
378
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
379
+		);
380
+		do_action('AHEE__EE_System__load_espresso_addons');
381
+		//if the WP API basic auth plugin isn't already loaded, load it now.
382
+		//We want it for mobile apps. Just include the entire plugin
383
+		//also, don't load the basic auth when a plugin is getting activated, because
384
+		//it could be the basic auth plugin, and it doesn't check if its methods are already defined
385
+		//and causes a fatal error
386
+		if (
387
+			$this->request->getRequestParam('activate') !== 'true'
388
+			&& ! function_exists('json_basic_auth_handler')
389
+			&& ! function_exists('json_basic_auth_error')
390
+			&& ! in_array(
391
+				$this->request->getRequestParam('action'),
392
+				array('activate', 'activate-selected'),
393
+				true
394
+			)
395
+		) {
396
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth' . DS . 'basic-auth.php';
397
+		}
398
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
399
+	}
400
+
401
+
402
+
403
+	/**
404
+	 * detect_activations_or_upgrades
405
+	 * Checks for activation or upgrade of core first;
406
+	 * then also checks if any registered addons have been activated or upgraded
407
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
408
+	 * which runs during the WP 'plugins_loaded' action at priority 3
409
+	 *
410
+	 * @access public
411
+	 * @return void
412
+	 */
413
+	public function detect_activations_or_upgrades()
414
+	{
415
+		//first off: let's make sure to handle core
416
+		$this->detect_if_activation_or_upgrade();
417
+		foreach ($this->registry->addons as $addon) {
418
+			if ($addon instanceof EE_Addon) {
419
+				//detect teh request type for that addon
420
+				$addon->detect_activation_or_upgrade();
421
+			}
422
+		}
423
+	}
424
+
425
+
426
+
427
+	/**
428
+	 * detect_if_activation_or_upgrade
429
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
430
+	 * and either setting up the DB or setting up maintenance mode etc.
431
+	 *
432
+	 * @access public
433
+	 * @return void
434
+	 */
435
+	public function detect_if_activation_or_upgrade()
436
+	{
437
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
438
+		// check if db has been updated, or if its a brand-new installation
439
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
440
+		$request_type       = $this->detect_req_type($espresso_db_update);
441
+		//EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
442
+		switch ($request_type) {
443
+			case EE_System::req_type_new_activation:
444
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
445
+				$this->_handle_core_version_change($espresso_db_update);
446
+				break;
447
+			case EE_System::req_type_reactivation:
448
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
449
+				$this->_handle_core_version_change($espresso_db_update);
450
+				break;
451
+			case EE_System::req_type_upgrade:
452
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
453
+				//migrations may be required now that we've upgraded
454
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
455
+				$this->_handle_core_version_change($espresso_db_update);
456
+				//				echo "done upgrade";die;
457
+				break;
458
+			case EE_System::req_type_downgrade:
459
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
460
+				//its possible migrations are no longer required
461
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
462
+				$this->_handle_core_version_change($espresso_db_update);
463
+				break;
464
+			case EE_System::req_type_normal:
465
+			default:
466
+				break;
467
+		}
468
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
469
+	}
470
+
471
+
472
+
473
+	/**
474
+	 * Updates the list of installed versions and sets hooks for
475
+	 * initializing the database later during the request
476
+	 *
477
+	 * @param array $espresso_db_update
478
+	 */
479
+	private function _handle_core_version_change($espresso_db_update)
480
+	{
481
+		$this->update_list_of_installed_versions($espresso_db_update);
482
+		//get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
483
+		add_action(
484
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
485
+			array($this, 'initialize_db_if_no_migrations_required')
486
+		);
487
+	}
488
+
489
+
490
+
491
+	/**
492
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
493
+	 * information about what versions of EE have been installed and activated,
494
+	 * NOT necessarily the state of the database
495
+	 *
496
+	 * @param mixed $espresso_db_update           the value of the WordPress option.
497
+	 *                                            If not supplied, fetches it from the options table
498
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
499
+	 */
500
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
501
+	{
502
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
503
+		if (! $espresso_db_update) {
504
+			$espresso_db_update = get_option('espresso_db_update');
505
+		}
506
+		// check that option is an array
507
+		if (! is_array($espresso_db_update)) {
508
+			// if option is FALSE, then it never existed
509
+			if ($espresso_db_update === false) {
510
+				// make $espresso_db_update an array and save option with autoload OFF
511
+				$espresso_db_update = array();
512
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
513
+			} else {
514
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
515
+				$espresso_db_update = array($espresso_db_update => array());
516
+				update_option('espresso_db_update', $espresso_db_update);
517
+			}
518
+		} else {
519
+			$corrected_db_update = array();
520
+			//if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
521
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
522
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
523
+					//the key is an int, and the value IS NOT an array
524
+					//so it must be numerically-indexed, where values are versions installed...
525
+					//fix it!
526
+					$version_string                         = $should_be_array;
527
+					$corrected_db_update[ $version_string ] = array('unknown-date');
528
+				} else {
529
+					//ok it checks out
530
+					$corrected_db_update[ $should_be_version_string ] = $should_be_array;
531
+				}
532
+			}
533
+			$espresso_db_update = $corrected_db_update;
534
+			update_option('espresso_db_update', $espresso_db_update);
535
+		}
536
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
537
+		return $espresso_db_update;
538
+	}
539
+
540
+
541
+
542
+	/**
543
+	 * Does the traditional work of setting up the plugin's database and adding default data.
544
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
545
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
546
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
547
+	 * so that it will be done when migrations are finished
548
+	 *
549
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
550
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
551
+	 *                                       This is a resource-intensive job
552
+	 *                                       so we prefer to only do it when necessary
553
+	 * @return void
554
+	 * @throws EE_Error
555
+	 */
556
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
557
+	{
558
+		$request_type = $this->detect_req_type();
559
+		//only initialize system if we're not in maintenance mode.
560
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
561
+			update_option('ee_flush_rewrite_rules', true);
562
+			if ($verify_schema) {
563
+				EEH_Activation::initialize_db_and_folders();
564
+			}
565
+			EEH_Activation::initialize_db_content();
566
+			EEH_Activation::system_initialization();
567
+			if ($initialize_addons_too) {
568
+				$this->initialize_addons();
569
+			}
570
+		} else {
571
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
572
+		}
573
+		if ($request_type === EE_System::req_type_new_activation
574
+			|| $request_type === EE_System::req_type_reactivation
575
+			|| (
576
+				$request_type === EE_System::req_type_upgrade
577
+				&& $this->is_major_version_change()
578
+			)
579
+		) {
580
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
581
+		}
582
+	}
583
+
584
+
585
+
586
+	/**
587
+	 * Initializes the db for all registered addons
588
+	 *
589
+	 * @throws EE_Error
590
+	 */
591
+	public function initialize_addons()
592
+	{
593
+		//foreach registered addon, make sure its db is up-to-date too
594
+		foreach ($this->registry->addons as $addon) {
595
+			if ($addon instanceof EE_Addon) {
596
+				$addon->initialize_db_if_no_migrations_required();
597
+			}
598
+		}
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
605
+	 *
606
+	 * @param    array  $version_history
607
+	 * @param    string $current_version_to_add version to be added to the version history
608
+	 * @return    boolean success as to whether or not this option was changed
609
+	 */
610
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
611
+	{
612
+		if (! $version_history) {
613
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
614
+		}
615
+		if ($current_version_to_add === null) {
616
+			$current_version_to_add = espresso_version();
617
+		}
618
+		$version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
619
+		// re-save
620
+		return update_option('espresso_db_update', $version_history);
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * Detects if the current version indicated in the has existed in the list of
627
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
628
+	 *
629
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
630
+	 *                                  If not supplied, fetches it from the options table.
631
+	 *                                  Also, caches its result so later parts of the code can also know whether
632
+	 *                                  there's been an update or not. This way we can add the current version to
633
+	 *                                  espresso_db_update, but still know if this is a new install or not
634
+	 * @return int one of the constants on EE_System::req_type_
635
+	 */
636
+	public function detect_req_type($espresso_db_update = null)
637
+	{
638
+		if ($this->_req_type === null) {
639
+			$espresso_db_update          = ! empty($espresso_db_update)
640
+				? $espresso_db_update
641
+				: $this->fix_espresso_db_upgrade_option();
642
+			$this->_req_type             = EE_System::detect_req_type_given_activation_history(
643
+				$espresso_db_update,
644
+				'ee_espresso_activation', espresso_version()
645
+			);
646
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
647
+			$this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
648
+		}
649
+		return $this->_req_type;
650
+	}
651
+
652
+
653
+
654
+	/**
655
+	 * Returns whether or not there was a non-micro version change (ie, change in either
656
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
657
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
658
+	 *
659
+	 * @param $activation_history
660
+	 * @return bool
661
+	 */
662
+	private function _detect_major_version_change($activation_history)
663
+	{
664
+		$previous_version       = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
665
+		$previous_version_parts = explode('.', $previous_version);
666
+		$current_version_parts  = explode('.', espresso_version());
667
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
668
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
669
+				   || $previous_version_parts[1] !== $current_version_parts[1]
670
+			   );
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * Returns true if either the major or minor version of EE changed during this request.
677
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
678
+	 *
679
+	 * @return bool
680
+	 */
681
+	public function is_major_version_change()
682
+	{
683
+		return $this->_major_version_change;
684
+	}
685
+
686
+
687
+
688
+	/**
689
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
690
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
691
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
692
+	 * just activated to (for core that will always be espresso_version())
693
+	 *
694
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
695
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
696
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
697
+	 *                                                 indicate that this plugin was just activated
698
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
699
+	 *                                                 espresso_version())
700
+	 * @return int one of the constants on EE_System::req_type_*
701
+	 */
702
+	public static function detect_req_type_given_activation_history(
703
+		$activation_history_for_addon,
704
+		$activation_indicator_option_name,
705
+		$version_to_upgrade_to
706
+	) {
707
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
708
+		if ($activation_history_for_addon) {
709
+			//it exists, so this isn't a completely new install
710
+			//check if this version already in that list of previously installed versions
711
+			if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
712
+				//it a version we haven't seen before
713
+				if ($version_is_higher === 1) {
714
+					$req_type = EE_System::req_type_upgrade;
715
+				} else {
716
+					$req_type = EE_System::req_type_downgrade;
717
+				}
718
+				delete_option($activation_indicator_option_name);
719
+			} else {
720
+				// its not an update. maybe a reactivation?
721
+				if (get_option($activation_indicator_option_name, false)) {
722
+					if ($version_is_higher === -1) {
723
+						$req_type = EE_System::req_type_downgrade;
724
+					} elseif ($version_is_higher === 0) {
725
+						//we've seen this version before, but it's an activation. must be a reactivation
726
+						$req_type = EE_System::req_type_reactivation;
727
+					} else {//$version_is_higher === 1
728
+						$req_type = EE_System::req_type_upgrade;
729
+					}
730
+					delete_option($activation_indicator_option_name);
731
+				} else {
732
+					//we've seen this version before and the activation indicate doesn't show it was just activated
733
+					if ($version_is_higher === -1) {
734
+						$req_type = EE_System::req_type_downgrade;
735
+					} elseif ($version_is_higher === 0) {
736
+						//we've seen this version before and it's not an activation. its normal request
737
+						$req_type = EE_System::req_type_normal;
738
+					} else {//$version_is_higher === 1
739
+						$req_type = EE_System::req_type_upgrade;
740
+					}
741
+				}
742
+			}
743
+		} else {
744
+			//brand new install
745
+			$req_type = EE_System::req_type_new_activation;
746
+			delete_option($activation_indicator_option_name);
747
+		}
748
+		return $req_type;
749
+	}
750
+
751
+
752
+
753
+	/**
754
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
755
+	 * the $activation_history_for_addon
756
+	 *
757
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
758
+	 *                                             sometimes containing 'unknown-date'
759
+	 * @param string $version_to_upgrade_to        (current version)
760
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
761
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
762
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
763
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
764
+	 */
765
+	private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
766
+	{
767
+		//find the most recently-activated version
768
+		$most_recently_active_version =
769
+			EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
770
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
771
+	}
772
+
773
+
774
+
775
+	/**
776
+	 * Gets the most recently active version listed in the activation history,
777
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
778
+	 *
779
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
780
+	 *                                   sometimes containing 'unknown-date'
781
+	 * @return string
782
+	 */
783
+	private static function _get_most_recently_active_version_from_activation_history($activation_history)
784
+	{
785
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
786
+		$most_recently_active_version            = '0.0.0.dev.000';
787
+		if (is_array($activation_history)) {
788
+			foreach ($activation_history as $version => $times_activated) {
789
+				//check there is a record of when this version was activated. Otherwise,
790
+				//mark it as unknown
791
+				if (! $times_activated) {
792
+					$times_activated = array('unknown-date');
793
+				}
794
+				if (is_string($times_activated)) {
795
+					$times_activated = array($times_activated);
796
+				}
797
+				foreach ($times_activated as $an_activation) {
798
+					if ($an_activation !== 'unknown-date'
799
+						&& $an_activation
800
+						   > $most_recently_active_version_activation) {
801
+						$most_recently_active_version            = $version;
802
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
803
+							? '1970-01-01 00:00:00'
804
+							: $an_activation;
805
+					}
806
+				}
807
+			}
808
+		}
809
+		return $most_recently_active_version;
810
+	}
811
+
812
+
813
+
814
+	/**
815
+	 * This redirects to the about EE page after activation
816
+	 *
817
+	 * @return void
818
+	 */
819
+	public function redirect_to_about_ee()
820
+	{
821
+		$notices = EE_Error::get_notices(false);
822
+		//if current user is an admin and it's not an ajax or rest request
823
+		if (
824
+			! isset($notices['errors'])
825
+			&& $this->request->isAdmin()
826
+			&& apply_filters(
827
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
828
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
829
+			)
830
+		) {
831
+			$query_params = array('page' => 'espresso_about');
832
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
833
+				$query_params['new_activation'] = true;
834
+			}
835
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
836
+				$query_params['reactivation'] = true;
837
+			}
838
+			$url = add_query_arg($query_params, admin_url('admin.php'));
839
+			wp_safe_redirect($url);
840
+			exit();
841
+		}
842
+	}
843
+
844
+
845
+
846
+	/**
847
+	 * load_core_configuration
848
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
849
+	 * which runs during the WP 'plugins_loaded' action at priority 5
850
+	 *
851
+	 * @return void
852
+	 * @throws ReflectionException
853
+	 */
854
+	public function load_core_configuration()
855
+	{
856
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
857
+		$this->loader->getShared('EE_Load_Textdomain');
858
+		//load textdomain
859
+		EE_Load_Textdomain::load_textdomain();
860
+		// load and setup EE_Config and EE_Network_Config
861
+		$config = $this->loader->getShared('EE_Config');
862
+		$this->loader->getShared('EE_Network_Config');
863
+		// setup autoloaders
864
+		// enable logging?
865
+		if ($config->admin->use_full_logging) {
866
+			$this->loader->getShared('EE_Log');
867
+		}
868
+		// check for activation errors
869
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
870
+		if ($activation_errors) {
871
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
872
+			update_option('ee_plugin_activation_errors', false);
873
+		}
874
+		// get model names
875
+		$this->_parse_model_names();
876
+		//load caf stuff a chance to play during the activation process too.
877
+		$this->_maybe_brew_regular();
878
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
879
+	}
880
+
881
+
882
+
883
+	/**
884
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
885
+	 *
886
+	 * @return void
887
+	 * @throws ReflectionException
888
+	 */
889
+	private function _parse_model_names()
890
+	{
891
+		//get all the files in the EE_MODELS folder that end in .model.php
892
+		$models                 = glob(EE_MODELS . '*.model.php');
893
+		$model_names            = array();
894
+		$non_abstract_db_models = array();
895
+		foreach ($models as $model) {
896
+			// get model classname
897
+			$classname       = EEH_File::get_classname_from_filepath_with_standard_filename($model);
898
+			$short_name      = str_replace('EEM_', '', $classname);
899
+			$reflectionClass = new ReflectionClass($classname);
900
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
901
+				$non_abstract_db_models[ $short_name ] = $classname;
902
+			}
903
+			$model_names[ $short_name ] = $classname;
904
+		}
905
+		$this->registry->models                 = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
906
+		$this->registry->non_abstract_db_models = apply_filters(
907
+			'FHEE__EE_System__parse_implemented_model_names',
908
+			$non_abstract_db_models
909
+		);
910
+	}
911
+
912
+
913
+
914
+	/**
915
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
916
+	 * that need to be setup before our EE_System launches.
917
+	 *
918
+	 * @return void
919
+	 */
920
+	private function _maybe_brew_regular()
921
+	{
922
+		if ((! defined('EE_DECAF') || EE_DECAF !== true) && is_readable(EE_CAFF_PATH . 'brewing_regular.php')) {
923
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
924
+		}
925
+	}
926
+
927
+
928
+
929
+	/**
930
+	 * register_shortcodes_modules_and_widgets
931
+	 * generate lists of shortcodes and modules, then verify paths and classes
932
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
933
+	 * which runs during the WP 'plugins_loaded' action at priority 7
934
+	 *
935
+	 * @access public
936
+	 * @return void
937
+	 * @throws Exception
938
+	 */
939
+	public function register_shortcodes_modules_and_widgets()
940
+	{
941
+		if ($this->request->isFrontend() || $this->request->isIframe()) {
942
+			try {
943
+				// load, register, and add shortcodes the new way
944
+				$this->loader->getShared(
945
+					'EventEspresso\core\services\shortcodes\ShortcodesManager',
946
+					array(
947
+						// and the old way, but we'll put it under control of the new system
948
+						EE_Config::getLegacyShortcodesManager(),
949
+					)
950
+				);
951
+			} catch (Exception $exception) {
952
+				new ExceptionStackTraceDisplay($exception);
953
+			}
954
+		}
955
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
956
+		// check for addons using old hook point
957
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
958
+			$this->_incompatible_addon_error();
959
+		}
960
+	}
961
+
962
+
963
+
964
+	/**
965
+	 * _incompatible_addon_error
966
+	 *
967
+	 * @access public
968
+	 * @return void
969
+	 */
970
+	private function _incompatible_addon_error()
971
+	{
972
+		// get array of classes hooking into here
973
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
974
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
975
+		);
976
+		if (! empty($class_names)) {
977
+			$msg = __(
978
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
979
+				'event_espresso'
980
+			);
981
+			$msg .= '<ul>';
982
+			foreach ($class_names as $class_name) {
983
+				$msg .= '<li><b>Event Espresso - ' . str_replace(
984
+						array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'), '',
985
+						$class_name
986
+					) . '</b></li>';
987
+			}
988
+			$msg .= '</ul>';
989
+			$msg .= __(
990
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
991
+				'event_espresso'
992
+			);
993
+			// save list of incompatible addons to wp-options for later use
994
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
995
+			if (is_admin()) {
996
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
997
+			}
998
+		}
999
+	}
1000
+
1001
+
1002
+
1003
+	/**
1004
+	 * brew_espresso
1005
+	 * begins the process of setting hooks for initializing EE in the correct order
1006
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1007
+	 * which runs during the WP 'plugins_loaded' action at priority 9
1008
+	 *
1009
+	 * @return void
1010
+	 */
1011
+	public function brew_espresso()
1012
+	{
1013
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
1014
+		// load some final core systems
1015
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
1016
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1017
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
1018
+		add_action('init', array($this, 'load_controllers'), 7);
1019
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
1020
+		add_action('init', array($this, 'initialize'), 10);
1021
+		add_action('init', array($this, 'initialize_last'), 100);
1022
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1023
+			// pew pew pew
1024
+			$this->loader->getShared('EE_PUE');
1025
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1026
+		}
1027
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
1028
+	}
1029
+
1030
+
1031
+
1032
+	/**
1033
+	 *    set_hooks_for_core
1034
+	 *
1035
+	 * @access public
1036
+	 * @return    void
1037
+	 * @throws EE_Error
1038
+	 */
1039
+	public function set_hooks_for_core()
1040
+	{
1041
+		$this->_deactivate_incompatible_addons();
1042
+		do_action('AHEE__EE_System__set_hooks_for_core');
1043
+		//caps need to be initialized on every request so that capability maps are set.
1044
+		//@see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1045
+		$this->registry->CAP->init_caps();
1046
+	}
1047
+
1048
+
1049
+
1050
+	/**
1051
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
1052
+	 * deactivates any addons considered incompatible with the current version of EE
1053
+	 */
1054
+	private function _deactivate_incompatible_addons()
1055
+	{
1056
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
1057
+		if (! empty($incompatible_addons)) {
1058
+			$active_plugins = get_option('active_plugins', array());
1059
+			foreach ($active_plugins as $active_plugin) {
1060
+				foreach ($incompatible_addons as $incompatible_addon) {
1061
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1062
+						unset($_GET['activate']);
1063
+						espresso_deactivate_plugin($active_plugin);
1064
+					}
1065
+				}
1066
+			}
1067
+		}
1068
+	}
1069
+
1070
+
1071
+
1072
+	/**
1073
+	 *    perform_activations_upgrades_and_migrations
1074
+	 *
1075
+	 * @access public
1076
+	 * @return    void
1077
+	 */
1078
+	public function perform_activations_upgrades_and_migrations()
1079
+	{
1080
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1081
+	}
1082
+
1083
+
1084
+
1085
+	/**
1086
+	 *    load_CPTs_and_session
1087
+	 *
1088
+	 * @access public
1089
+	 * @return    void
1090
+	 */
1091
+	public function load_CPTs_and_session()
1092
+	{
1093
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1094
+		// register Custom Post Types
1095
+		$this->loader->getShared('EE_Register_CPTs');
1096
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1097
+	}
1098
+
1099
+
1100
+
1101
+	/**
1102
+	 * load_controllers
1103
+	 * this is the best place to load any additional controllers that needs access to EE core.
1104
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1105
+	 * time
1106
+	 *
1107
+	 * @access public
1108
+	 * @return void
1109
+	 */
1110
+	public function load_controllers()
1111
+	{
1112
+		do_action('AHEE__EE_System__load_controllers__start');
1113
+		// let's get it started
1114
+		if (
1115
+			! $this->maintenance_mode->level()
1116
+			&& ($this->request->isFrontend() || $this->request->isFrontAjax())
1117
+		) {
1118
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1119
+			$this->loader->getShared('EE_Front_Controller');
1120
+		} elseif ($this->request->isAdmin() || $this->request->isAdminAjax()) {
1121
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1122
+			$this->loader->getShared('EE_Admin');
1123
+		}
1124
+		do_action('AHEE__EE_System__load_controllers__complete');
1125
+	}
1126
+
1127
+
1128
+
1129
+	/**
1130
+	 * core_loaded_and_ready
1131
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1132
+	 *
1133
+	 * @access public
1134
+	 * @return void
1135
+	 */
1136
+	public function core_loaded_and_ready()
1137
+	{
1138
+		if (
1139
+			$this->request->isAdmin()
1140
+			|| $this->request->isEeAjax()
1141
+			|| $this->request->isFrontend()
1142
+		) {
1143
+			$this->loader->getShared('EE_Session');
1144
+		}
1145
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1146
+		// load_espresso_template_tags
1147
+		if (
1148
+			is_readable(EE_PUBLIC . 'template_tags.php')
1149
+			&& ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isFeed())
1150
+		) {
1151
+			require_once EE_PUBLIC . 'template_tags.php';
1152
+		}
1153
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1154
+		if ($this->request->isAdmin() || $this->request->isFrontend() || $this->request->isIframe()) {
1155
+			$this->loader->getShared('EventEspresso\core\services\assets\Registry');
1156
+		}
1157
+	}
1158
+
1159
+
1160
+
1161
+	/**
1162
+	 * initialize
1163
+	 * this is the best place to begin initializing client code
1164
+	 *
1165
+	 * @access public
1166
+	 * @return void
1167
+	 */
1168
+	public function initialize()
1169
+	{
1170
+		do_action('AHEE__EE_System__initialize');
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * initialize_last
1177
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1178
+	 * initialize has done so
1179
+	 *
1180
+	 * @access public
1181
+	 * @return void
1182
+	 */
1183
+	public function initialize_last()
1184
+	{
1185
+		do_action('AHEE__EE_System__initialize_last');
1186
+		add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1187
+	}
1188
+
1189
+
1190
+
1191
+	/**
1192
+	 * @return void
1193
+	 * @throws EE_Error
1194
+	 */
1195
+	public function addEspressoToolbar()
1196
+	{
1197
+		$this->loader->getShared(
1198
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1199
+			array($this->registry->CAP)
1200
+		);
1201
+	}
1202
+
1203
+
1204
+
1205
+	/**
1206
+	 * do_not_cache
1207
+	 * sets no cache headers and defines no cache constants for WP plugins
1208
+	 *
1209
+	 * @access public
1210
+	 * @return void
1211
+	 */
1212
+	public static function do_not_cache()
1213
+	{
1214
+		// set no cache constants
1215
+		if (! defined('DONOTCACHEPAGE')) {
1216
+			define('DONOTCACHEPAGE', true);
1217
+		}
1218
+		if (! defined('DONOTCACHCEOBJECT')) {
1219
+			define('DONOTCACHCEOBJECT', true);
1220
+		}
1221
+		if (! defined('DONOTCACHEDB')) {
1222
+			define('DONOTCACHEDB', true);
1223
+		}
1224
+		// add no cache headers
1225
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1226
+		// plus a little extra for nginx and Google Chrome
1227
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1228
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1229
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1230
+	}
1231
+
1232
+
1233
+
1234
+	/**
1235
+	 *    extra_nocache_headers
1236
+	 *
1237
+	 * @access    public
1238
+	 * @param $headers
1239
+	 * @return    array
1240
+	 */
1241
+	public static function extra_nocache_headers($headers)
1242
+	{
1243
+		// for NGINX
1244
+		$headers['X-Accel-Expires'] = 0;
1245
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1246
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1247
+		return $headers;
1248
+	}
1249
+
1250
+
1251
+
1252
+	/**
1253
+	 *    nocache_headers
1254
+	 *
1255
+	 * @access    public
1256
+	 * @return    void
1257
+	 */
1258
+	public static function nocache_headers()
1259
+	{
1260
+		nocache_headers();
1261
+	}
1262
+
1263
+
1264
+
1265
+	/**
1266
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1267
+	 * never returned with the function.
1268
+	 *
1269
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1270
+	 * @return array
1271
+	 */
1272
+	public function remove_pages_from_wp_list_pages($exclude_array)
1273
+	{
1274
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1275
+	}
1276 1276
 
1277 1277
 
1278 1278
 
Please login to merge, or discard this patch.