file.php 80.2 KB
Newer Older
godog's avatar
godog committed
1
2
<?php
/**
lechuck's avatar
lechuck committed
3
4
 * Filesystem API: Top-level functionality
 *
lechuck's avatar
lechuck committed
5
6
7
 * 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.
godog's avatar
godog committed
8
9
 *
 * @package WordPress
lechuck's avatar
lechuck committed
10
11
 * @subpackage Filesystem
 * @since 2.3.0
godog's avatar
godog committed
12
13
14
 */

/** The descriptions for theme files. */
root's avatar
root committed
15
$wp_file_descriptions = array(
lechuck's avatar
lechuck committed
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
	'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' ),
	// 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' ),
lucha's avatar
lucha committed
38
	'front-page.php'        => __( 'Homepage' ),
lechuck's avatar
lechuck committed
39
40
41
42
43
44
	// 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' ),
lucha's avatar
lucha committed
45
46
47
48
49
50
	// 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' ),
lechuck's avatar
lechuck committed
51
52
53
54
55
56
57
58
	// 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 )' ),
godog's avatar
godog committed
59
	// Deprecated files
lechuck's avatar
lechuck committed
60
61
	'wp-layout.css'         => __( 'Stylesheet' ),
	'wp-comments.php'       => __( 'Comments Template' ),
root's avatar
root committed
62
	'wp-comments-popup.php' => __( 'Popup Comments Template' ),
lechuck's avatar
lechuck committed
63
	'comments-popup.php'    => __( 'Popup Comments' ),
root's avatar
root committed
64
);
godog's avatar
godog committed
65
66

/**
root's avatar
root committed
67
68
 * Get the description for standard WordPress theme files and other various standard
 * WordPress files
godog's avatar
godog committed
69
 *
root's avatar
root committed
70
 * @since 1.5.0
godog's avatar
godog committed
71
 *
lucha's avatar
lucha committed
72
73
 * @global array $wp_file_descriptions Theme file descriptions.
 * @global array $allowed_files        List of allowed files.
root's avatar
root committed
74
 * @param string $file Filesystem path or filename
lechuck's avatar
lechuck committed
75
76
 * @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
godog's avatar
godog committed
77
78
 */
function get_file_description( $file ) {
lechuck's avatar
lechuck committed
79
80
	global $wp_file_descriptions, $allowed_files;

lucha's avatar
lucha committed
81
82
	$dirname = pathinfo( $file, PATHINFO_DIRNAME );

lechuck's avatar
lechuck committed
83
	$file_path = $allowed_files[ $file ];
lucha's avatar
lucha committed
84
	if ( isset( $wp_file_descriptions[ basename( $file ) ] ) && '.' === $dirname ) {
lechuck's avatar
lechuck committed
85
86
87
88
89
90
		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 ) ) {
			return sprintf( __( '%s Page Template' ), _cleanup_header_comment( $name[1] ) );
		}
godog's avatar
godog committed
91
92
	}

lechuck's avatar
lechuck committed
93
	return trim( basename( $file ) );
godog's avatar
godog committed
94
95
96
}

/**
root's avatar
root committed
97
 * Get the absolute filesystem path to the root of the WordPress installation
godog's avatar
godog committed
98
 *
root's avatar
root committed
99
 * @since 1.5.0
godog's avatar
godog committed
100
 *
root's avatar
root committed
101
 * @return string Full filesystem path to the root of the WordPress installation
godog's avatar
godog committed
102
103
 */
function get_home_path() {
lucha's avatar
lucha committed
104
105
	$home    = set_url_scheme( get_option( 'home' ), 'http' );
	$siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
lechuck's avatar
lechuck committed
106
107
108
109
	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 );
godog's avatar
godog committed
110
111
112
113
114
		$home_path = trailingslashit( $home_path );
	} else {
		$home_path = ABSPATH;
	}

lechuck's avatar
lechuck committed
115
	return str_replace( '\\', '/', $home_path );
godog's avatar
godog committed
116
117
118
119
120
121
122
}

/**
 * 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
lucha's avatar
lucha committed
123
 * @since 4.9.0 Added the `$exclusions` parameter.
godog's avatar
godog committed
124
 *
lechuck's avatar
lechuck committed
125
126
 * @param string $folder Optional. Full path to folder. Default empty.
 * @param int    $levels Optional. Levels of folders to follow, Default 100 (PHP Loop limit).
lucha's avatar
lucha committed
127
 * @param array  $exclusions Optional. List of folders and files to skip.
godog's avatar
godog committed
128
129
 * @return bool|array False on failure, Else array of files
 */
lucha's avatar
lucha committed
130
131
function list_files( $folder = '', $levels = 100, $exclusions = array() ) {
	if ( empty( $folder ) ) {
godog's avatar
godog committed
132
		return false;
lucha's avatar
lucha committed
133
134
135
	}

	$folder = trailingslashit( $folder );
godog's avatar
godog committed
136

lucha's avatar
lucha committed
137
	if ( ! $levels ) {
godog's avatar
godog committed
138
		return false;
lucha's avatar
lucha committed
139
	}
godog's avatar
godog committed
140
141

	$files = array();
lucha's avatar
lucha committed
142
143
144
145
146
147
148
149
150
151
152

	$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 ( '.' === $file[0] || in_array( $file, $exclusions, true ) ) {
godog's avatar
godog committed
153
				continue;
lucha's avatar
lucha committed
154
155
156
157
158
			}

			if ( is_dir( $folder . $file ) ) {
				$files2 = list_files( $folder . $file, $levels - 1 );
				if ( $files2 ) {
godog's avatar
godog committed
159
					$files = array_merge($files, $files2 );
lucha's avatar
lucha committed
160
161
162
				} else {
					$files[] = $folder . $file . '/';
				}
godog's avatar
godog committed
163
			} else {
lucha's avatar
lucha committed
164
				$files[] = $folder . $file;
godog's avatar
godog committed
165
166
167
168
			}
		}
	}
	@closedir( $dir );
lucha's avatar
lucha committed
169

godog's avatar
godog committed
170
171
172
	return $files;
}

lucha's avatar
lucha committed
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
/**
 * Get list of file extensions that are editable in plugins.
 *
 * @since 4.9.0
 *
 * @param string $plugin Plugin.
 * @return array File extensions.
 */
function wp_get_plugin_file_editable_extensions( $plugin ) {

	$editable_extensions = 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 file type extensions editable in the plugin editor.
	 *
	 * @since 2.8.0
	 * @since 4.9.0 Adds $plugin param.
	 *
	 * @param string $plugin Plugin file.
	 * @param array $editable_extensions An array of editable plugin file extensions.
	 */
	$editable_extensions = (array) apply_filters( 'editable_extensions', $editable_extensions, $plugin );

	return $editable_extensions;
}

/**
 * Get list of file extensions that are editable for a given theme.
 *
 * @param WP_Theme $theme Theme.
 * @return array 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 editor.
	 *
	 * @since 4.4.0
	 *
	 * @param array    $default_types List of file types. Default types include 'php' and 'css'.
	 * @param WP_Theme $theme         The current 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 ) );
}

/**
 * Print 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: %$1s is line number and %1$s is file path. */
						__( 'Your PHP code changes were rolled back 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 _e( 'You need to make this file writable before you can save your changes. See <a href="https://codex.wordpress.org/Changing_File_Permissions">the Codex</a> for more information.' ); ?></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 _e( 'Dismiss' ); ?></span></button>
			<# } #>
		</div>
	</script>
	<?php
}

/**
 * Attempt 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 array $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     Plugin being edited.
 *     @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' );
	}
	$file = $args['file'];
	if ( 0 !== validate_file( $file ) ) {
		return new WP_Error( 'bad_file' );
	}

	if ( ! isset( $args['newcontent'] ) ) {
		return new WP_Error( 'missing_content' );
	}
	$content = $args['newcontent'];

	if ( ! isset( $args['nonce'] ) ) {
		return new WP_Error( 'missing_nonce' );
	}

	$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.' ) );
		}

		$real_file = $theme->get_stylesheet_directory() . '/' . $file;
		if ( ! wp_verify_nonce( $args['nonce'], 'edit-theme_' . $real_file . $stylesheet ) ) {
			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;
			}
		}

lucha's avatar
lucha committed
448
449
		// Compare based on relative paths
		if ( 0 !== validate_file( $file, array_keys( $allowed_files ) ) ) {
lucha's avatar
lucha committed
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
			return new WP_Error( 'disallowed_theme_file', __( 'Sorry, that file cannot be edited.' ) );
		}

		$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', __( 'No such file exists! 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_writeable( $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.' ) );
	}
	if ( 'php' === $extension && function_exists( 'opcache_invalidate' ) ) {
		opcache_invalidate( $real_file, true );
	}

	if ( $is_active && 'php' === $extension ) {

		$scrape_key = md5( rand() );
		$transient = 'scrape_key_' . $scrape_key;
		$scrape_nonce = strval( rand() );
		set_transient( $transient, $scrape_nonce, 60 ); // It shouldn't take more than 60 seconds to make the two loopback requests.

		$cookies = wp_unslash( $_COOKIE );
		$scrape_params = array(
			'wp_scrape_key' => $scrape_key,
			'wp_scrape_nonce' => $scrape_nonce,
		);
		$headers = array(
			'Cache-Control' => 'no-cache',
		);

		// 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.
		@set_time_limit( 300 );

		// Time to wait for loopback requests to finish.
		$timeout = 100;

		$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();
		}
		$url = add_query_arg( $scrape_params, $url );
		$r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout' ) );
		$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' ) );
			$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 );
			if ( function_exists( 'opcache_invalidate' ) ) {
				opcache_invalidate( $real_file, true );
			}

			if ( ! isset( $result['message'] ) ) {
kiki's avatar
kiki committed
592
				$message = __( 'Something went wrong.' );
lucha's avatar
lucha committed
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
			} 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;
}


godog's avatar
godog committed
609
610
611
612
613
/**
 * Returns a filename of a Temporary unique file.
 * Please note that the calling function must unlink() this itself.
 *
 * The filename is based off the passed parameter or defaults to the current unix timestamp,
lechuck's avatar
lechuck committed
614
 * while the directory can either be passed as well, or by leaving it blank, default to a writable temporary directory.
godog's avatar
godog committed
615
616
617
 *
 * @since 2.6.0
 *
lechuck's avatar
lechuck committed
618
619
 * @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.
godog's avatar
godog committed
620
621
 * @return string a writable filename
 */
ale's avatar
ale committed
622
623
function wp_tempnam( $filename = '', $dir = '' ) {
	if ( empty( $dir ) ) {
godog's avatar
godog committed
624
		$dir = get_temp_dir();
ale's avatar
ale committed
625
626
	}

lucha's avatar
lucha committed
627
	if ( empty( $filename ) || '.' == $filename || '/' == $filename || '\\' == $filename ) {
godog's avatar
godog committed
628
		$filename = time();
ale's avatar
ale committed
629
630
631
632
633
634
	}

	// 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 );

lechuck's avatar
lechuck committed
635
	// If the folder is falsey, use its parent directory name instead.
ale's avatar
ale committed
636
637
638
639
	if ( ! $temp_filename ) {
		return wp_tempnam( dirname( $filename ), $dir );
	}

lechuck's avatar
lechuck committed
640
641
	// Suffix some random data to avoid filename conflicts
	$temp_filename .= '-' . wp_generate_password( 6, false );
ale's avatar
ale committed
642
643
	$temp_filename .= '.tmp';
	$temp_filename = $dir . wp_unique_filename( $dir, $temp_filename );
lechuck's avatar
lechuck committed
644
645
646
647
648
649
650
651

	$fp = @fopen( $temp_filename, 'x' );
	if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) {
		return wp_tempnam( $filename, $dir );
	}
	if ( $fp ) {
		fclose( $fp );
	}
godog's avatar
godog committed
652

ale's avatar
ale committed
653
	return $temp_filename;
godog's avatar
godog committed
654
655
656
}

/**
lucha's avatar
lucha committed
657
 * Makes sure that the file that was requested to be edited is allowed to be edited.
root's avatar
root committed
658
 *
lucha's avatar
lucha committed
659
 * Function will die if you are not allowed to edit the file.
godog's avatar
godog committed
660
 *
root's avatar
root committed
661
 * @since 1.5.0
godog's avatar
godog committed
662
 *
lucha's avatar
lucha committed
663
664
 * @param string $file          File the user is attempting to edit.
 * @param array  $allowed_files Optional. Array of allowed files to edit, $file must match an entry exactly.
lechuck's avatar
lechuck committed
665
 * @return string|null
godog's avatar
godog committed
666
 */
lucha's avatar
lucha committed
667
function validate_file_to_edit( $file, $allowed_files = array() ) {
godog's avatar
godog committed
668
669
670
671
672
673
674
	$code = validate_file( $file, $allowed_files );

	if (!$code )
		return $file;

	switch ( $code ) {
		case 1 :
lechuck's avatar
lechuck committed
675
			wp_die( __( 'Sorry, that file cannot be edited.' ) );
godog's avatar
godog committed
676

lucha's avatar
lucha committed
677
678
		// case 2 :
		// wp_die( __('Sorry, can&#8217;t call files with their real path.' ));
godog's avatar
godog committed
679
680

		case 3 :
lechuck's avatar
lechuck committed
681
			wp_die( __( 'Sorry, that file cannot be edited.' ) );
godog's avatar
godog committed
682
683
684
685
	}
}

/**
root's avatar
root committed
686
687
 * Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type,
 * and moving the file to the appropriate directory within the uploads directory.
godog's avatar
godog committed
688
 *
lechuck's avatar
lechuck committed
689
 * @access private
lucha's avatar
lucha committed
690
 * @since 4.0.0
godog's avatar
godog committed
691
 *
lucha's avatar
lucha committed
692
693
 * @see wp_handle_upload_error
 *
ale's avatar
ale committed
694
695
696
697
 * @param array       $file      Reference to a single element of $_FILES. Call the function once for each uploaded file.
 * @param array|false $overrides An associative array of names => values to override default variables. Default false.
 * @param string      $time      Time formatted in 'yyyy/mm'.
 * @param string      $action    Expected value for $_POST['action'].
lucha's avatar
lucha committed
698
699
 * @return array On success, returns an associative array of file attributes. On failure, returns
 *               $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
lechuck's avatar
lechuck committed
700
 */
lucha's avatar
lucha committed
701
function _wp_handle_upload( &$file, $overrides, $time, $action ) {
godog's avatar
godog committed
702
703
704
	// The default error handler.
	if ( ! function_exists( 'wp_handle_upload_error' ) ) {
		function wp_handle_upload_error( &$file, $message ) {
lucha's avatar
lucha committed
705
			return array( 'error' => $message );
godog's avatar
godog committed
706
707
708
		}
	}

lechuck's avatar
lechuck committed
709
	/**
lucha's avatar
lucha committed
710
	 * Filters the data for a file before it is uploaded to WordPress.
lechuck's avatar
lechuck committed
711
	 *
lechuck's avatar
lechuck committed
712
713
714
715
	 * The dynamic portion of the hook name, `$action`, refers to the post action.
	 *
	 * @since 2.9.0 as 'wp_handle_upload_prefilter'.
	 * @since 4.0.0 Converted to a dynamic hook with `$action`.
lechuck's avatar
lechuck committed
716
717
718
	 *
	 * @param array $file An array of data for a single file.
	 */
lucha's avatar
lucha committed
719
	$file = apply_filters( "{$action}_prefilter", $file );
godog's avatar
godog committed
720
721
722

	// You may define your own function and pass the name in $overrides['upload_error_handler']
	$upload_error_handler = 'wp_handle_upload_error';
lucha's avatar
lucha committed
723
724
725
	if ( isset( $overrides['upload_error_handler'] ) ) {
		$upload_error_handler = $overrides['upload_error_handler'];
	}
godog's avatar
godog committed
726

lechuck's avatar
lechuck committed
727
	// You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
lucha's avatar
lucha committed
728
	if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) {
lucha's avatar
lucha committed
729
		return call_user_func_array( $upload_error_handler, array( &$file, $file['error'] ) );
lucha's avatar
lucha committed
730
731
732
	}

	// Install user overrides. Did we mention that this voids your warranty?
godog's avatar
godog committed
733
734
735

	// You may define your own function and pass the name in $overrides['unique_filename_callback']
	$unique_filename_callback = null;
lucha's avatar
lucha committed
736
737
738
	if ( isset( $overrides['unique_filename_callback'] ) ) {
		$unique_filename_callback = $overrides['unique_filename_callback'];
	}
godog's avatar
godog committed
739

lucha's avatar
lucha committed
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
	/*
	 * This may not have orignially been intended to be overrideable,
	 * 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,
			__( 'The uploaded file exceeds the upload_max_filesize directive in php.ini.' ),
			__( 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.' ),
			__( '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.' )
		);
	}
godog's avatar
godog committed
760

root's avatar
root committed
761
	// All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
lucha's avatar
lucha committed
762
763
	$test_form = isset( $overrides['test_form'] ) ? $overrides['test_form'] : true;
	$test_size = isset( $overrides['test_size'] ) ? $overrides['test_size'] : true;
godog's avatar
godog committed
764

lucha's avatar
lucha committed
765
766
767
	// 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'] : false;
godog's avatar
godog committed
768
769

	// A correct form post will pass this test.
lucha's avatar
lucha committed
770
	if ( $test_form && ( ! isset( $_POST['action'] ) || ( $_POST['action'] != $action ) ) ) {
lucha's avatar
lucha committed
771
		return call_user_func_array( $upload_error_handler, array( &$file, __( 'Invalid form submission.' ) ) );
lucha's avatar
lucha committed
772
	}
godog's avatar
godog committed
773
	// A successful upload will pass this test. It makes no sense to override this one.
lechuck's avatar
lechuck committed
774
	if ( isset( $file['error'] ) && $file['error'] > 0 ) {
lucha's avatar
lucha committed
775
		return call_user_func_array( $upload_error_handler, array( &$file, $upload_error_strings[ $file['error'] ] ) );
lechuck's avatar
lechuck committed
776
	}
godog's avatar
godog committed
777

lucha's avatar
lucha committed
778
	$test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] );
godog's avatar
godog committed
779
	// A non-empty file will pass this test.
lucha's avatar
lucha committed
780
781
	if ( $test_size && ! ( $test_file_size > 0 ) ) {
		if ( is_multisite() ) {
godog's avatar
godog committed
782
			$error_msg = __( 'File is empty. Please upload something more substantial.' );
lucha's avatar
lucha committed
783
		} else {
godog's avatar
godog committed
784
			$error_msg = __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.' );
lucha's avatar
lucha committed
785
		}
lucha's avatar
lucha committed
786
		return call_user_func_array( $upload_error_handler, array( &$file, $error_msg ) );
godog's avatar
godog committed
787
788
789
	}

	// A properly uploaded file will pass this test. There should be no reason to override this one.
lucha's avatar
lucha committed
790
	$test_uploaded_file = 'wp_handle_upload' === $action ? @ is_uploaded_file( $file['tmp_name'] ) : @ is_file( $file['tmp_name'] );
lechuck's avatar
lechuck committed
791
	if ( ! $test_uploaded_file ) {
lucha's avatar
lucha committed
792
		return call_user_func_array( $upload_error_handler, array( &$file, __( 'Specified file failed upload test.' ) ) );
lucha's avatar
lucha committed
793
	}
godog's avatar
godog committed
794
795
796
797

	// 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 );
lucha's avatar
lucha committed
798
799
800
		$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'];
godog's avatar
godog committed
801
802

		// Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
lucha's avatar
lucha committed
803
		if ( $proper_filename ) {
godog's avatar
godog committed
804
			$file['name'] = $proper_filename;
lucha's avatar
lucha committed
805
806
		}
		if ( ( ! $type || !$ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
lucha's avatar
lucha committed
807
			return call_user_func_array( $upload_error_handler, array( &$file, __( 'Sorry, this file type is not permitted for security reasons.' ) ) );
lucha's avatar
lucha committed
808
809
		}
		if ( ! $type ) {
godog's avatar
godog committed
810
			$type = $file['type'];
lucha's avatar
lucha committed
811
		}
godog's avatar
godog committed
812
813
814
815
	} else {
		$type = '';
	}

lucha's avatar
lucha committed
816
817
818
819
820
	/*
	 * A writable uploads dir will pass this test. Again, there's no point
	 * overriding this one.
	 */
	if ( ! ( ( $uploads = wp_upload_dir( $time ) ) && false === $uploads['error'] ) ) {
lucha's avatar
lucha committed
821
		return call_user_func_array( $upload_error_handler, array( &$file, $uploads['error'] ) );
lucha's avatar
lucha committed
822
	}
godog's avatar
godog committed
823
824
825

	$filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );

lucha's avatar
lucha committed
826
	// Move the file to the uploads dir.
root's avatar
root committed
827
	$new_file = $uploads['path'] . "/$filename";
lucha's avatar
lucha committed
828

lucha's avatar
lucha committed
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
 	/**
	 * Filters whether to short-circuit moving the uploaded file after passing all checks.
	 *
	 * If a non-null value is passed to the filter, moving the file and any related error
	 * reporting will be completely skipped.
	 *
	 * @since 4.9.0
	 *
	 * @param string $move_new_file If null (default) move the file after the upload.
	 * @param string $file          An array of data for a single file.
	 * @param string $new_file      Filename of the newly-uploaded file.
	 * @param string $type          File type.
	 */
	$move_new_file = apply_filters( 'pre_move_uploaded_file', null, $file, $new_file, $type );

	if ( null === $move_new_file ) {
		if ( 'wp_handle_upload' === $action ) {
			$move_new_file = @ move_uploaded_file( $file['tmp_name'], $new_file );
lucha's avatar
lucha committed
847
		} else {
lucha's avatar
lucha committed
848
849
850
851
852
853
854
855
856
857
858
859
			// use copy and unlink because rename breaks streams.
			$move_new_file = @ copy( $file['tmp_name'], $new_file );
			unlink( $file['tmp_name'] );
		}

		if ( false === $move_new_file ) {
			if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
				$error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
			} else {
				$error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
			}
			return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $error_path ) );
lucha's avatar
lucha committed
860
		}
lechuck's avatar
lechuck committed
861
	}
root's avatar
root committed
862

lucha's avatar
lucha committed
863
	// Set correct file permissions.
godog's avatar
godog committed
864
865
866
867
	$stat = stat( dirname( $new_file ));
	$perms = $stat['mode'] & 0000666;
	@ chmod( $new_file, $perms );

lucha's avatar
lucha committed
868
	// Compute the URL.
godog's avatar
godog committed
869
870
	$url = $uploads['url'] . "/$filename";

lucha's avatar
lucha committed
871
	if ( is_multisite() ) {
godog's avatar
godog committed
872
		delete_transient( 'dirsize_cache' );
lucha's avatar
lucha committed
873
	}
godog's avatar
godog committed
874

lechuck's avatar
lechuck committed
875
	/**
lucha's avatar
lucha committed
876
	 * Filters the data array for the uploaded file.
lechuck's avatar
lechuck committed
877
878
879
880
881
882
883
884
885
886
	 *
	 * @since 2.1.0
	 *
	 * @param array  $upload {
	 *     Array of upload data.
	 *
	 *     @type string $file Filename of the newly-uploaded file.
	 *     @type string $url  URL of the uploaded file.
	 *     @type string $type File type.
	 * }
lucha's avatar
lucha committed
887
	 * @param string $context The type of upload action. Values include 'upload' or 'sideload'.
lechuck's avatar
lechuck committed
888
	 */
lucha's avatar
lucha committed
889
890
891
892
	return apply_filters( 'wp_handle_upload', array(
		'file' => $new_file,
		'url'  => $url,
		'type' => $type
lechuck's avatar
lechuck committed
893
894
	), 'wp_handle_sideload' === $action ? 'sideload' : 'upload' );
}
godog's avatar
godog committed
895
896

/**
lucha's avatar
lucha committed
897
898
899
 * Wrapper for _wp_handle_upload().
 *
 * Passes the {@see 'wp_handle_upload'} action.
godog's avatar
godog committed
900
 *
lucha's avatar
lucha committed
901
 * @since 2.0.0
godog's avatar
godog committed
902
 *
lucha's avatar
lucha committed
903
904
 * @see _wp_handle_upload()
 *
lucha's avatar
lucha committed
905
 * @param array      $file      Reference to a single element of `$_FILES`. Call the function once for
lucha's avatar
lucha committed
906
907
908
909
910
911
 *                              each uploaded file.
 * @param array|bool $overrides Optional. An associative array of names=>values to override default
 *                              variables. Default false.
 * @param string     $time      Optional. Time formatted in 'yyyy/mm'. Default null.
 * @return array On success, returns an associative array of file attributes. On failure, returns
 *               $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
godog's avatar
godog committed
912
 */
lucha's avatar
lucha committed
913
914
915
916
917
918
919
920
function wp_handle_upload( &$file, $overrides = false, $time = null ) {
	/*
	 *  $_POST['action'] must be set and its value must equal $overrides['action']
	 *  or this:
	 */
	$action = 'wp_handle_upload';
	if ( isset( $overrides['action'] ) ) {
		$action = $overrides['action'];
godog's avatar
godog committed
921
922
	}

lucha's avatar
lucha committed
923
924
	return _wp_handle_upload( $file, $overrides, $time, $action );
}
godog's avatar
godog committed
925

lucha's avatar
lucha committed
926
/**
lucha's avatar
lucha committed
927
928
929
 * Wrapper for _wp_handle_upload().
 *
 * Passes the {@see 'wp_handle_sideload'} action.
lucha's avatar
lucha committed
930
931
932
933
934
 *
 * @since 2.6.0
 *
 * @see _wp_handle_upload()
 *
lucha's avatar
lucha committed
935
 * @param array      $file      An array similar to that of a PHP `$_FILES` POST array
lucha's avatar
lucha committed
936
937
938
939
940
941
942
943
944
945
946
 * @param array|bool $overrides Optional. An associative array of names=>values to override default
 *                              variables. Default false.
 * @param string     $time      Optional. Time formatted in 'yyyy/mm'. Default null.
 * @return array On success, returns an associative array of file attributes. On failure, returns
 *               $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
 */
function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
	/*
	 *  $_POST['action'] must be set and its value must equal $overrides['action']
	 *  or this:
	 */
godog's avatar
godog committed
947
	$action = 'wp_handle_sideload';
lucha's avatar
lucha committed
948
949
	if ( isset( $overrides['action'] ) ) {
		$action = $overrides['action'];
godog's avatar
godog committed
950
	}
lucha's avatar
lucha committed
951
	return _wp_handle_upload( $file, $overrides, $time, $action );
godog's avatar
godog committed
952
953
}

lucha's avatar
lucha committed
954

godog's avatar
godog committed
955
/**
lechuck's avatar
lechuck committed
956
 * Downloads a URL to a local temporary file using the WordPress HTTP Class.
lechuck's avatar
lechuck committed
957
 * Please note, That the calling function must unlink() the file.
godog's avatar
godog committed
958
959
960
961
 *
 * @since 2.5.0
 *
 * @param string $url the URL of the file to download
root's avatar
root committed
962
 * @param int $timeout The timeout for the request to download the file default 300 seconds
godog's avatar
godog committed
963
964
 * @return mixed WP_Error on failure, string Filename on success.
 */
root's avatar
root committed
965
function download_url( $url, $timeout = 300 ) {
godog's avatar
godog committed
966
967
968
969
	//WARNING: The file is not automatically deleted, The script must unlink() the file.
	if ( ! $url )
		return new WP_Error('http_no_url', __('Invalid URL Provided.'));

lucha's avatar
lucha committed
970
971
972
	$url_filename = basename( parse_url( $url, PHP_URL_PATH ) );

	$tmpfname = wp_tempnam( $url_filename );
godog's avatar
godog committed
973
974
975
	if ( ! $tmpfname )
		return new WP_Error('http_no_file', __('Could not create Temporary file.'));

lechuck's avatar
lechuck committed
976
	$response = wp_safe_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) );
godog's avatar
godog committed
977

shammash's avatar
shammash committed
978
979
	if ( is_wp_error( $response ) ) {
		unlink( $tmpfname );
godog's avatar
godog committed
980
981
982
		return $response;
	}

shammash's avatar
shammash committed
983
984
985
	if ( 200 != wp_remote_retrieve_response_code( $response ) ){
		unlink( $tmpfname );
		return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) );
godog's avatar
godog committed
986
987
	}

lucha's avatar
lucha committed
988
989
990
991
992
993
994
995
996
	$content_md5 = wp_remote_retrieve_header( $response, 'content-md5' );
	if ( $content_md5 ) {
		$md5_check = verify_file_md5( $tmpfname, $content_md5 );
		if ( is_wp_error( $md5_check ) ) {
			unlink( $tmpfname );
			return $md5_check;
		}
	}

godog's avatar
godog committed
997
998
999
	return $tmpfname;
}

lucha's avatar
lucha committed
1000
/**
lechuck's avatar
lechuck committed
1001
 * Calculates and compares the MD5 of a file to its expected value.
lucha's avatar
lucha committed
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
 *
 * @since 3.7.0
 *
 * @param string $filename The filename to check the MD5 of.
 * @param string $expected_md5 The expected MD5 of the file, either a base64 encoded raw md5, or a hex-encoded md5
 * @return bool|object WP_Error on failure, true on success, false when the MD5 format is unknown/unexpected
 */
function verify_file_md5( $filename, $expected_md5 ) {
	if ( 32 == strlen( $expected_md5 ) )
		$expected_raw_md5 = pack( 'H*', $expected_md5 );
	elseif ( 24 == strlen( $expected_md5 ) )
		$expected_raw_md5 = base64_decode( $expected_md5 );
	else
		return false; // unknown format

	$file_md5 = md5_file( $filename, true );

	if ( $file_md5 === $expected_raw_md5 )
		return true;

	return new WP_Error( 'md5_mismatch', sprintf( __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ), bin2hex( $file_md5 ), bin2hex( $expected_raw_md5 ) ) );
}

godog's avatar
godog committed
1025
/**
root's avatar
root committed
1026
 * Unzips a specified ZIP file to a location on the Filesystem via the WordPress Filesystem Abstraction.
godog's avatar
godog committed
1027
1028
1029
1030
1031
1032
1033
 * Assumes that WP_Filesystem() has already been called and set up. Does not extract a root-level __MACOSX directory, if present.
 *
 * Attempts to increase the PHP Memory limit to 256M before uncompressing,
 * However, The most memory required shouldn't be much larger than the Archive itself.
 *
 * @since 2.5.0
 *
lechuck's avatar
lechuck committed
1034
1035
 * @global WP_Filesystem_Base $wp_filesystem Subclass
 *
godog's avatar
godog committed
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
 * @param string $file Full path and filename of zip archive
 * @param string $to Full path on the filesystem to extract archive to
 * @return mixed WP_Error on failure, True on success
 */
function unzip_file($file, $to) {
	global $wp_filesystem;

	if ( ! $wp_filesystem || !is_object($wp_filesystem) )
		return new WP_Error('fs_unavailable', __('Could not access filesystem.'));

lucha's avatar
lucha committed
1046
1047
	// Unzip can use a lot of memory, but not this much hopefully.
	wp_raise_memory_limit( 'admin' );
godog's avatar
godog committed
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069

	$needed_dirs = array();
	$to = trailingslashit($to);

	// Determine any parent dir's needed (of the upgrade directory)
	if ( ! $wp_filesystem->is_dir($to) ) { //Only do parents if no children exist
		$path = preg_split('![/\\\]!', untrailingslashit($to));
		for ( $i = count($path); $i >= 0; $i-- ) {
			if ( empty($path[$i]) )
				continue;

			$dir = implode('/', array_slice($path, 0, $i+1) );
			if ( preg_match('!^[a-z]:$!i', $dir) ) // Skip it if it looks like a Windows Drive letter.
				continue;

			if ( ! $wp_filesystem->is_dir($dir) )
				$needed_dirs[] = $dir;
			else
				break; // A folder exists, therefor, we dont need the check the levels below this
		}
	}

lechuck's avatar
lechuck committed
1070
	/**
lucha's avatar
lucha committed
1071
	 * Filters whether to use ZipArchive to unzip archives.
lechuck's avatar
lechuck committed
1072
1073
1074
1075
1076
	 *
	 * @since 3.0.0
	 *
	 * @param bool $ziparchive Whether to use ZipArchive. Default true.
	 */
lechuck's avatar
lechuck committed
1077
	if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
godog's avatar
godog committed
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
		$result = _unzip_file_ziparchive($file, $to, $needed_dirs);
		if ( true === $result ) {
			return $result;
		} elseif ( is_wp_error($result) ) {
			if ( 'incompatible_archive' != $result->get_error_code() )
				return $result;
		}
	}
	// Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
	return _unzip_file_pclzip($file, $to, $needed_dirs);
}

/**
 * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the ZipArchive class.
 * Assumes that WP_Filesystem() has already been called and set up.
 *
 * @since 3.0.0
 * @see unzip_file
 * @access private
 *
lechuck's avatar
lechuck committed
1098
1099
 * @global WP_Filesystem_Base $wp_filesystem Subclass
 *
godog's avatar
godog committed
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
 * @param string $file Full path and filename of zip archive
 * @param string $to Full path on the filesystem to extract archive to
 * @param array $needed_dirs A partial list of required folders needed to be created.
 * @return mixed WP_Error on failure, True on success
 */
function _unzip_file_ziparchive($file, $to, $needed_dirs = array() ) {
	global $wp_filesystem;

	$z = new ZipArchive();

lucha's avatar
lucha committed
1110
	$zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS );
godog's avatar
godog committed
1111
	if ( true !== $zopen )
lucha's avatar
lucha committed
1112
1113
1114
		return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) );

	$uncompressed_size = 0;
godog's avatar
godog committed
1115
1116
1117

	for ( $i = 0; $i < $z->numFiles; $i++ ) {
		if ( ! $info = $z->statIndex($i) )
lucha's avatar
lucha committed
1118
			return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
godog's avatar
godog committed
1119
1120
1121
1122

		if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Skip the OS X-created __MACOSX directory
			continue;

lucha's avatar
lucha committed
1123
		// Don't extract invalid files:
lucha's avatar
lucha committed
1124
		if ( 0 !== validate_file( $info['name'] ) ) {
lucha's avatar
lucha committed
1125
			continue;
lucha's avatar
lucha committed
1126
1127
		}

lucha's avatar
lucha committed
1128
1129
		$uncompressed_size += $info['size'];

lucha's avatar
lucha committed
1130
1131
1132
1133
1134
1135
1136
		if ( '/' === substr( $info['name'], -1 ) ) {
			// Directory.
			$needed_dirs[] = $to . untrailingslashit( $info['name'] );
		} elseif ( '.' !== $dirname = dirname( $info['name'] ) ) {
			// Path to a file.
			$needed_dirs[] = $to . untrailingslashit( $dirname );
		}
godog's avatar
godog committed
1137
1138
	}

lucha's avatar
lucha committed
1139
1140
1141
1142
1143
	/*
	 * disk_free_space() could return false. Assume that any falsey value is an error.
	 * A disk that has zero free bytes has bigger problems.
	 * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
	 */
lucha's avatar
lucha committed
1144
	if ( wp_doing_cron() ) {
lucha's avatar
lucha committed
1145
1146
1147
1148
1149
		$available_space = @disk_free_space( WP_CONTENT_DIR );
		if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space )
			return new WP_Error( 'disk_full_unzip_file', __( 'Could not copy files. You may have run out of disk space.' ), compact( 'uncompressed_size', 'available_space' ) );
	}

godog's avatar
godog committed
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
	$needed_dirs = array_unique($needed_dirs);
	foreach ( $needed_dirs as $dir ) {
		// Check the parent folders of the folders all exist within the creation array.
		if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
			continue;
		if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
			continue;

		$parent_folder = dirname($dir);
		while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
			$needed_dirs[] = $parent_folder;
			$parent_folder = dirname($parent_folder);
		}
	}
	asort($needed_dirs);

	// Create those directories if need be:
	foreach ( $needed_dirs as $_dir ) {
ale's avatar
ale committed
1168
1169
		// Only check to see if the Dir exists upon creation failure. Less I/O this way.
		if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
lucha's avatar
lucha committed
1170
			return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
ale's avatar
ale committed
1171
		}
godog's avatar
godog committed
1172
1173
1174
1175
1176
	}
	unset($needed_dirs);

	for ( $i = 0; $i < $z->numFiles; $i++ ) {
		if ( ! $info = $z->statIndex($i) )
lucha's avatar
lucha committed
1177
			return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
godog's avatar
godog committed
1178
1179
1180
1181
1182
1183
1184

		if ( '/' == substr($info['name'], -1) ) // directory
			continue;

		if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
			continue;

lucha's avatar
lucha committed
1185
1186
1187
1188
1189
		// Don't extract invalid files:
		if ( 0 !== validate_file( $info['name'] ) ) {
			continue;
		}

godog's avatar
godog committed
1190
1191
		$contents = $z->getFromIndex($i);
		if ( false === $contents )
lucha's avatar
lucha committed
1192
			return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] );
godog's avatar
godog committed
1193
1194

		if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE) )
lucha's avatar
lucha committed
1195
			return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] );
godog's avatar
godog committed
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
	}

	$z->close();

	return true;
}

/**
 * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the PclZip library.
 * Assumes that WP_Filesystem() has already been called and set up.
 *
 * @since 3.0.0
 * @see unzip_file
 * @access private
 *
lechuck's avatar
lechuck committed
1211
1212
 * @global WP_Filesystem_Base $wp_filesystem Subclass
 *
godog's avatar
godog committed
1213
1214
1215
1216
1217
1218
1219
1220
 * @param string $file Full path and filename of zip archive
 * @param string $to Full path on the filesystem to extract archive to
 * @param array $needed_dirs A partial list of required folders needed to be created.
 * @return mixed WP_Error on failure, True on success
 */
function _unzip_file_pclzip($file, $to, $needed_dirs = array()) {
	global $wp_filesystem;

lucha's avatar
lucha committed
1221
	mbstring_binary_safe_encoding();
shammash's avatar
shammash committed
1222

godog's avatar
godog committed
1223
1224
1225
1226
	require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');

	$archive = new PclZip($file);

shammash's avatar
shammash committed
1227
1228
	$archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);

lucha's avatar
lucha committed
1229
	reset_mbstring_encoding();
shammash's avatar
shammash committed
1230

godog's avatar
godog committed
1231
	// Is the archive valid?
shammash's avatar
shammash committed
1232
	if ( !is_array($archive_files) )
godog's avatar
godog committed
1233
1234
1235
		return new WP_Error('incompatible_archive', __('Incompatible Archive.'), $archive->errorInfo(true));

	if ( 0 == count($archive_files) )
lucha's avatar
lucha committed
1236
1237
1238
		return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) );

	$uncompressed_size = 0;
godog's avatar
godog committed
1239
1240
1241
1242
1243
1244

	// Determine any children directories needed (From within the archive)
	foreach ( $archive_files as $file ) {
		if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Skip the OS X-created __MACOSX directory
			continue;

lucha's avatar
lucha committed
1245
1246
		$uncompressed_size += $file['size'];

godog's avatar
godog committed
1247
1248
1249
		$needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname($file['filename']) );
	}

lucha's avatar
lucha committed
1250
1251
1252
1253
1254
	/*
	 * disk_free_space() could return false. Assume that any falsey value is an error.
	 * A disk that has zero free bytes has bigger problems.
	 * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
	 */
lucha's avatar
lucha committed
1255
	if ( wp_doing_cron() ) {
lucha's avatar
lucha committed
1256
1257
1258
1259
1260
		$available_space = @disk_free_space( WP_CONTENT_DIR );
		if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space )
			return new WP_Error( 'disk_full_unzip_file', __( 'Could not copy files. You may have run out of disk space.' ), compact( 'uncompressed_size', 'available_space' ) );
	}

godog's avatar
godog committed
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
	$needed_dirs = array_unique($needed_dirs);
	foreach ( $needed_dirs as $dir ) {
		// Check the parent folders of the folders all exist within the creation array.
		if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
			continue;
		if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
			continue;

		$parent_folder = dirname($dir);
		while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
			$needed_dirs[] = $parent_folder;
			$parent_folder = dirname($parent_folder);
		}
	}
	asort($needed_dirs);

	// Create those directories if need be:
	foreach ( $needed_dirs as $_dir ) {
lucha's avatar
lucha committed
1279
1280
1281
		// Only check to see if the dir exists upon creation failure. Less I/O this way.
		if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) )
			return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
godog's avatar
godog committed
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
	}
	unset($needed_dirs);

	// Extract the files from the zip
	foreach ( $archive_files as $file ) {
		if ( $file['folder'] )
			continue;

		if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
			continue;

lucha's avatar
lucha committed
1293
		// Don't extract invalid files:
lucha's avatar
lucha committed
1294
		if ( 0 !== validate_file( $file['filename'] ) ) {
lucha's avatar
lucha committed
1295
			continue;
lucha's avatar
lucha committed
1296
1297
		}

godog's avatar
godog committed
1298
		if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE) )
lucha's avatar
lucha committed
1299
			return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $file['filename'] );
godog's avatar
godog committed
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
	}
	return true;
}

/**
 * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
 * Assumes that WP_Filesystem() has already been called and setup.
 *
 * @since 2.5.0
 *
lechuck's avatar
lechuck committed
1310
1311
 * @global WP_Filesystem_Base $wp_filesystem Subclass
 *
godog's avatar
godog committed
1312
1313
 * @param string $from source directory
 * @param string $to destination directory
shammash's avatar
shammash committed
1314
 * @param array $skip_list a list of files/folders to skip copying
godog's avatar
godog committed
1315
1316
 * @return mixed WP_Error on failure, True on success.
 */
shammash's avatar
shammash committed
1317
function copy_dir($from, $to, $skip_list = array() ) {
godog's avatar
godog committed
1318
1319
1320
1321
1322
1323
1324
1325
	global $wp_filesystem;

	$dirlist = $wp_filesystem->dirlist($from);

	$from = trailingslashit($from);
	$to = trailingslashit($to);

	foreach ( (array) $dirlist as $filename => $fileinfo ) {
lucha's avatar
lucha committed
1326
1327
		if ( in_array( $filename, $skip_list ) )
			continue;
shammash's avatar
shammash committed
1328

godog's avatar
godog committed
1329
		if ( 'f' == $fileinfo['type'] ) {
shammash's avatar
shammash committed
1330
			if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
godog's avatar
godog committed
1331
				// If copy failed, chmod file to 0644 and try again.
lucha's avatar
lucha committed
1332
				$wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE );
shammash's avatar
shammash committed
1333
				if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
lucha's avatar
lucha committed
1334
					return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename );
godog's avatar
godog committed
1335
1336
1337
1338
			}
		} elseif ( 'd' == $fileinfo['type'] ) {
			if ( !$wp_filesystem->is_dir($to . $filename) ) {
				if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
lucha's avatar
lucha committed
1339
					return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename );
godog's avatar
godog committed
1340
			}
lucha's avatar
lucha committed
1341
1342
1343
1344
1345
1346
1347
1348
1349

			// generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list
			$sub_skip_list = array();
			foreach ( $skip_list as $skip_item ) {
				if ( 0 === strpos( $skip_item, $filename . '/' ) )
					$sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item );
			}

			$result = copy_dir($from . $filename, $to . $filename, $sub_skip_list);
godog's avatar
godog committed
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
			if ( is_wp_error($result) )
				return $result;
		}
	}
	return true;
}

/**
 * Initialises and connects the WordPress Filesystem Abstraction classes.
 * This function will include the chosen transport and attempt connecting.
 *
lechuck's avatar
lechuck committed
1361
1362
 * Plugins may add extra transports, And force WordPress to use them by returning
 * the filename via the {@see 'filesystem_method_file'} filter.
godog's avatar
godog committed
1363
1364
1365
 *
 * @since 2.5.0
 *
lechuck's avatar
lechuck committed
1366
1367
1368
1369
1370
1371
1372
 * @global WP_Filesystem_Base $wp_filesystem Subclass
 *
 * @param array|false  $args                         Optional. Connection args, These are passed directly to
 *                                                   the `WP_Filesystem_*()` classes. Default false.
 * @param string|false $context                      Optional. Context for get_filesystem_method(). Default false.
 * @param bool         $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. Default false.
 * @return null|bool false on failure, true on success.
godog's avatar
godog committed
1373
 */
lechuck's avatar
lechuck committed
1374
function WP_Filesystem( $args = false, $context = false, $allow_relaxed_file_ownership = false ) {
godog's avatar
godog committed
1375
1376
1377
1378
	global $wp_filesystem;

	require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');

lechuck's avatar
lechuck committed
1379
	$method = get_filesystem_method( $args, $context, $allow_relaxed_file_ownership );
godog's avatar
godog committed
1380
1381
1382
1383

	if ( ! $method )
		return false;

lechuck's avatar
lechuck committed
1384
	if ( ! class_exists( "WP_Filesystem_$method" ) ) {
lechuck's avatar
lechuck committed
1385
1386

		/**
lucha's avatar
lucha committed
1387
		 * Filters the path for a specific filesystem method class file.
lechuck's avatar
lechuck committed
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
		 *
		 * @since 2.6.0
		 *
		 * @see get_filesystem_method()
		 *
		 * @param string $path   Path to the specific filesystem method class file.
		 * @param string $method The filesystem method to use.
		 */
		$abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method );

godog's avatar
godog committed
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
		if ( ! file_exists($abstraction_file) )
			return;

		require_once($abstraction_file);
	}
	$method = "WP_Filesystem_$method";

	$wp_filesystem = new $method($args);

	//Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default.
	if ( ! defined('FS_CONNECT_TIMEOUT') )
		define('FS_CONNECT_TIMEOUT', 30);
	if ( ! defined('FS_TIMEOUT') )
		define('FS_TIMEOUT', 30);

	if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
		return false;

	if ( !$wp_filesystem->connect() )
root's avatar
root committed
1417
		return false; //There was an error connecting to the server.
godog's avatar
godog committed
1418
1419
1420

	// Set the permission constants if not already set.
	if ( ! defined('FS_CHMOD_DIR') )
lucha's avatar
lucha committed
1421
		define('FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
godog's avatar
godog committed
1422
	if ( ! defined('FS_CHMOD_FILE') )
lucha's avatar
lucha committed
1423
		define('FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
godog's avatar
godog committed
1424
1425
1426
1427
1428

	return true;
}

/**
ale's avatar
ale committed
1429
1430
 * Determines which method to use for reading, writing, modifying, or deleting
 * files on the filesystem.
godog's avatar
godog committed
1431
 *
ale's avatar
ale committed
1432
1433
1434
 * The priority of the transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets
 * (Via Sockets class, or `fsockopen()`). Valid values for these are: 'direct', 'ssh2',
 * 'ftpext' or 'ftpsockets'.
lechuck's avatar
lechuck committed
1435
 *
ale's avatar
ale committed
1436
1437
 * The return value can be overridden by defining the `FS_METHOD` constant in `wp-config.php`,
 * or filtering via {@see 'filesystem_method'}.
lechuck's avatar
lechuck committed
1438
 *
ale's avatar
ale committed
1439
 * @link https://codex.wordpress.org/Editing_wp-config.php#WordPress_Upgrade_Constants
lechuck's avatar
lechuck committed
1440
 *
ale's avatar
ale committed
1441
 * Plugins may define a custom transport handler, See WP_Filesystem().
godog's avatar
godog committed
1442
1443
1444
 *
 * @since 2.5.0
 *
lechuck's avatar
lechuck committed
1445
 * @global callable $_wp_filesystem_direct_method
lechuck's avatar
lechuck committed
1446
 *
ale's avatar
ale committed
1447
1448
 * @param array  $args                         Optional. Connection details. Default empty array.
 * @param string $context                      Optional. Full path to the directory that is tested
lucha's avatar
lucha committed
1449
 *                                             for being writable. Default empty.
ale's avatar
ale committed
1450
1451
 * @param bool   $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
 *                                             Default false.
godog's avatar
godog committed
1452
1453
 * @return string The transport to use, see description for valid return values.
 */
lucha's avatar
lucha committed
1454
function get_filesystem_method( $args = array(), $context = '', $allow_relaxed_file_ownership = false ) {
lechuck's avatar
lechuck committed
1455
	$method = defined('FS_METHOD') ? FS_METHOD : false; // Please ensure that this is either 'direct', 'ssh2', 'ftpext' or 'ftpsockets'
godog's avatar
godog committed
1456

lechuck's avatar
lechuck committed
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
	if ( ! $context ) {
		$context = WP_CONTENT_DIR;
	}

	// If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it.
	if ( WP_LANG_DIR == $context && ! is_dir( $context ) ) {
		$context = dirname( $context );
	}

	$context = trailingslashit( $context );
lucha's avatar
lucha committed
1467

lechuck's avatar
lechuck committed
1468
	if ( ! $method ) {
lucha's avatar
lucha committed
1469

godog's avatar
godog committed
1470
1471
1472
		$temp_file_name = $context . 'temp-write-test-' . time();
		$temp_handle = @fopen($temp_file_name, 'w');
		if ( $temp_handle ) {
lechuck's avatar
lechuck committed
1473
1474
1475
1476