-
Notifications
You must be signed in to change notification settings - Fork 274
/
Copy pathindex.ts
542 lines (513 loc) · 17.9 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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
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;
}
}
`
);
/**
* Automatically logs the user in to aid the login Blueprint step and
* the Playground runtimes.
*
* There are two ways to trigger the auto-login:
*
* ## The PLAYGROUND_AUTO_LOGIN_AS_USER constant
*
* Used by the login Blueprint step does.
*
* When the PLAYGROUND_AUTO_LOGIN_AS_USER constant is defined, this mu-plugin
* will automatically log the user in on their first visit. The username is
* the value of the constant.
*
* On subsequent visits, the playground_auto_login_already_happened cookie will be
* detected and the user will not be logged in. This means the "logout" feature
* will work as expected.
*
* ## The playground_force_auto_login_as_user GET parameter
*
* Used by the "login" button in various Playground runtimes.
*
* Only works if the PLAYGROUND_FORCE_AUTO_LOGIN_ENABLED constant is defined.
*
* When the playground_force_auto_login_as_user GET parameter is present,
* this mu-plugin will automatically log in any logged out visitor. This will
* happen every time they visit, not just on their first visit.
*
*
* ## Context
*
* The login step used to make a HTTP request to the /wp-login.php endpoint,
* but that approach had significant downsides:
*
* * It only worked in web browsers
* * It didn't support custom login mechanisms
* * It required storing plaintext passwords in the Blueprint files
*/
await php.writeFile(
'/internal/shared/mu-plugins/1-auto-login.php',
`<?php
/**
* Returns the username to auto-login as, if any.
* @return string|false
*/
function playground_get_username_for_auto_login() {
/**
* Allow users to auto-login as a specific user on their first visit.
*
* Prevent the auto-login if it already happened by checking for the
* playground_auto_login_already_happened cookie.
* This is used to allow the user to logout.
*/
if ( defined('PLAYGROUND_AUTO_LOGIN_AS_USER') && !isset($_COOKIE['playground_auto_login_already_happened']) ) {
return PLAYGROUND_AUTO_LOGIN_AS_USER;
}
/**
* Allow users to auto-login as a specific user by passing the
* playground_force_auto_login_as_user GET parameter.
*/
if ( defined('PLAYGROUND_FORCE_AUTO_LOGIN_ENABLED') && isset($_GET['playground_force_auto_login_as_user']) ) {
return $_GET['playground_force_auto_login_as_user'];
}
return false;
}
/**
* Logs the user in on their first visit if the Playground runtime told us to.
*/
function playground_auto_login() {
/**
* The redirect should only run if the current PHP request is
* a HTTP request. If it's a PHP CLI run, we can't login the user
* because logins require cookies which aren't available in the CLI.
*
* Currently all Playground requests use the "cli" SAPI name
* to ensure support for WP-CLI, so the best way to distinguish
* between a CLI run and an HTTP request is by checking if the
* $_SERVER['REQUEST_URI'] global is set.
*
* If $_SERVER['REQUEST_URI'] is not set, we assume it's a CLI run.
*/
if (empty($_SERVER['REQUEST_URI'])) {
return;
}
$user_name = playground_get_username_for_auto_login();
if ( false === $user_name ) {
return;
}
if (wp_doing_ajax() || defined('REST_REQUEST')) {
return;
}
if ( is_user_logged_in() ) {
return;
}
$user = get_user_by('login', $user_name);
if (!$user) {
return;
}
/**
* This approach is described in a comment on
* https://developer.wordpress.org/reference/functions/wp_set_current_user/
*/
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID );
do_action( 'wp_login', $user->user_login, $user );
setcookie('playground_auto_login_already_happened', '1');
/**
* Reload page to ensure the user is logged in correctly.
* WordPress uses cookies to determine if the user is logged in,
* so we need to reload the page to ensure the cookies are set.
*/
wp_redirect(
$_SERVER['REQUEST_URI'],
302
);
exit;
}
/**
* Autologin users from the wp-login.php page.
*
* The wp hook isn't triggered on
**/
add_action('init', 'playground_auto_login', 1);
/**
* Disable the Site Admin Email Verification Screen for any session started
* via autologin.
*/
add_filter('admin_email_check_interval', function($interval) {
if(false === playground_get_username_for_auto_login()) {
return 0;
}
return $interval;
});
`
);
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) {
/**
* 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;
}
/**
* Networking support in Playground registers a http_api_transports filter.
*
* This filter is deprecated, and no longer actively used, but is needed for wp_http_supports().
* @see https://core.trac.wordpress.org/ticket/37708
*/
if (
strpos($message, "http_api_transports") !== false &&
strpos($message, "since version 6.4.0 with no alternative available") !== 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;
}