mirrored from git://develop.git.wordpress.org/
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
file.php
2835 lines (2468 loc) · 96.1 KB
/
file.php
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Filesystem API: Top-level functionality
*
* Functions for reading, writing, modifying, and deleting files on the file system.
* Includes functionality for theme-specific files as well as operations for uploading,
* archiving, and rendering output when necessary.
*
* @package WordPress
* @subpackage Filesystem
* @since 2.3.0
*/
/** The descriptions for theme files. */
$wp_file_descriptions = array(
'functions.php' => __( 'Theme Functions' ),
'header.php' => __( 'Theme Header' ),
'footer.php' => __( 'Theme Footer' ),
'sidebar.php' => __( 'Sidebar' ),
'comments.php' => __( 'Comments' ),
'searchform.php' => __( 'Search Form' ),
'404.php' => __( '404 Template' ),
'link.php' => __( 'Links Template' ),
'theme.json' => __( 'Theme Styles & Block Settings' ),
// Archives.
'index.php' => __( 'Main Index Template' ),
'archive.php' => __( 'Archives' ),
'author.php' => __( 'Author Template' ),
'taxonomy.php' => __( 'Taxonomy Template' ),
'category.php' => __( 'Category Template' ),
'tag.php' => __( 'Tag Template' ),
'home.php' => __( 'Posts Page' ),
'search.php' => __( 'Search Results' ),
'date.php' => __( 'Date Template' ),
// Content.
'singular.php' => __( 'Singular Template' ),
'single.php' => __( 'Single Post' ),
'page.php' => __( 'Single Page' ),
'front-page.php' => __( 'Homepage' ),
'privacy-policy.php' => __( 'Privacy Policy Page' ),
// Attachments.
'attachment.php' => __( 'Attachment Template' ),
'image.php' => __( 'Image Attachment Template' ),
'video.php' => __( 'Video Attachment Template' ),
'audio.php' => __( 'Audio Attachment Template' ),
'application.php' => __( 'Application Attachment Template' ),
// Embeds.
'embed.php' => __( 'Embed Template' ),
'embed-404.php' => __( 'Embed 404 Template' ),
'embed-content.php' => __( 'Embed Content Template' ),
'header-embed.php' => __( 'Embed Header Template' ),
'footer-embed.php' => __( 'Embed Footer Template' ),
// Stylesheets.
'style.css' => __( 'Stylesheet' ),
'editor-style.css' => __( 'Visual Editor Stylesheet' ),
'editor-style-rtl.css' => __( 'Visual Editor RTL Stylesheet' ),
'rtl.css' => __( 'RTL Stylesheet' ),
// Other.
'my-hacks.php' => __( 'my-hacks.php (legacy hacks support)' ),
'.htaccess' => __( '.htaccess (for rewrite rules )' ),
// Deprecated files.
'wp-layout.css' => __( 'Stylesheet' ),
'wp-comments.php' => __( 'Comments Template' ),
'wp-comments-popup.php' => __( 'Popup Comments Template' ),
'comments-popup.php' => __( 'Popup Comments' ),
);
/**
* Gets the description for standard WordPress theme files.
*
* @since 1.5.0
*
* @global array $wp_file_descriptions Theme file descriptions.
* @global array $allowed_files List of allowed files.
*
* @param string $file Filesystem path or filename.
* @return string Description of file from $wp_file_descriptions or basename of $file if description doesn't exist.
* Appends 'Page Template' to basename of $file if the file is a page template.
*/
function get_file_description( $file ) {
global $wp_file_descriptions, $allowed_files;
$dirname = pathinfo( $file, PATHINFO_DIRNAME );
$file_path = $allowed_files[ $file ];
if ( isset( $wp_file_descriptions[ basename( $file ) ] ) && '.' === $dirname ) {
return $wp_file_descriptions[ basename( $file ) ];
} elseif ( file_exists( $file_path ) && is_file( $file_path ) ) {
$template_data = implode( '', file( $file_path ) );
if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) ) {
/* translators: %s: Template name. */
return sprintf( __( '%s Page Template' ), _cleanup_header_comment( $name[1] ) );
}
}
return trim( basename( $file ) );
}
/**
* Gets the absolute filesystem path to the root of the WordPress installation.
*
* @since 1.5.0
*
* @return string Full filesystem path to the root of the WordPress installation.
*/
function get_home_path() {
$home = set_url_scheme( get_option( 'home' ), 'http' );
$siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) {
$wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
$pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );
$home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
$home_path = trailingslashit( $home_path );
} else {
$home_path = ABSPATH;
}
return str_replace( '\\', '/', $home_path );
}
/**
* Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep.
*
* The depth of the recursiveness can be controlled by the $levels param.
*
* @since 2.6.0
* @since 4.9.0 Added the `$exclusions` parameter.
* @since 6.3.0 Added the `$include_hidden` parameter.
*
* @param string $folder Optional. Full path to folder. Default empty.
* @param int $levels Optional. Levels of folders to follow, Default 100 (PHP Loop limit).
* @param string[] $exclusions Optional. List of folders and files to skip.
* @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
* Default false.
* @return string[]|false Array of files on success, false on failure.
*/
function list_files( $folder = '', $levels = 100, $exclusions = array(), $include_hidden = false ) {
if ( empty( $folder ) ) {
return false;
}
$folder = trailingslashit( $folder );
if ( ! $levels ) {
return false;
}
$files = array();
$dir = @opendir( $folder );
if ( $dir ) {
while ( ( $file = readdir( $dir ) ) !== false ) {
// Skip current and parent folder links.
if ( in_array( $file, array( '.', '..' ), true ) ) {
continue;
}
// Skip hidden and excluded files.
if ( ( ! $include_hidden && '.' === $file[0] ) || in_array( $file, $exclusions, true ) ) {
continue;
}
if ( is_dir( $folder . $file ) ) {
$files2 = list_files( $folder . $file, $levels - 1, array(), $include_hidden );
if ( $files2 ) {
$files = array_merge( $files, $files2 );
} else {
$files[] = $folder . $file . '/';
}
} else {
$files[] = $folder . $file;
}
}
closedir( $dir );
}
return $files;
}
/**
* Gets the list of file extensions that are editable in plugins.
*
* @since 4.9.0
*
* @param string $plugin Path to the plugin file relative to the plugins directory.
* @return string[] Array of editable file extensions.
*/
function wp_get_plugin_file_editable_extensions( $plugin ) {
$default_types = array(
'bash',
'conf',
'css',
'diff',
'htm',
'html',
'http',
'inc',
'include',
'js',
'json',
'jsx',
'less',
'md',
'patch',
'php',
'php3',
'php4',
'php5',
'php7',
'phps',
'phtml',
'sass',
'scss',
'sh',
'sql',
'svg',
'text',
'txt',
'xml',
'yaml',
'yml',
);
/**
* Filters the list of file types allowed for editing in the plugin file editor.
*
* @since 2.8.0
* @since 4.9.0 Added the `$plugin` parameter.
*
* @param string[] $default_types An array of editable plugin file extensions.
* @param string $plugin Path to the plugin file relative to the plugins directory.
*/
$file_types = (array) apply_filters( 'editable_extensions', $default_types, $plugin );
return $file_types;
}
/**
* Gets the list of file extensions that are editable for a given theme.
*
* @since 4.9.0
*
* @param WP_Theme $theme Theme object.
* @return string[] Array of editable file extensions.
*/
function wp_get_theme_file_editable_extensions( $theme ) {
$default_types = array(
'bash',
'conf',
'css',
'diff',
'htm',
'html',
'http',
'inc',
'include',
'js',
'json',
'jsx',
'less',
'md',
'patch',
'php',
'php3',
'php4',
'php5',
'php7',
'phps',
'phtml',
'sass',
'scss',
'sh',
'sql',
'svg',
'text',
'txt',
'xml',
'yaml',
'yml',
);
/**
* Filters the list of file types allowed for editing in the theme file editor.
*
* @since 4.4.0
*
* @param string[] $default_types An array of editable theme file extensions.
* @param WP_Theme $theme The active theme object.
*/
$file_types = apply_filters( 'wp_theme_editor_filetypes', $default_types, $theme );
// Ensure that default types are still there.
return array_unique( array_merge( $file_types, $default_types ) );
}
/**
* Prints file editor templates (for plugins and themes).
*
* @since 4.9.0
*/
function wp_print_file_editor_templates() {
?>
<script type="text/html" id="tmpl-wp-file-editor-notice">
<div class="notice inline notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.classes || '' }}">
<# if ( 'php_error' === data.code ) { #>
<p>
<?php
printf(
/* translators: 1: Line number, 2: File path. */
__( 'Your PHP code changes were not applied due to an error on line %1$s of file %2$s. Please fix and try saving again.' ),
'{{ data.line }}',
'{{ data.file }}'
);
?>
</p>
<pre>{{ data.message }}</pre>
<# } else if ( 'file_not_writable' === data.code ) { #>
<p>
<?php
printf(
/* translators: %s: Documentation URL. */
__( 'You need to make this file writable before you can save your changes. See <a href="%s">Changing File Permissions</a> for more information.' ),
__( 'https://wordpress.org/documentation/article/changing-file-permissions/' )
);
?>
</p>
<# } else { #>
<p>{{ data.message || data.code }}</p>
<# if ( 'lint_errors' === data.code ) { #>
<p>
<# var elementId = 'el-' + String( Math.random() ); #>
<input id="{{ elementId }}" type="checkbox">
<label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label>
</p>
<# } #>
<# } #>
<# if ( data.dismissible ) { #>
<button type="button" class="notice-dismiss"><span class="screen-reader-text">
<?php
/* translators: Hidden accessibility text. */
_e( 'Dismiss' );
?>
</span></button>
<# } #>
</div>
</script>
<?php
}
/**
* Attempts to edit a file for a theme or plugin.
*
* When editing a PHP file, loopback requests will be made to the admin and the homepage
* to attempt to see if there is a fatal error introduced. If so, the PHP change will be
* reverted.
*
* @since 4.9.0
*
* @param string[] $args {
* Args. Note that all of the arg values are already unslashed. They are, however,
* coming straight from `$_POST` and are not validated or sanitized in any way.
*
* @type string $file Relative path to file.
* @type string $plugin Path to the plugin file relative to the plugins directory.
* @type string $theme Theme being edited.
* @type string $newcontent New content for the file.
* @type string $nonce Nonce.
* }
* @return true|WP_Error True on success or `WP_Error` on failure.
*/
function wp_edit_theme_plugin_file( $args ) {
if ( empty( $args['file'] ) ) {
return new WP_Error( 'missing_file' );
}
if ( 0 !== validate_file( $args['file'] ) ) {
return new WP_Error( 'bad_file' );
}
if ( ! isset( $args['newcontent'] ) ) {
return new WP_Error( 'missing_content' );
}
if ( ! isset( $args['nonce'] ) ) {
return new WP_Error( 'missing_nonce' );
}
$file = $args['file'];
$content = $args['newcontent'];
$plugin = null;
$theme = null;
$real_file = null;
if ( ! empty( $args['plugin'] ) ) {
$plugin = $args['plugin'];
if ( ! current_user_can( 'edit_plugins' ) ) {
return new WP_Error( 'unauthorized', __( 'Sorry, you are not allowed to edit plugins for this site.' ) );
}
if ( ! wp_verify_nonce( $args['nonce'], 'edit-plugin_' . $file ) ) {
return new WP_Error( 'nonce_failure' );
}
if ( ! array_key_exists( $plugin, get_plugins() ) ) {
return new WP_Error( 'invalid_plugin' );
}
if ( 0 !== validate_file( $file, get_plugin_files( $plugin ) ) ) {
return new WP_Error( 'bad_plugin_file_path', __( 'Sorry, that file cannot be edited.' ) );
}
$editable_extensions = wp_get_plugin_file_editable_extensions( $plugin );
$real_file = WP_PLUGIN_DIR . '/' . $file;
$is_active = in_array(
$plugin,
(array) get_option( 'active_plugins', array() ),
true
);
} elseif ( ! empty( $args['theme'] ) ) {
$stylesheet = $args['theme'];
if ( 0 !== validate_file( $stylesheet ) ) {
return new WP_Error( 'bad_theme_path' );
}
if ( ! current_user_can( 'edit_themes' ) ) {
return new WP_Error( 'unauthorized', __( 'Sorry, you are not allowed to edit templates for this site.' ) );
}
$theme = wp_get_theme( $stylesheet );
if ( ! $theme->exists() ) {
return new WP_Error( 'non_existent_theme', __( 'The requested theme does not exist.' ) );
}
if ( ! wp_verify_nonce( $args['nonce'], 'edit-theme_' . $stylesheet . '_' . $file ) ) {
return new WP_Error( 'nonce_failure' );
}
if ( $theme->errors() && 'theme_no_stylesheet' === $theme->errors()->get_error_code() ) {
return new WP_Error(
'theme_no_stylesheet',
__( 'The requested theme does not exist.' ) . ' ' . $theme->errors()->get_error_message()
);
}
$editable_extensions = wp_get_theme_file_editable_extensions( $theme );
$allowed_files = array();
foreach ( $editable_extensions as $type ) {
switch ( $type ) {
case 'php':
$allowed_files = array_merge( $allowed_files, $theme->get_files( 'php', -1 ) );
break;
case 'css':
$style_files = $theme->get_files( 'css', -1 );
$allowed_files['style.css'] = $style_files['style.css'];
$allowed_files = array_merge( $allowed_files, $style_files );
break;
default:
$allowed_files = array_merge( $allowed_files, $theme->get_files( $type, -1 ) );
break;
}
}
// Compare based on relative paths.
if ( 0 !== validate_file( $file, array_keys( $allowed_files ) ) ) {
return new WP_Error( 'disallowed_theme_file', __( 'Sorry, that file cannot be edited.' ) );
}
$real_file = $theme->get_stylesheet_directory() . '/' . $file;
$is_active = ( get_stylesheet() === $stylesheet || get_template() === $stylesheet );
} else {
return new WP_Error( 'missing_theme_or_plugin' );
}
// Ensure file is real.
if ( ! is_file( $real_file ) ) {
return new WP_Error( 'file_does_not_exist', __( 'File does not exist! Please double check the name and try again.' ) );
}
// Ensure file extension is allowed.
$extension = null;
if ( preg_match( '/\.([^.]+)$/', $real_file, $matches ) ) {
$extension = strtolower( $matches[1] );
if ( ! in_array( $extension, $editable_extensions, true ) ) {
return new WP_Error( 'illegal_file_type', __( 'Files of this type are not editable.' ) );
}
}
$previous_content = file_get_contents( $real_file );
if ( ! is_writable( $real_file ) ) {
return new WP_Error( 'file_not_writable' );
}
$f = fopen( $real_file, 'w+' );
if ( false === $f ) {
return new WP_Error( 'file_not_writable' );
}
$written = fwrite( $f, $content );
fclose( $f );
if ( false === $written ) {
return new WP_Error( 'unable_to_write', __( 'Unable to write to file.' ) );
}
wp_opcache_invalidate( $real_file, true );
if ( $is_active && 'php' === $extension ) {
$scrape_key = md5( rand() );
$transient = 'scrape_key_' . $scrape_key;
$scrape_nonce = (string) rand();
// It shouldn't take more than 60 seconds to make the two loopback requests.
set_transient( $transient, $scrape_nonce, 60 );
$cookies = wp_unslash( $_COOKIE );
$scrape_params = array(
'wp_scrape_key' => $scrape_key,
'wp_scrape_nonce' => $scrape_nonce,
);
$headers = array(
'Cache-Control' => 'no-cache',
);
/** This filter is documented in wp-includes/class-wp-http-streams.php */
$sslverify = apply_filters( 'https_local_ssl_verify', false );
// Include Basic auth in loopback requests.
if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
$headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
}
// Make sure PHP process doesn't die before loopback requests complete.
if ( function_exists( 'set_time_limit' ) ) {
set_time_limit( 5 * MINUTE_IN_SECONDS );
}
// Time to wait for loopback requests to finish.
$timeout = 100; // 100 seconds.
$needle_start = "###### wp_scraping_result_start:$scrape_key ######";
$needle_end = "###### wp_scraping_result_end:$scrape_key ######";
// Attempt loopback request to editor to see if user just whitescreened themselves.
if ( $plugin ) {
$url = add_query_arg( compact( 'plugin', 'file' ), admin_url( 'plugin-editor.php' ) );
} elseif ( isset( $stylesheet ) ) {
$url = add_query_arg(
array(
'theme' => $stylesheet,
'file' => $file,
),
admin_url( 'theme-editor.php' )
);
} else {
$url = admin_url();
}
if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
/*
* Close any active session to prevent HTTP requests from timing out
* when attempting to connect back to the site.
*/
session_write_close();
}
$url = add_query_arg( $scrape_params, $url );
$r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
$body = wp_remote_retrieve_body( $r );
$scrape_result_position = strpos( $body, $needle_start );
$loopback_request_failure = array(
'code' => 'loopback_request_failed',
'message' => __( 'Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.' ),
);
$json_parse_failure = array(
'code' => 'json_parse_error',
);
$result = null;
if ( false === $scrape_result_position ) {
$result = $loopback_request_failure;
} else {
$error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
$error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
$result = json_decode( trim( $error_output ), true );
if ( empty( $result ) ) {
$result = $json_parse_failure;
}
}
// Try making request to homepage as well to see if visitors have been whitescreened.
if ( true === $result ) {
$url = home_url( '/' );
$url = add_query_arg( $scrape_params, $url );
$r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
$body = wp_remote_retrieve_body( $r );
$scrape_result_position = strpos( $body, $needle_start );
if ( false === $scrape_result_position ) {
$result = $loopback_request_failure;
} else {
$error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
$error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
$result = json_decode( trim( $error_output ), true );
if ( empty( $result ) ) {
$result = $json_parse_failure;
}
}
}
delete_transient( $transient );
if ( true !== $result ) {
// Roll-back file change.
file_put_contents( $real_file, $previous_content );
wp_opcache_invalidate( $real_file, true );
if ( ! isset( $result['message'] ) ) {
$message = __( 'Something went wrong.' );
} else {
$message = $result['message'];
unset( $result['message'] );
}
return new WP_Error( 'php_error', $message, $result );
}
}
if ( $theme instanceof WP_Theme ) {
$theme->cache_delete();
}
return true;
}
/**
* Returns a filename of a temporary unique file.
*
* Please note that the calling function must delete or move the file.
*
* The filename is based off the passed parameter or defaults to the current unix timestamp,
* while the directory can either be passed as well, or by leaving it blank, default to a writable
* temporary directory.
*
* @since 2.6.0
*
* @param string $filename Optional. Filename to base the Unique file off. Default empty.
* @param string $dir Optional. Directory to store the file in. Default empty.
* @return string A writable filename.
*/
function wp_tempnam( $filename = '', $dir = '' ) {
if ( empty( $dir ) ) {
$dir = get_temp_dir();
}
if ( empty( $filename ) || in_array( $filename, array( '.', '/', '\\' ), true ) ) {
$filename = uniqid();
}
// Use the basename of the given file without the extension as the name for the temporary directory.
$temp_filename = basename( $filename );
$temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename );
// If the folder is falsey, use its parent directory name instead.
if ( ! $temp_filename ) {
return wp_tempnam( dirname( $filename ), $dir );
}
// Suffix some random data to avoid filename conflicts.
$temp_filename .= '-' . wp_generate_password( 6, false );
$temp_filename .= '.tmp';
$temp_filename = wp_unique_filename( $dir, $temp_filename );
/*
* Filesystems typically have a limit of 255 characters for a filename.
*
* If the generated unique filename exceeds this, truncate the initial
* filename and try again.
*
* As it's possible that the truncated filename may exist, producing a
* suffix of "-1" or "-10" which could exceed the limit again, truncate
* it to 252 instead.
*/
$characters_over_limit = strlen( $temp_filename ) - 252;
if ( $characters_over_limit > 0 ) {
$filename = substr( $filename, 0, -$characters_over_limit );
return wp_tempnam( $filename, $dir );
}
$temp_filename = $dir . $temp_filename;
$fp = @fopen( $temp_filename, 'x' );
if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) {
return wp_tempnam( $filename, $dir );
}
if ( $fp ) {
fclose( $fp );
}
return $temp_filename;
}
/**
* Makes sure that the file that was requested to be edited is allowed to be edited.
*
* Function will die if you are not allowed to edit the file.
*
* @since 1.5.0
*
* @param string $file File the user is attempting to edit.
* @param string[] $allowed_files Optional. Array of allowed files to edit.
* `$file` must match an entry exactly.
* @return string|void Returns the file name on success, dies on failure.
*/
function validate_file_to_edit( $file, $allowed_files = array() ) {
$code = validate_file( $file, $allowed_files );
if ( ! $code ) {
return $file;
}
switch ( $code ) {
case 1:
wp_die( __( 'Sorry, that file cannot be edited.' ) );
// case 2 :
// wp_die( __('Sorry, cannot call files with their real path.' ));
case 3:
wp_die( __( 'Sorry, that file cannot be edited.' ) );
}
}
/**
* Handles PHP uploads in WordPress.
*
* Sanitizes file names, checks extensions for mime type, and moves the file
* to the appropriate directory within the uploads directory.
*
* @access private
* @since 4.0.0
*
* @see wp_handle_upload_error
*
* @param array $file {
* Reference to a single element from `$_FILES`. Call the function once for each uploaded file.
*
* @type string $name The original name of the file on the client machine.
* @type string $type The mime type of the file, if the browser provided this information.
* @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
* @type int $size The size, in bytes, of the uploaded file.
* @type int $error The error code associated with this file upload.
* }
* @param array|false $overrides {
* An array of override parameters for this file, or boolean false if none are provided.
*
* @type callable $upload_error_handler Function to call when there is an error during the upload process.
* See {@see wp_handle_upload_error()}.
* @type callable $unique_filename_callback Function to call when determining a unique file name for the file.
* See {@see wp_unique_filename()}.
* @type string[] $upload_error_strings The strings that describe the error indicated in
* `$_FILES[{form field}]['error']`.
* @type bool $test_form Whether to test that the `$_POST['action']` parameter is as expected.
* @type bool $test_size Whether to test that the file size is greater than zero bytes.
* @type bool $test_type Whether to test that the mime type of the file is as expected.
* @type string[] $mimes Array of allowed mime types keyed by their file extension regex.
* }
* @param string $time Time formatted in 'yyyy/mm'.
* @param string $action Expected value for `$_POST['action']`.
* @return array {
* On success, returns an associative array of file attributes.
* On failure, returns `$overrides['upload_error_handler']( &$file, $message )`
* or `array( 'error' => $message )`.
*
* @type string $file Filename of the newly-uploaded file.
* @type string $url URL of the newly-uploaded file.
* @type string $type Mime type of the newly-uploaded file.
* }
*/
function _wp_handle_upload( &$file, $overrides, $time, $action ) {
// The default error handler.
if ( ! function_exists( 'wp_handle_upload_error' ) ) {
function wp_handle_upload_error( &$file, $message ) {
return array( 'error' => $message );
}
}
/**
* Filters the data for a file before it is uploaded to WordPress.
*
* The dynamic portion of the hook name, `$action`, refers to the post action.
*
* Possible hook names include:
*
* - `wp_handle_sideload_prefilter`
* - `wp_handle_upload_prefilter`
*
* @since 2.9.0 as 'wp_handle_upload_prefilter'.
* @since 4.0.0 Converted to a dynamic hook with `$action`.
*
* @param array $file {
* Reference to a single element from `$_FILES`.
*
* @type string $name The original name of the file on the client machine.
* @type string $type The mime type of the file, if the browser provided this information.
* @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
* @type int $size The size, in bytes, of the uploaded file.
* @type int $error The error code associated with this file upload.
* }
*/
$file = apply_filters( "{$action}_prefilter", $file );
/**
* Filters the override parameters for a file before it is uploaded to WordPress.
*
* The dynamic portion of the hook name, `$action`, refers to the post action.
*
* Possible hook names include:
*
* - `wp_handle_sideload_overrides`
* - `wp_handle_upload_overrides`
*
* @since 5.7.0
*
* @param array|false $overrides An array of override parameters for this file. Boolean false if none are
* provided. See {@see _wp_handle_upload()}.
* @param array $file {
* Reference to a single element from `$_FILES`.
*
* @type string $name The original name of the file on the client machine.
* @type string $type The mime type of the file, if the browser provided this information.
* @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
* @type int $size The size, in bytes, of the uploaded file.
* @type int $error The error code associated with this file upload.
* }
*/
$overrides = apply_filters( "{$action}_overrides", $overrides, $file );
// You may define your own function and pass the name in $overrides['upload_error_handler'].
$upload_error_handler = 'wp_handle_upload_error';
if ( isset( $overrides['upload_error_handler'] ) ) {
$upload_error_handler = $overrides['upload_error_handler'];
}
// You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) {
return call_user_func_array( $upload_error_handler, array( &$file, $file['error'] ) );
}
// Install user overrides. Did we mention that this voids your warranty?
// You may define your own function and pass the name in $overrides['unique_filename_callback'].
$unique_filename_callback = null;
if ( isset( $overrides['unique_filename_callback'] ) ) {
$unique_filename_callback = $overrides['unique_filename_callback'];
}
/*
* This may not have originally been intended to be overridable,
* but historically has been.
*/
if ( isset( $overrides['upload_error_strings'] ) ) {
$upload_error_strings = $overrides['upload_error_strings'];
} else {
// Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
$upload_error_strings = array(
false,
sprintf(
/* translators: 1: upload_max_filesize, 2: php.ini */
__( 'The uploaded file exceeds the %1$s directive in %2$s.' ),
'upload_max_filesize',
'php.ini'
),
sprintf(
/* translators: %s: MAX_FILE_SIZE */
__( 'The uploaded file exceeds the %s directive that was specified in the HTML form.' ),
'MAX_FILE_SIZE'
),
__( 'The uploaded file was only partially uploaded.' ),
__( 'No file was uploaded.' ),
'',
__( 'Missing a temporary folder.' ),
__( 'Failed to write file to disk.' ),
__( 'File upload stopped by extension.' ),
);
}
// All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
$test_form = isset( $overrides['test_form'] ) ? $overrides['test_form'] : true;
$test_size = isset( $overrides['test_size'] ) ? $overrides['test_size'] : true;
// If you override this, you must provide $ext and $type!!
$test_type = isset( $overrides['test_type'] ) ? $overrides['test_type'] : true;
$mimes = isset( $overrides['mimes'] ) ? $overrides['mimes'] : null;
// A correct form post will pass this test.
if ( $test_form && ( ! isset( $_POST['action'] ) || $_POST['action'] !== $action ) ) {
return call_user_func_array( $upload_error_handler, array( &$file, __( 'Invalid form submission.' ) ) );
}
// A successful upload will pass this test. It makes no sense to override this one.
if ( isset( $file['error'] ) && $file['error'] > 0 ) {
return call_user_func_array( $upload_error_handler, array( &$file, $upload_error_strings[ $file['error'] ] ) );
}
// A properly uploaded file will pass this test. There should be no reason to override this one.
$test_uploaded_file = 'wp_handle_upload' === $action ? is_uploaded_file( $file['tmp_name'] ) : @is_readable( $file['tmp_name'] );
if ( ! $test_uploaded_file ) {
return call_user_func_array( $upload_error_handler, array( &$file, __( 'Specified file failed upload test.' ) ) );
}
$test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] );
// A non-empty file will pass this test.
if ( $test_size && ! ( $test_file_size > 0 ) ) {
if ( is_multisite() ) {
$error_msg = __( 'File is empty. Please upload something more substantial.' );
} else {
$error_msg = sprintf(
/* translators: 1: php.ini, 2: post_max_size, 3: upload_max_filesize */
__( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your %1$s file or by %2$s being defined as smaller than %3$s in %1$s.' ),
'php.ini',
'post_max_size',
'upload_max_filesize'
);
}
return call_user_func_array( $upload_error_handler, array( &$file, $error_msg ) );
}
// A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
if ( $test_type ) {
$wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
$ext = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
$type = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
$proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
// Check to see if wp_check_filetype_and_ext() determined the filename was incorrect.
if ( $proper_filename ) {
$file['name'] = $proper_filename;
}
if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
return call_user_func_array( $upload_error_handler, array( &$file, __( 'Sorry, you are not allowed to upload this file type.' ) ) );
}
if ( ! $type ) {
$type = $file['type'];
}
} else {
$type = '';
}
/*
* A writable uploads dir will pass this test. Again, there's no point
* overriding this one.
*/
$uploads = wp_upload_dir( $time );
if ( ! ( $uploads && false === $uploads['error'] ) ) {
return call_user_func_array( $upload_error_handler, array( &$file, $uploads['error'] ) );
}
$filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
// Move the file to the uploads dir.
$new_file = $uploads['path'] . "/$filename";
/**
* Filters whether to short-circuit moving the uploaded file after passing all checks.
*
* If a non-null value is returned from the filter, moving the file and any related
* error reporting will be completely skipped.
*
* @since 4.9.0
*
* @param mixed $move_new_file If null (default) move the file after the upload.
* @param array $file {
* Reference to a single element from `$_FILES`.
*