Repository navigation
Expand file tree
/
Copy pathController.php
More file actions
920 lines (851 loc) · 31.8 KB
/
Copy pathController.php
File metadata and controls
920 lines (851 loc) · 31.8 KB
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
<?php
/**
* The admin-specific functionality of the plugin.
*
* Defines the plugin name, version, and two examples hooks for how to
* enqueue the admin-specific stylesheet and JavaScript.
*
* @package Reactpress
* @subpackage Reactpress/admin
* @author Marco Laspe <marco@rockiger.com>
*/
namespace ReactPress\Admin;
if (!defined('ABSPATH')) {
exit;
}
use LengthException;
use ReactPress\Admin\Utils;
use function \repr_log;
class Controller {
// # Controller functions
public static function add_page(string $appname, int $pageId, string $page_title) {
$app_options = Utils::get_app_options($appname);
$apptype = Utils::get_app_type($appname);
//# Check if the app allows adding of more URL slugs
if ($app_options && $app_options['allowsRouting'] && count($app_options['pageIds'])) {
echo wp_json_encode([
'status' => 0,
'message' => 'Apps with client-side routing can only be shown on one single page.'
]);
return;
}
// add slug to existing app_options
$inserted_page = Controller::insert_page($pageId, $page_title);
if (!$inserted_page['ID']) {
echo wp_json_encode([
'status' => 0,
'message' => $inserted_page['message']
]);
return;
}
$permalink = get_permalink($inserted_page['ID']);
$permalink = $permalink ? $permalink : '';
$app_options ? Utils::add_pageId_to_app_options($appname, $inserted_page['ID']) : Utils::add_app_options($appname, $inserted_page['ID']);
Controller::add_build_path($appname, $apptype);
if ($app_options['allowsRouting']) {
add_rewrite_rule('^' . wp_make_link_relative($permalink) . '/(.*)?', 'index.php?pagename=' . wp_make_link_relative($permalink), 'top');
Utils::set_public_url_for_dev_server($appname, $permalink);
}
flush_rewrite_rules();
$html_content = Controller::get_index_html_content($permalink, $apptype, $appname);
if (empty($html_content)) {
echo wp_json_encode([
'status' => 0,
'message' => 'Couldn\'t download page content.'
]);
} elseif (Controller::write_index_html($appname, $html_content, $apptype)) {
echo wp_json_encode([
'status' => 1,
'message' => 'Page added.',
'pageId' => $inserted_page['ID'],
'page_title' => $inserted_page['page_title'],
'permalink' => $permalink
]);
} else {
echo wp_json_encode([
'status' => 0,
'message' => 'Something went wrong.',
]);
}
}
public static function delete_page(string $appname, int $pageId, string $permalink) {
try {
// Ignore the request permalink and use the page's own URL. The posted
// value is written into package.json and must not be attacker-controlled.
$stored_permalink = get_permalink($pageId);
$permalink = is_string($stored_permalink) ? $stored_permalink : '';
$app_options_list = Utils::get_apps();
Utils::delete_page($app_options_list, $appname, $pageId);
Utils::unset_public_url_for_dev_server($appname, $permalink);
echo wp_json_encode(['status' => 1]);
} catch (\Exception $e) {
repr_log($e);
echo wp_json_encode(['status' => 0, 'message' => $e->getMessage()]);
}
}
public static function delete_react_app(string $appname) {
$options = get_option('repr_apps');
$options = is_array($options) ? $options : [];
Utils::write_apps_option(array_values(array_filter(
$options,
fn ($el) => $el['appname'] !== $appname
)));
$app_directory = self::resolve_app_directory($appname);
$is_appdir_removed = $app_directory !== '' && repr_delete_directory($app_directory);
if ($is_appdir_removed) {
echo wp_json_encode([
'status' => 1,
'message' => 'App deleted.',
]);
} else {
echo wp_json_encode([
'status' => 1,
'message' => "Couldn't remove files. Please remove directory by hand.",
]);
}
}
public static function get_react_apps() {
$apps = Utils::get_apps();
echo wp_json_encode(['status' => 1, 'apps' => $apps]);
}
public static function update_index_html(string $appname, string $permalink) {
$apptype = Utils::get_app_type($appname);
$html_content = Controller::get_index_html_content($permalink, $apptype, $appname);
if (empty($html_content)) {
echo wp_json_encode([
'status' => 0,
'message' => 'Couldn\'t download page content.'
]);
} elseif (Controller::write_index_html($appname, $html_content, $apptype)) {
echo wp_json_encode([
'status' => 1,
'message' => 'Index.html updated.',
]);
} else {
echo wp_json_encode([
'status' => 0,
'message' => 'Index.html could not be updated.',
]);
}
}
// # Helper functions
/**
* Add the right build path to package.json
*
* @param string $appname
* @return int 0 if no success
* @since 1.2.0
*/
public static function add_build_path(string $appname, string $apptype = 'development_cra'): int {
$apppath = self::resolve_app_directory($appname);
if ($apppath === '') {
return 0;
}
// We need the relative path, that we can deploy our
// built app to another server later.
$relative_apppath = Utils::app_path($appname, true);
$relative_apppath = $relative_apppath ? $relative_apppath : "/wp-content/reactpress/apps/{$appname}/";
if ($apptype === 'development_vite') {
$homepage = "{$relative_apppath}/dist/";
$path_vite_config = is_file("{$apppath}/vite.config.js") ? "{$apppath}/vite.config.js" : "{$apppath}/vite.config.ts";
if (!is_file($path_vite_config)) {
return 0;
}
$vite_config_contents = file_get_contents($path_vite_config);
if (!$vite_config_contents) {
return 0;
} elseif (stripos($vite_config_contents, $homepage)) {
return 1;
} else {
// add the base pathe to vite.config.*
file_put_contents(
$path_vite_config,
str_replace(
"export default defineConfig({\n plugins: [react()],\n})",
"export default defineConfig(({ command }) => {\n if (command === 'build') {\n return {\n base: \"{$homepage}\",\n plugins: [react()],\n }\n } else {\n return {\n plugins: [react()],\n }\n }\n})",
$vite_config_contents
)
);
return 2;
}
} elseif ($apptype === 'development_cra') {
$homepage = "{$relative_apppath}/build";
$path_package_json = "{$apppath}/package.json";
if (!is_file($path_package_json)) {
return 0;
}
$package_json_contents = file_get_contents($path_package_json);
if (!$package_json_contents) {
return 0;
} elseif (stripos($package_json_contents, $homepage)) {
return 1;
} else {
// add the base path that images are correctly loaded
file_put_contents(
$path_package_json,
str_replace("react-scripts build", REPR_IS_WINDOWS ? "set PUBLIC_URL={$homepage}&&react-scripts build" : "PUBLIC_URL={$homepage} react-scripts build", $package_json_contents)
);
return 2;
}
}
return 0;
}
/**
* Downloads the content of the page with the given permalink and removes the
* the react assets of the build page, that we can use the content for our
* development server.
*
* @param $permalink
* @return string
* @since 1.0.0
*/
public static function get_index_html_content(string $permalink, string $apptype = 'development_cra', string $appname = ''): string {
// Never request the raw permalink. Only the canonical URL of a page
// already assigned to this app, on this site, may be downloaded.
$permalink = self::canonical_app_permalink($appname, $permalink);
if ($permalink === '') {
return '';
}
$response = self::fetch_local_permalink($permalink);
if (is_wp_error($response)) {
return '';
}
if ((int) wp_remote_retrieve_response_code($response) !== 200) {
return '';
}
$content_type = self::header_value(wp_remote_retrieve_header($response, 'content-type'));
if (
$content_type !== ''
&& stripos($content_type, 'text/html') === false
&& stripos($content_type, 'application/xhtml+xml') === false
) {
return '';
}
$body = wp_remote_retrieve_body($response);
if ($body === '' || strlen($body) > 2 * 1024 * 1024) {
return '';
}
$filtered_contents = self::sanitize_index_html($body);
if ($filtered_contents === '') {
return '';
}
// All inline scripts (including the reactPress bootstrap) are removed by
// sanitize_index_html(). The former str_replace('var reactPress', '<script>...')
// is gone on purpose: it turned plain page text into an opening <script> tag.
$contents = $filtered_contents;
if ($apptype === 'development_vite') {
$apppath = self::resolve_app_directory($appname);
if ($apppath === '') {
return '';
}
$file_ending = is_file("{$apppath}/src/main.jsx") ? 'jsx' : 'tsx';
// add script tag after root div that link to src/main.tsx
$contents = str_replace(
'<div id="root"></div>',
// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript -- Written into the Vite dev index.html file, not output to WordPress.
"<div id=\"root\"></div><script type=\"module\" src=\"/src/main.{$file_ending}\"></script>",
$contents
);
}
return $contents;
}
/**
* Creates or updates a page with the given name and title.
*
* @param int $pageId
* @param string $page_title
* @since 1.0.0
*/
public static function insert_page(int $pageId, string $page_title) {
if ($pageId === -1) {
$result = wp_insert_post(
array(
'post_title' => $page_title,
'post_status' => 'publish',
'post_content' => REPR_REACT_ROOT_TAG,
'post_type' => "page",
// Assign page template using the relative path, it will be
// resolved to the fully qualified name at run-time
'page_template' => 'templates/react-page-template.php',
)
);
return $result
? ['status' => 'true', 'message' => 'Page created.', 'ID' => $result, 'page_title' => $page_title]
: ['status' => 'false', 'message' => "Couldn't create page.", "ID" => $result, 'page_title' => $page_title];
} else {
$page = get_post($pageId);
if ($page) {
// already we have data with this post name
if (strpos($page->post_content, '<div id="root"></div>') !== false) {
return ['status' => 'true', 'message' => 'Page with app already exists.', 'ID' => $page->ID, 'page_title' => $page_title];
}
$result = wp_update_post(
[
'ID' => $page->ID,
'post_content' => $page->post_content . "\n\n" . REPR_REACT_ROOT_TAG
]
);
return $result
? ['status' => 'true', 'message' => 'Add app to page.', 'ID' => $result, 'page_title' => $page->post_title]
: ['status' => 'false', 'message' => 'Couldn\'t add app to page.', 'ID' => 0, 'page_title' => ''];
}
}
}
public static function toggle_react_routing(string $appname) {
try {
$app_options = Utils::get_apps();
$new_options = array_map(function ($el) use ($appname) {
if ($el['appname'] === $appname) {
//# create new allowsRouting state
$allowsRouting = $el['allowsRouting'] ?? false;
$el['allowsRouting'] = !$allowsRouting;
//# change rewrite rules in wordpress
if ($el['allowsRouting']) {
// routing is only allowed for one single page
if (count($el['pages']) > 1) {
throw new LengthException('Client-side routing is only possible on one single page.');
}
foreach ($el['pages'] as $page) {
add_rewrite_rule(
'^' .
// Trim leading and trailing slashes to get `^foo/bar/(.*)?` not `^/foo/bar//(.*)?`
trim(wp_make_link_relative($page['permalink']), '/') .
'/(.*)?',
'index.php?pagename=' .
// Trim leading and trailing slashes to get `index.php?pagename=foo/bar` not `index.php?pagename=/foo/bar/`
trim(wp_make_link_relative($page['permalink']), '/'),
'top'
);
Utils::set_public_url_for_dev_server($appname, $page['permalink']);
}
flush_rewrite_rules();
} else {
foreach ($el['pages'] as $page) {
Utils::remove_rewrite_rule('^' . wp_make_link_relative($page['permalink']) . '/(.*)?');
Utils::unset_public_url_for_dev_server($appname, $page['permalink']);
}
flush_rewrite_rules();
}
return $el;
}
return $el;
}, $app_options);
Utils::write_apps_option($new_options);
echo wp_json_encode(['status' => 1]);
} catch (\Exception $e) {
repr_log($e);
echo wp_json_encode(['status' => 0, 'message' => $e->getMessage()]);
}
}
/**
* Writes the given to the index.html file in the app directory of
* the given appname and produces if the writing of the file succeded or not.
*
* @param string $appname
* @param string $content
* @since 1.0.0
*/
public static function write_index_html(string $appname, string $content, string $apptype = 'development_cra') {
if ($content === '') {
return false;
}
$dir = self::resolve_app_directory($appname);
if ($dir === '') {
return false;
}
if ($apptype === 'development_vite') {
return file_put_contents($dir . '/index.html', $content, LOCK_EX);
} elseif ($apptype === 'development_cra') {
$public_dir = realpath($dir . '/public');
$dir_prefix = rtrim(str_replace('\\', '/', $dir), '/') . '/';
if ($public_dir === false || !is_dir($public_dir)) {
return false;
}
$public_prefix = rtrim(str_replace('\\', '/', $public_dir), '/') . '/';
if (!str_starts_with($public_prefix, $dir_prefix)) {
return false;
}
return file_put_contents($public_dir . '/index.html', $content, LOCK_EX);
}
return true;
}
/**
* Canonical permalink of a page assigned to $appname, when $url points at
* that page. Remote hosts and other local URLs return an empty string.
*/
private static function canonical_app_permalink(string $appname, string $url): string {
$url = esc_url_raw($url);
if ($url === '' || !self::is_same_site_url($url)) {
return '';
}
$wanted = self::normalized_url($url);
if ($wanted === '') {
return '';
}
$options = Utils::get_app_options($appname);
$page_ids = (is_array($options) && isset($options['pageIds']) && is_array($options['pageIds']))
? $options['pageIds']
: [];
foreach ($page_ids as $page_id) {
if (!is_numeric($page_id)) {
continue;
}
$permalink = get_permalink((int) $page_id);
if (!is_string($permalink) || $permalink === '' || !self::is_same_site_url($permalink)) {
continue;
}
if (self::normalized_url($permalink) === $wanted) {
return $permalink;
}
}
return '';
}
/**
* Download a same-site permalink as an anonymous visitor. No cookies are
* sent, so the stored index.html never contains the admin bar, nonces or
* the name of the logged-in user. Redirects that leave the site are refused.
*
* @return array<string, mixed>|\WP_Error
*/
private static function fetch_local_permalink(string $url) {
$current = $url;
for ($hop = 0; $hop < 3; $hop++) {
if (!self::is_same_site_url($current)) {
return new \WP_Error('repr_offsite_url', 'Refusing to request a URL outside this site.');
}
$response = wp_safe_remote_get($current, [
'timeout' => 20,
'redirection' => 0,
'limit_response_size' => 2 * 1024 * 1024,
'cookies' => [],
]);
if (is_wp_error($response)) {
return $response;
}
$code = (int) wp_remote_retrieve_response_code($response);
if ($code < 300 || $code >= 400) {
return $response;
}
$location = self::header_value(wp_remote_retrieve_header($response, 'location'));
if ($location === '') {
return $response;
}
$next = self::absolute_redirect_url($current, $location);
if ($next === '' || !self::is_same_site_url($next)) {
return new \WP_Error('repr_offsite_redirect', 'Refusing to follow a redirect off this site.');
}
$current = $next;
}
return new \WP_Error('repr_too_many_redirects', 'Too many redirects.');
}
/**
* True when $url uses http(s) and its host, port, and scheme match this site.
*/
private static function is_same_site_url(string $url): bool {
$url = esc_url_raw($url);
if ($url === '') {
return false;
}
$parts = wp_parse_url($url);
if (!is_array($parts) || empty($parts['host']) || empty($parts['scheme'])) {
return false;
}
if (isset($parts['user']) || isset($parts['pass'])) {
return false;
}
$scheme = strtolower((string) $parts['scheme']);
if ($scheme !== 'http' && $scheme !== 'https') {
return false;
}
$host = rtrim(strtolower((string) $parts['host']), '.');
$port = isset($parts['port']) ? (int) $parts['port'] : ($scheme === 'https' ? 443 : 80);
foreach ([home_url(), site_url()] as $base) {
$base_parts = wp_parse_url((string) $base);
if (!is_array($base_parts) || empty($base_parts['host'])) {
continue;
}
$base_scheme = strtolower((string) ($base_parts['scheme'] ?? 'http'));
if ($base_scheme !== 'http' && $base_scheme !== 'https') {
continue;
}
$base_host = rtrim(strtolower((string) $base_parts['host']), '.');
$base_port = isset($base_parts['port']) ? (int) $base_parts['port'] : ($base_scheme === 'https' ? 443 : 80);
if ($scheme === $base_scheme && $host === $base_host && $port === $base_port) {
return true;
}
}
return false;
}
private static function normalized_url(string $url): string {
$parts = wp_parse_url($url);
if (!is_array($parts) || empty($parts['host']) || empty($parts['scheme'])) {
return '';
}
$scheme = strtolower((string) $parts['scheme']);
$host = rtrim(strtolower((string) $parts['host']), '.');
$port = '';
if (isset($parts['port'])) {
$port_number = (int) $parts['port'];
$is_default = ($scheme === 'https' && $port_number === 443) || ($scheme === 'http' && $port_number === 80);
if (!$is_default) {
$port = ':' . $port_number;
}
}
$path = isset($parts['path']) ? untrailingslashit((string) $parts['path']) : '';
$query = isset($parts['query']) && $parts['query'] !== '' ? '?' . $parts['query'] : '';
return $scheme . '://' . $host . $port . $path . $query;
}
private static function absolute_redirect_url(string $current, string $location): string {
$location = trim($location);
if ($location === '' || str_contains($location, "\n") || str_contains($location, "\r")) {
return '';
}
if (str_starts_with($location, '//')) {
$scheme = wp_parse_url($current, PHP_URL_SCHEME);
return is_string($scheme) ? $scheme . ':' . $location : '';
}
$parts = wp_parse_url($location);
if (is_array($parts) && !empty($parts['host'])) {
return esc_url_raw($location);
}
$absolute = \WP_Http::make_absolute_url($location, $current);
return esc_url_raw($absolute);
}
/**
* @param mixed $header
*/
private static function header_value($header): string {
if (is_array($header)) {
$first = reset($header);
return is_string($first) ? $first : '';
}
return is_string($header) ? $header : '';
}
/**
* App directory inside REPR_APPS_PATH, or '' when $appname escapes that directory.
*/
private static function resolve_app_directory(string $appname): string {
$appname = sanitize_file_name($appname);
if ($appname === '' || !preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{0,100}$/', $appname)) {
return '';
}
$base = realpath(REPR_APPS_PATH);
if ($base === false) {
return '';
}
$dir = realpath($base . DIRECTORY_SEPARATOR . $appname);
if ($dir === false || !is_dir($dir)) {
return '';
}
$base_prefix = rtrim(str_replace('\\', '/', $base), '/') . '/';
$dir_prefix = rtrim(str_replace('\\', '/', $dir), '/') . '/';
if (!str_starts_with($dir_prefix, $base_prefix)) {
return '';
}
return $dir;
}
/**
* Elements that are removed together with their content.
* Includes SVG animation elements, which can set href to javascript: URLs.
*
* @var list<string>
*/
private const REMOVED_ELEMENTS = [
'iframe', 'frame', 'frameset', 'object', 'embed', 'applet', 'portal',
'base', 'form',
'animate', 'set', 'animatemotion', 'animatetransform', 'animatecolor',
'discard', 'handler', 'listener',
];
/**
* Attributes that carry a URL and are checked with is_allowed_resource_url().
*
* @var list<string>
*/
private const URL_ATTRIBUTES = [
'href', 'src', 'action', 'formaction', 'poster', 'xlink:href', 'background',
'data', 'codebase', 'cite', 'longdesc', 'lowsrc', 'dynsrc', 'ping', 'manifest', 'icon',
];
/**
* Ids of admin-bar assets. The page is fetched anonymously, so they should
* not be present; they are removed in case another plugin adds them anyway.
*
* @var list<string>
*/
private const ADMIN_ONLY_IDS = [
'wpadminbar', 'admin-bar-css', 'admin-bar-inline-css', 'admin-bar-js', 'hoverintent-js-js',
];
/**
* Drop active content that must not be stored in a public index.html.
* Theme stylesheets and WordPress core, plugin and theme script files are
* kept so the dev server can still mirror the WordPress page. wp_kses() is
* not used: it would strip the stylesheet and script markup this file exists
* to preserve. Removed: all inline scripts, scripts outside wp-includes,
* plugins and themes (e.g. uploads), inline event handlers, javascript: and
* data: URLs (except raster images in src), SVG animation elements, CSS
* @import, off-site srcset candidates, the admin bar and nonce/logout links.
*/
private static function sanitize_index_html(string $html): string {
$dom = new \DOMDocument();
$previous = libxml_use_internal_errors(true);
$loaded = $dom->loadHTML($html, LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
libxml_clear_errors();
libxml_use_internal_errors($previous);
if (!$loaded) {
return '';
}
foreach (self::REMOVED_ELEMENTS as $tag) {
self::remove_elements_by_tag($dom, $tag);
}
$refresh_metas = [];
foreach ($dom->getElementsByTagName('meta') as $meta) {
if (strtolower(trim($meta->getAttribute('http-equiv'))) === 'refresh') {
$refresh_metas[] = $meta;
}
}
self::remove_nodes($refresh_metas);
$xpath = new \DOMXPath($dom);
$id_conditions = array_map(fn ($id) => '@id="' . $id . '"', self::ADMIN_ONLY_IDS);
$removable = $xpath->query('//*[starts-with(@id, "rp-react-app-asset-") or ' . implode(' or ', $id_conditions) . ']');
if ($removable instanceof \DOMNodeList) {
self::remove_nodes(iterator_to_array($removable));
}
$elements = [];
foreach ($dom->getElementsByTagName('*') as $element) {
$elements[] = $element;
}
foreach ($elements as $element) {
self::sanitize_element_attributes($element);
}
$scripts = [];
foreach ($dom->getElementsByTagName('script') as $script) {
$scripts[] = $script;
}
foreach ($scripts as $script) {
$src = trim($script->getAttribute('src'));
$type = strtolower(trim($script->getAttribute('type')));
if ($src !== '') {
$keep = self::is_allowed_script_src($src);
} else {
// Inline scripts are never kept. JSON data blocks are not executed.
$keep = in_array($type, ['application/json', 'application/ld+json'], true);
}
if (!$keep && $script->parentNode instanceof \DOMNode) {
$script->parentNode->removeChild($script);
}
}
$styles = [];
foreach ($dom->getElementsByTagName('style') as $style) {
$styles[] = $style;
}
foreach ($styles as $style) {
$css = self::sanitize_css((string) $style->textContent);
if ($css === null) {
if ($style->parentNode instanceof \DOMNode) {
$style->parentNode->removeChild($style);
}
} elseif ($css !== $style->textContent) {
$style->textContent = $css;
}
}
$body = $dom->getElementsByTagName('body')->item(0);
if ($body instanceof \DOMElement && $body->hasAttribute('class')) {
$classes = preg_split('/\s+/', trim($body->getAttribute('class')));
$classes = is_array($classes) ? array_diff($classes, ['admin-bar', 'logged-in']) : [];
$body->setAttribute('class', implode(' ', $classes));
}
$saved = $dom->saveHTML();
return is_string($saved) ? $saved : '';
}
/**
* @param array<\DOMNode> $nodes
*/
private static function remove_nodes(array $nodes): void {
foreach ($nodes as $node) {
if ($node->parentNode instanceof \DOMNode) {
$node->parentNode->removeChild($node);
}
}
}
private static function remove_elements_by_tag(\DOMDocument $dom, string $tag): void {
$nodes = [];
foreach ($dom->getElementsByTagName($tag) as $node) {
$nodes[] = $node;
}
self::remove_nodes($nodes);
}
private static function sanitize_element_attributes(\DOMElement $element): void {
$remove = [];
$set = [];
$tag = strtolower($element->tagName);
foreach ($element->attributes as $attr) {
$name = strtolower($attr->nodeName);
$value = (string) $attr->nodeValue;
if (str_starts_with($name, 'on') || $name === 'srcdoc') {
$remove[] = $attr->nodeName;
continue;
}
if (in_array($name, self::URL_ATTRIBUTES, true)) {
// Script sources are checked with the element below. Stripping only the
// attribute would turn <script src="evil">code</script> into an inline script.
if ($name === 'src' && $tag === 'script') {
continue;
}
$allow_data_image = in_array($name, ['src', 'poster'], true);
if ($value !== '' && (!self::is_allowed_resource_url($value, false, $allow_data_image) || self::has_nonce_or_logout($value))) {
$remove[] = $attr->nodeName;
}
continue;
}
if ($name === 'srcset' || $name === 'imagesrcset') {
$clean = self::sanitize_srcset($value);
if ($clean === '') {
$remove[] = $attr->nodeName;
} elseif ($clean !== $value) {
$set[$attr->nodeName] = $clean;
}
continue;
}
if ($name === 'style' && self::sanitize_css($value) !== $value) {
$remove[] = $attr->nodeName;
}
}
foreach ($remove as $attr_name) {
$element->removeAttribute($attr_name);
}
foreach ($set as $attr_name => $attr_value) {
$element->setAttribute($attr_name, $attr_value);
}
}
/**
* True for URLs that carry a nonce or log the user out. They must not be
* stored in a public file.
*/
private static function has_nonce_or_logout(string $url): bool {
return (bool) preg_match('/(?:[?&;]|&)(?:_wpnonce|_ajax_nonce|_wp_http_referer)=|[?&]action=logout\b/i', $url);
}
/**
* Keep only srcset candidates that point to this site (absolute or relative).
*/
private static function sanitize_srcset(string $value): string {
$candidates = preg_split('/,(?=\s)|,$/', trim($value));
if (!is_array($candidates)) {
return '';
}
$kept = [];
foreach ($candidates as $candidate) {
$parts = preg_split('/\s+/', trim($candidate));
if (!is_array($parts) || $parts[0] === '' || count($parts) > 2) {
continue;
}
$url = $parts[0];
$descriptor = $parts[1] ?? '';
if ($descriptor !== '' && !preg_match('/^\d+(?:\.\d+)?[wx]$/', $descriptor)) {
continue;
}
if (!self::is_allowed_resource_url($url, true, false)) {
continue;
}
$kept[] = $descriptor === '' ? $url : $url . ' ' . $descriptor;
}
return implode(', ', $kept);
}
/**
* Remove @import rules from CSS. Returns null when the CSS still contains
* dangerous constructs after that (e.g. obfuscated with escapes or comments).
*/
private static function sanitize_css(string $css): ?string {
$clean = preg_replace('/@import\s[^;{}]*;?/i', '', $css);
$clean = is_string($clean) ? $clean : '';
$decoded = self::decode_css($clean);
if (preg_match('/@import|expression\s*\(|javascript\s*:|vbscript\s*:|-moz-binding|behavior\s*:/i', $decoded)) {
return null;
}
return $clean;
}
/**
* Resolve CSS escapes and drop comments, so checks cannot be bypassed with
* "@\69mport" or "@im/ ** /port".
*/
private static function decode_css(string $css): string {
$decoded = preg_replace('#/\*.*?(?:\*/|$)#s', '', $css);
$decoded = is_string($decoded) ? $decoded : '';
$decoded = preg_replace_callback(
'/\\\\([0-9a-fA-F]{1,6})\s?/',
fn ($m) => html_entity_decode('&#x' . $m[1] . ';', ENT_QUOTES | ENT_HTML5, 'UTF-8'),
$decoded
);
$decoded = is_string($decoded) ? $decoded : '';
$decoded = preg_replace('/\\\\(.)/s', '$1', $decoded);
return is_string($decoded) ? $decoded : '';
}
/**
* Script files are only kept when they are served from this site and live in
* wp-includes, the plugins or the themes directory. Uploads and other paths
* are dropped, because users with upload rights could place files there.
*/
private static function is_allowed_script_src(string $src): bool {
$src = trim($src);
if (!str_starts_with($src, '/') && !preg_match('#^https?://#i', $src)) {
return false;
}
if (!self::is_allowed_resource_url($src, true, false)) {
return false;
}
$path = wp_parse_url($src, PHP_URL_PATH);
if (!is_string($path) || $path === '' || str_contains($path, '..') || str_contains($path, '%') || str_contains($path, '\\')) {
return false;
}
if (!preg_match('/\.m?js$/i', $path)) {
return false;
}
foreach (self::allowed_script_path_prefixes() as $prefix) {
if (str_starts_with($path, $prefix)) {
return true;
}
}
return false;
}
/**
* @return list<string>
*/
private static function allowed_script_path_prefixes(): array {
$urls = [includes_url(), content_url('plugins'), content_url('mu-plugins'), content_url('themes')];
$prefixes = [];
foreach ($urls as $url) {
$path = wp_parse_url((string) $url, PHP_URL_PATH);
if (is_string($path) && $path !== '' && $path !== '/') {
$prefixes[] = rtrim($path, '/') . '/';
}
}
return array_values(array_unique($prefixes));
}
private static function is_allowed_resource_url(string $url, bool $same_site_only, bool $allow_data_image = false): bool {
$url = trim($url);
if ($url === '' || preg_match('/[\x00-\x20\\\\]/', $url)) {
return false;
}
$lower = strtolower($url);
if (str_starts_with($lower, 'data:')) {
// Only raster images; SVG data URLs can contain scripts.
return $allow_data_image && (bool) preg_match('#^data:image/(?:png|jpe?g|gif|webp|avif|bmp)[;,]#', $lower);
}
foreach (['javascript:', 'vbscript:', 'file:'] as $scheme) {
if (str_starts_with($lower, $scheme)) {
return false;
}
}
if (!$same_site_only && preg_match('#^(mailto|tel):#i', $url)) {
return true;
}
if (str_starts_with($url, '//') || str_contains($url, '..')) {
return false;
}
if (str_starts_with($url, '#') || str_starts_with($url, '?') || str_starts_with($url, '/')) {
return true;
}
if (preg_match('#^https?://#i', $url)) {
return $same_site_only ? self::is_same_site_url($url) : true;
}
return !preg_match('#^[a-z][a-z0-9+.-]*:#i', $url);
}
}