<?php
/**
 * Module Name: Settings Pages Protect
 * Description: Ask the user's password to enter the secupress settings pages (needs page-protect).
 * Main Module: sensitive_data
 * Author: SecuPress
 * Version: 1.1
 */

defined( 'SECUPRESS_VERSION' ) or die( 'Cheatin&#8217; uh?' );


add_action( 'admin_init', 'secupress_shortcut_settings_hooks' );
/**
 * Will lock secupress pages.
 *
 * @since 1.0
 * @author Julio Potier
 */
function secupress_shortcut_settings_hooks() {
	if ( isset( $_GET['page'], $_GET['module'] ) && SECUPRESS_PLUGIN_SLUG . '_modules' === $_GET['page'] && 'services' === $_GET['module'] ) {
		// Don't block access to the support page.
		return;
	}

	$hooks = array(
		'toplevel_page'  => array( SECUPRESS_PLUGIN_SLUG . '_scanners' ),
		'secupress_page' => array( SECUPRESS_PLUGIN_SLUG . '_settings', SECUPRESS_PLUGIN_SLUG . '_modules', SECUPRESS_PLUGIN_SLUG . '_logs' ),
	);

	foreach ( $hooks as $page => $subs ) {
		foreach ( $subs as $sub ) {
			add_action( "load-{$page}_{$sub}", 'secupress_shortcut_settings', 0 );
		}
	}
}


add_action( 'current_screen', 'secupress_settings_page_protect_deny_access' );
/**
 * Deny access to SecuPress settings pages.
 *
 * @since 1.2.3
 * @author Julio Potier
 *
 * @param (object) $current_screen Current WP_Screen object.
 */
function secupress_settings_page_protect_deny_access( $current_screen ) {
	global $pagenow;

	if ( 'options.php' !== $pagenow || 'POST' !== $_SERVER['REQUEST_METHOD'] || empty( $_POST ) || ! isset( $_POST['_wp_http_referer'], $_POST['option_page'] ) ) { // WPCS: CSRF ok.
		return;
	}

	$parsed_url = wp_parse_url( wp_get_referer() );

	if ( empty( $parsed_url['query'] ) ) {
		return;
	}

	wp_parse_str( $parsed_url['query'], $query );

	if ( isset( $query['page'], $query['module'], $_POST['_wpnonce'] ) && SECUPRESS_PLUGIN_SLUG . '_modules' === $query['page'] && 'services' === $query['module'] && wp_verify_nonce( $_POST['_wpnonce'], 'secupress_services_settings-options' ) ) { // WPCS: CSRF ok.
		// Don't block the support page process.
		return;
	}

	$hooks = array(
		SECUPRESS_PLUGIN_SLUG . '_scanners' => 1,
		SECUPRESS_PLUGIN_SLUG . '_settings' => 1,
		SECUPRESS_PLUGIN_SLUG . '_modules'  => 1,
		SECUPRESS_PLUGIN_SLUG . '_logs'     => 1,
	);

	if ( isset( $query['page'] ) && ! empty( $hooks[ $query['page'] ] ) && false === get_site_transient( 'secupress_check_password_' . get_current_user_id() ) ) {
		wp_safe_redirect( wp_get_referer() );
		die();
	}
}
