-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathindex.ts
402 lines (377 loc) · 13.5 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import { PHP, UniversalPHP } from '@php-wasm/universal';
import { joinPaths, phpVar } from '@php-wasm/util';
import { unzipFile } from '@wp-playground/common';
export { bootWordPress, getFileNotFoundActionForWordPress } from './boot';
export { getLoadedWordPressVersion } from './version-detect';
export * from './version-detect';
export * from './rewrite-rules';
/**
* Preloads the platform mu-plugins from /internal/shared/mu-plugins.
* This avoids polluting the WordPress installation with mu-plugins
* that are only needed in the Playground environment.
*
* @param php
*/
export async function setupPlatformLevelMuPlugins(php: UniversalPHP) {
await php.mkdir('/internal/shared/mu-plugins');
await php.writeFile(
'/internal/shared/preload/env.php',
`<?php
// Allow adding filters/actions prior to loading WordPress.
// $function_to_add MUST be a string.
function playground_add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
global $wp_filter;
$wp_filter[$tag][$priority][$function_to_add] = array('function' => $function_to_add, 'accepted_args' => $accepted_args);
}
function playground_add_action( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
playground_add_filter( $tag, $function_to_add, $priority, $accepted_args );
}
// Load our mu-plugins after customer mu-plugins
// NOTE: this means our mu-plugins can't use the muplugins_loaded action!
playground_add_action( 'muplugins_loaded', 'playground_load_mu_plugins', 0 );
function playground_load_mu_plugins() {
// Load all PHP files from /internal/shared/mu-plugins, sorted by filename
$mu_plugins_dir = '/internal/shared/mu-plugins';
if(!is_dir($mu_plugins_dir)){
return;
}
$mu_plugins = glob( $mu_plugins_dir . '/*.php' );
sort( $mu_plugins );
foreach ( $mu_plugins as $mu_plugin ) {
require_once $mu_plugin;
}
}
`
);
await php.writeFile(
'/internal/shared/mu-plugins/0-playground.php',
`<?php
// Needed because gethostbyname( 'wordpress.org' ) returns
// a private network IP address for some reason.
add_filter( 'allowed_redirect_hosts', function( $deprecated = '' ) {
return array(
'wordpress.org',
'api.wordpress.org',
'downloads.wordpress.org',
);
} );
// Support pretty permalinks
add_filter( 'got_url_rewrite', '__return_true' );
// Create the fonts directory if missing
if(!file_exists(WP_CONTENT_DIR . '/fonts')) {
mkdir(WP_CONTENT_DIR . '/fonts');
}
$log_file = WP_CONTENT_DIR . '/debug.log';
define('ERROR_LOG_FILE', $log_file);
ini_set('error_log', $log_file);
?>`
);
// Load the error handler before any other PHP file to ensure it
// treats all the errors, even those trigerred before mu-plugins
// are loaded.
await php.writeFile(
'/internal/shared/preload/error-handler.php',
`<?php
(function() {
$playground_consts = [];
if(file_exists('/internal/shared/consts.json')) {
$playground_consts = @json_decode(file_get_contents('/internal/shared/consts.json'), true) ?: [];
$playground_consts = array_keys($playground_consts);
}
set_error_handler(function($severity, $message, $file, $line) use($playground_consts) {
/**
* We're forced to use this deprecated hook to ensure SSL operations work without
* the kitchen-sink bundled. See https://github.com/WordPress/wordpress-playground/pull/1504
* for more context.
*/
if (
strpos($message, "Hook http_api_transports is deprecated") !== false ||
strpos($message, "Hook http_api_transports is <strong>deprecated</strong>") !== false
) {
return;
}
/**
* This is a temporary workaround to hide the 32bit integer warnings that
* appear when using various time related function, such as strtotime and mktime.
* Examples of the warnings that are displayed:
*
* Warning: mktime(): Epoch doesn't fit in a PHP integer in <file>
* Warning: strtotime(): Epoch doesn't fit in a PHP integer in <file>
*/
if (strpos($message, "fit in a PHP integer") !== false) {
return;
}
/**
* Playground defines some constants upfront, and some of them may be redefined
* in wp-config.php. For example, SITE_URL or WP_DEBUG. This is expected and
* we want Playground constants to take priority without showing warnings like:
*
* Warning: Constant SITE_URL already defined in
*/
if (strpos($message, "already defined") !== false) {
foreach($playground_consts as $const) {
if(strpos($message, "Constant $const already defined") !== false) {
return;
}
}
}
/**
* Don't complain about network errors when not connected to the network.
*/
if (
(
! defined('USE_FETCH_FOR_REQUESTS') ||
! USE_FETCH_FOR_REQUESTS
) &&
strpos($message, "WordPress could not establish a secure connection to WordPress.org") !== false)
{
return;
}
return false;
});
})();`
);
}
/**
* Runs phpinfo() when the requested path is /phpinfo.php.
*/
export async function preloadPhpInfoRoute(
php: UniversalPHP,
requestPath = '/phpinfo.php'
) {
await php.writeFile(
'/internal/shared/preload/phpinfo.php',
`<?php
// Render PHPInfo if the requested page is /phpinfo.php
if ( ${phpVar(requestPath)} === $_SERVER['REQUEST_URI'] ) {
phpinfo();
exit;
}
`
);
}
export async function preloadSqliteIntegration(
php: UniversalPHP,
sqliteZip: File
) {
if (await php.isDir('/tmp/sqlite-database-integration')) {
await php.rmdir('/tmp/sqlite-database-integration', {
recursive: true,
});
}
await php.mkdir('/tmp/sqlite-database-integration');
await unzipFile(php, sqliteZip, '/tmp/sqlite-database-integration');
const SQLITE_PLUGIN_FOLDER = '/internal/shared/sqlite-database-integration';
const temporarySqlitePluginFolder = (await php.isDir(
'/tmp/sqlite-database-integration/sqlite-database-integration-main'
))
? // This is the name when the dev branch used to be called "main"
'/tmp/sqlite-database-integration/sqlite-database-integration-main'
: // This is the name today when the dev branch is called "develop"
'/tmp/sqlite-database-integration/sqlite-database-integration-develop';
await php.mv(temporarySqlitePluginFolder, SQLITE_PLUGIN_FOLDER);
// Prevents the SQLite integration from trying to call activate_plugin()
await php.defineConstant('SQLITE_MAIN_FILE', '1');
const dbCopy = await php.readFileAsText(
joinPaths(SQLITE_PLUGIN_FOLDER, 'db.copy')
);
const dbPhp = dbCopy
.replace(
"'{SQLITE_IMPLEMENTATION_FOLDER_PATH}'",
phpVar(SQLITE_PLUGIN_FOLDER)
)
.replace(
"'{SQLITE_PLUGIN}'",
phpVar(joinPaths(SQLITE_PLUGIN_FOLDER, 'load.php'))
);
const dbPhpPath = joinPaths(await php.documentRoot, 'wp-content/db.php');
const stopIfDbPhpExists = `<?php
// Do not preload this if WordPress comes with a custom db.php file.
if(file_exists(${phpVar(dbPhpPath)})) {
return;
}
?>`;
const SQLITE_MUPLUGIN_PATH =
'/internal/shared/mu-plugins/sqlite-database-integration.php';
await php.writeFile(SQLITE_MUPLUGIN_PATH, stopIfDbPhpExists + dbPhp);
await php.writeFile(
`/internal/shared/preload/0-sqlite.php`,
stopIfDbPhpExists +
`<?php
/**
* Loads the SQLite integration plugin before WordPress is loaded
* and without creating a drop-in "db.php" file.
*
* Technically, it creates a global $wpdb object whose only two
* purposes are to:
*
* * Exist – because the require_wp_db() WordPress function won't
* connect to MySQL if $wpdb is already set.
* * Load the SQLite integration plugin the first time it's used
* and replace the global $wpdb reference with the SQLite one.
*
* This lets Playground keep the WordPress installation clean and
* solves dillemas like:
*
* * Should we include db.php in Playground exports?
* * Should we remove db.php from Playground imports?
* * How should we treat stale db.php from long-lived OPFS sites?
*
* @see https://github.com/WordPress/wordpress-playground/discussions/1379 for
* more context.
*/
class Playground_SQLite_Integration_Loader {
public function __call($name, $arguments) {
$this->load_sqlite_integration();
if($GLOBALS['wpdb'] === $this) {
throw new Exception('Infinite loop detected in $wpdb – SQLite integration plugin could not be loaded');
}
return call_user_func_array(
array($GLOBALS['wpdb'], $name),
$arguments
);
}
public function __get($name) {
$this->load_sqlite_integration();
if($GLOBALS['wpdb'] === $this) {
throw new Exception('Infinite loop detected in $wpdb – SQLite integration plugin could not be loaded');
}
return $GLOBALS['wpdb']->$name;
}
public function __set($name, $value) {
$this->load_sqlite_integration();
if($GLOBALS['wpdb'] === $this) {
throw new Exception('Infinite loop detected in $wpdb – SQLite integration plugin could not be loaded');
}
$GLOBALS['wpdb']->$name = $value;
}
protected function load_sqlite_integration() {
require_once ${phpVar(SQLITE_MUPLUGIN_PATH)};
}
}
$wpdb = $GLOBALS['wpdb'] = new Playground_SQLite_Integration_Loader();
/**
* WordPress is capable of using a preloaded global $wpdb. However, if
* it cannot find the drop-in db.php plugin it still checks whether
* the mysqli_connect() function exists even though it's not used.
*
* What WordPress demands, Playground shall provide.
*/
if(!function_exists('mysqli_connect')) {
function mysqli_connect() {}
}
`
);
/**
* Ensure the SQLite integration is loaded and clearly communicate
* if it isn't. This is useful because WordPress database errors
* may be cryptic and won't mention the SQLite integration.
*/
await php.writeFile(
`/internal/shared/mu-plugins/sqlite-test.php`,
`<?php
global $wpdb;
if(!($wpdb instanceof WP_SQLite_DB)) {
var_dump(isset($wpdb));
die("SQLite integration not loaded " . get_class($wpdb));
}
`
);
}
/**
* Prepare the WordPress document root given a WordPress zip file and
* the sqlite-database-integration zip file.
*
* This is a TypeScript function for now, just to get something off the
* ground, but it may be superseded by the PHP Blueprints library developed
* at https://github.com/WordPress/blueprints-library/
*
* That PHP library will come with a set of functions and a CLI tool to
* turn a Blueprint into a WordPress directory structure or a zip Snapshot.
* Let's **not** invest in the TypeScript implementation of this function,
* accept the limitation, and switch to the PHP implementation as soon
* as that's viable.
*/
export async function unzipWordPress(php: PHP, wpZip: File) {
php.mkdir('/tmp/unzipped-wordpress');
await unzipFile(php, wpZip, '/tmp/unzipped-wordpress');
// The zip file may contain another zip file if it's coming from GitHub
// artifacts @TODO: Don't make so many guesses about the zip file contents.
// Allow the API consumer to specify the exact "coordinates" of WordPress
// inside the zip archive.
if (php.fileExists('/tmp/unzipped-wordpress/wordpress.zip')) {
await unzipFile(
php,
'/tmp/unzipped-wordpress/wordpress.zip',
'/tmp/unzipped-wordpress'
);
}
// The zip file may contain a subdirectory, or not.
// @TODO: Don't make so many guesses about the zip file contents. Allow the
// API consumer to specify the exact "coordinates" of WordPress inside
// the zip archive.
let wpPath = php.fileExists('/tmp/unzipped-wordpress/wordpress')
? '/tmp/unzipped-wordpress/wordpress'
: php.fileExists('/tmp/unzipped-wordpress/build')
? '/tmp/unzipped-wordpress/build'
: '/tmp/unzipped-wordpress';
// Dive one directory deeper if the zip root does not contain the sample
// config file. This is relevant when unzipping a zipped branch from the
// https://github.com/WordPress/WordPress repository.
if (!php.fileExists(joinPaths(wpPath, 'wp-config-sample.php'))) {
// Still don't know the directory structure of the zip file.
// 1. Get the first item in path.
const files = php.listFiles(wpPath);
if (files.length) {
const firstDir = files[0];
// 2. If it's a directory that contains wp-config-sample.php, use it.
if (
php.fileExists(
joinPaths(wpPath, firstDir, 'wp-config-sample.php')
)
) {
wpPath = joinPaths(wpPath, firstDir);
}
}
}
if (
php.isDir(php.documentRoot) &&
isCleanDirContainingSiteMetadata(php.documentRoot, php)
) {
// We cannot mv the directory over a non-empty directory,
// but we can move the children one by one.
for (const file of php.listFiles(wpPath)) {
const sourcePath = joinPaths(wpPath, file);
const targetPath = joinPaths(php.documentRoot, file);
php.mv(sourcePath, targetPath);
}
php.rmdir(wpPath, { recursive: true });
} else {
php.mv(wpPath, php.documentRoot);
}
if (
!php.fileExists(joinPaths(php.documentRoot, 'wp-config.php')) &&
php.fileExists(joinPaths(php.documentRoot, 'wp-config-sample.php'))
) {
php.writeFile(
joinPaths(php.documentRoot, 'wp-config.php'),
php.readFileAsText(
joinPaths(php.documentRoot, '/wp-config-sample.php')
)
);
}
}
function isCleanDirContainingSiteMetadata(path: string, php: PHP) {
const files = php.listFiles(path);
if (files.length === 0) {
return true;
}
if (
files.length === 1 &&
// TODO: use a constant from a site storage package
files[0] === 'playground-site-metadata.json'
) {
return true;
}
return false;
}