| 1 |
<?php |
| 2 |
/** |
| 3 |
* File related helper utilities. |
| 4 |
* |
| 5 |
* @package WP_Defender\Helper |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Helper; |
| 9 |
|
| 10 |
use WP_Error; |
| 11 |
|
| 12 |
/** |
| 13 |
* Handles file related tasks. |
| 14 |
*/ |
| 15 |
class File { |
| 16 |
|
| 17 |
/** |
| 18 |
* Check is two files identical. |
| 19 |
* |
| 20 |
* @param string $local_file File path of the local file for content comparison. |
| 21 |
* @param string $remote_file Url of the remote file for content comparison. |
| 22 |
* |
| 23 |
* @return bool|string|WP_Error If remote fetch fails return WP_Error object or |
| 24 |
* true for identical file content or false for non-identical file content. |
| 25 |
*/ |
| 26 |
public function is_identical_content( string $local_file, string $remote_file ) { |
| 27 |
wp_raise_memory_limit(); |
| 28 |
|
| 29 |
$local_file_content = file( $local_file, FILE_IGNORE_NEW_LINES ); |
| 30 |
|
| 31 |
$tmp = download_url( $remote_file ); |
| 32 |
|
| 33 |
if ( is_wp_error( $tmp ) ) { |
| 34 |
return $tmp; |
| 35 |
} |
| 36 |
|
| 37 |
$remote_file_content = file( $tmp, FILE_IGNORE_NEW_LINES ); |
| 38 |
|
| 39 |
wp_delete_file( $tmp ); |
| 40 |
|
| 41 |
return $local_file_content === $remote_file_content; |
| 42 |
} |
| 43 |
|
| 44 |
/** |
| 45 |
* Deny access for the provided directory. |
| 46 |
* |
| 47 |
* @param string $directory File path to the directory. |
| 48 |
* |
| 49 |
* @since 4.2.0 |
| 50 |
*/ |
| 51 |
public function maybe_dir_access_deny( string $directory ) { |
| 52 |
global $wp_filesystem; |
| 53 |
// Initialize the WP filesystem, no more using 'file-put-contents' function. |
| 54 |
if ( empty( $wp_filesystem ) ) { |
| 55 |
require_once ABSPATH . '/wp-admin/includes/file.php'; |
| 56 |
WP_Filesystem(); |
| 57 |
} |
| 58 |
$files = array( |
| 59 |
array( |
| 60 |
'base' => $directory, |
| 61 |
'file' => '.htaccess', |
| 62 |
'content' => 'deny from all', |
| 63 |
), |
| 64 |
array( |
| 65 |
'base' => $directory, |
| 66 |
'file' => 'index.html', |
| 67 |
'content' => '', |
| 68 |
), |
| 69 |
); |
| 70 |
|
| 71 |
foreach ( $files as $file ) { |
| 72 |
$file_path = trailingslashit( $file['base'] ) . $file['file']; |
| 73 |
if ( ! is_null( $file_path ) && ! file_exists( $file_path ) ) { |
| 74 |
$wp_filesystem->put_contents( $file_path, $file['content'] ); |
| 75 |
} |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
|