| 1 |
<?php |
| 2 |
// Exit if accessed directly. |
| 3 |
if ( ! defined( 'ABSPATH' ) ) { |
| 4 |
exit; |
| 5 |
} |
| 6 |
|
| 7 |
/** |
| 8 |
* Disable Directory Indexing Based on Plugin Setting. |
| 9 |
* |
| 10 |
* This function checks the 'ns_shield_directory_indexing' option. If directory indexing |
| 11 |
* is disabled, it prepends the "Options -Indexes" directive to the .htaccess file to prevent |
| 12 |
* directory listing. If the option is disabled, it removes the directive. |
| 13 |
* |
| 14 |
* The function uses the WP_Filesystem API to safely read and write to the .htaccess file. |
| 15 |
* |
| 16 |
* @return void |
| 17 |
*/ |
| 18 |
function ns_shield_disable_directory_indexing() { |
| 19 |
global $wp_filesystem; |
| 20 |
|
| 21 |
// Initialize the WordPress filesystem if it is not already set up. |
| 22 |
if ( empty( $wp_filesystem ) ) { |
| 23 |
require_once ABSPATH . 'wp-admin/includes/file.php'; |
| 24 |
WP_Filesystem(); |
| 25 |
} |
| 26 |
|
| 27 |
// Retrieve the option setting for directory indexing (default: false). |
| 28 |
$is_directory_indexing_disabled = get_option( 'ns_shield_directory_indexing', false ); |
| 29 |
|
| 30 |
// Define the path to the .htaccess file and the directive to disable directory indexing. |
| 31 |
$htaccess_file = ABSPATH . '.htaccess'; |
| 32 |
$htaccess_code = "Options -Indexes\n"; |
| 33 |
|
| 34 |
if ( $is_directory_indexing_disabled ) { |
| 35 |
// If directory indexing should be disabled, add the directive if it's not present. |
| 36 |
if ( $wp_filesystem->exists( $htaccess_file ) && $wp_filesystem->is_writable( $htaccess_file ) ) { |
| 37 |
$htaccess_content = $wp_filesystem->get_contents( $htaccess_file ); |
| 38 |
if ( strpos( $htaccess_content, 'Options -Indexes' ) === false ) { |
| 39 |
$wp_filesystem->put_contents( $htaccess_file, $htaccess_code . $htaccess_content, FS_CHMOD_FILE ); |
| 40 |
} |
| 41 |
} else { |
| 42 |
// Log error if .htaccess is missing or not writable. |
| 43 |
if ( function_exists( 'ns_shield_debug_log' ) ) { |
| 44 |
ns_shield_debug_log( 'The .htaccess file does not exist or is not writable.' ); |
| 45 |
} |
| 46 |
} |
| 47 |
} else { |
| 48 |
// If directory indexing is enabled, remove the "Options -Indexes" directive. |
| 49 |
if ( $wp_filesystem->exists( $htaccess_file ) && $wp_filesystem->is_writable( $htaccess_file ) ) { |
| 50 |
$htaccess_content = $wp_filesystem->get_contents( $htaccess_file ); |
| 51 |
$updated_content = str_replace( "Options -Indexes\n", '', $htaccess_content ); |
| 52 |
$wp_filesystem->put_contents( $htaccess_file, $updated_content, FS_CHMOD_FILE ); |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
add_action( 'init', 'ns_shield_disable_directory_indexing' ); |
| 57 |
|