<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

/* セクションID haumenu_define_section_id_04_security() */
/* タブのスラグ haumenu_define_tab_slug_04_security() */
/* $option_name 設定名 haumenu_define_option_name_04_security() */
/* get_option GetOP04_security() */

/***** 親設定の有効／無効に合わせて子設定の表示方法を変更する *****/
/* 関数名・設定名は画面ごとに変えること（関数重複を防ぐ） */
/* add_action('admin_notices', 'current_pagehook');を追加してページ名を取得し、$page_fooksuffixの値を変える */
/* 連動マップ（ID => セレクター）の項目を編集する */

function haup_child_setting_view_control_04_security( $hook_suffix ) {
	//ページフックにより出力を判断
	$page_fooksuffix = 'ha-utilitiy_page_haumenu_page_security'; //セキュリティとスパム対策設定

	if ( $page_fooksuffix !== $hook_suffix ) {
		return;
	}

	//メインスクリプトのハンドル
	$handle = 'haup-child-setting-control-js';

	// メインスクリプトが登録されていなければ終了(スクリプトの読み込みはmain-menu.phpで記述)
	if ( ! wp_script_is( $handle, 'registered' ) ) {
		return;
	}

	//設定名
	$set_name = haumenu_define_option_name_04_security();

	// 連動マップ（ID => セレクター）
	// 1つのIDに対して複数のCSSクラスを指定する（1つなら1行）
	$dependency_map = array(
		//$set_name . 'enable-set-revisions' => array(
			//'.set-revisions-num-wrapper', // リビジョン数
			//'.set-revisions-posttype-wrapper', // 指定する投稿タイプ
		//),

	);

	$inner_js = "";
	foreach ( $dependency_map as $id => $selectors ) {
		foreach ( (array) $selectors as $selector ) {
			// translators: %s stands for the CSS Class & ID.
			$inner_js .= sprintf(
				"haup_apply_dependency('%s', '%s');\n",
				esc_js( $id ),
				esc_js( $selector )
			);
		}
	}


	if ( $inner_js ) {
		$js_code = "if (window.haup_apply_dependency) {\n" . $inner_js . "}";
		// 第3引数を 'after' にすることで、本体JSの直後に出力
		wp_add_inline_script( $handle, $js_code, 'after' );
	}
}
add_action( 'admin_enqueue_scripts', 'haup_child_setting_view_control_04_security', 20 );

/***** 常時SSL通信セクション *****/
/*** 301リダイレクト設定 ***/
/* 項目の追加とデータの更新 */
function haumenu_init_field_ssl_redirects(){
//項目の追加
	add_settings_field(
		'ssl-redirects', // 設定名
		__('301 redirect all content','hima-art-utility'), // 設定タイトル
		'haumenu_ssl_redirects', // 設定項目のHTMLを出力する関数名
		haumenu_define_tab_slug_04_security(), //表示させるタブのスラグ
		haumenu_define_section_id_04_security(), //セクションID
		array( 'class' => 'ha-settings-separate' )
	);

}
add_action( 'admin_init', 'haumenu_init_field_ssl_redirects' );

/* 入力フォーム */
function haumenu_ssl_redirects() {
	$set_name = haumenu_define_option_name_04_security(); //  $option_name 設定名
	$options = get_option($set_name);
	$option_name = 'ssl-redirects'; //個別配列名

	//テーブルに値がなかった場合の措置（PHP8.x以降への対応）
	if(isset($options[$option_name])){
		$checked = $options[$option_name];
	}else{
		$checked = '';
	}

	//機能が使えるかどうかの判定
	$htaccess_file = ABSPATH . '.htaccess';
	$is_writable = ( file_exists( $htaccess_file ) && is_writable( $htaccess_file ) );
	if ( $is_writable ) {
		$enabled_message_text = __('This feature is available on this site.','hima-art-utility');
		$enabled_message = '<p style="color:green;font-weight:700;">'.$enabled_message_text.'</p>';
	} else {
		$enabled_message_text = __('You are either using a server where the .htaccess file does not exist, or you do not have write permissions to the .htaccess file, so you cannot use this feature.','hima-art-utility');
		$enabled_message = '<p style="color:red;font-weight:700;">'.$enabled_message_text.'</p>';
	}

	//機能が使えない場合には選択できないようにする
	$disabled_attr = ! $is_writable ? 'disabled' : '';
?>
<label>
	<input type="checkbox" id="<?php echo esc_html($set_name . $option_name ); ?>" name="<?php echo esc_html($set_name . '[' .$option_name. ']'); ?>" class="wppd-ui-toggle" <?php checked( $checked , 1 ); ?> value="1" <?php echo esc_html($disabled_attr ); ?>>
	<?php echo wp_kses_post( $enabled_message ); ?>
	<p><?php esc_html_e('When all posts and fixed pages are accessed with non-SSL (http://~) protocol, it will be transferred as access with SSL (https://~) protocol.','hima-art-utility'); ?></p>
</label>
<p class="haup-admin-bk">
	<span class="haup-admin-font-red">
		<?php esc_html_e('Please enable it after confirming that you can access both the management screen and the browsing screen with SSL (https://~).','hima-art-utility'); ?>
	</span>
<br>
	<span>
		<?php esc_html_e('After enabling this setting, open "Settings" → "Permalinks" on the management screen and click "Save changes" without doing anything.','hima-art-utility'); ?>
	</span>
</p>
<details class="accordion"  style="margin: 5px 0px 0px 0px;overflow: hidden;">
<summary class="accordion__title" style="cursor: pointer;"><?php esc_html_e('View detailed description','hima-art-utility'); ?></summary>
<div class="accordion__content">
<ul>
<li><?php esc_html_e('In many rental servers, a free SSL certificate is applied at the same time as the domain is acquired, and SSL communication is often possible (accessible with https://) when WordPress is automatically installed.','hima-art-utility'); ?></li>
<li><?php esc_html_e('However, this means that SSL communication is possible, and it does not mean that access from everyone can be forced to SSL communication.','hima-art-utility'); ?></li>
<li><?php esc_html_e('As a test, please change the page other than the top page of your site (individual posts and fixed pages) to "https://~" on purpose and access it.','hima-art-utility'); ?></li>
<li><?php esc_html_e('If it can be displayed as "https://~" as it is, you can enable SSL communication for all accesses by enabling the measures of this function, and create a safer environment. can.','hima-art-utility'); ?></li>
</ul>
</div>
</details>
<?php
}

/*** HSTSの設定 ***/
/* 項目の追加とデータの更新 */
function haumenu_init_field_use_security_header(){
//項目の追加
	add_settings_field(
		'use-security-header', // 設定名
		__('Adding security headers','hima-art-utility'), // 設定タイトル
		'haumenu_use_security_header', // 設定項目のHTMLを出力する関数名
		haumenu_define_tab_slug_04_security(), //表示させるタブのスラグ
		haumenu_define_section_id_04_security(), //セクションID
		array( 'class' => 'ha-settings-separate' )
	);

}
add_action( 'admin_init', 'haumenu_init_field_use_security_header' );

/* 入力フォーム */
function haumenu_use_security_header() {
	$set_name = haumenu_define_option_name_04_security(); //  $option_name 設定名
	$options = get_option($set_name);
	$option_name = 'use-security-header'; //個別配列名

	//テーブルに値がなかった場合の措置（PHP8.x以降への対応）
	if(isset($options[$option_name])){
		$checked = $options[$option_name];
	}else{
		$checked = '';
	}

?>
<label>
	<input type="checkbox" id="<?php echo esc_html($set_name . $option_name ); ?>" name="<?php echo esc_html($set_name . '[' .$option_name. ']'); ?>" class="wppd-ui-toggle" <?php checked( $checked , 1 ); ?> value="1">
	<?php echo wp_kses_post( $enabled_message ); ?>
	<p><?php esc_html_e('Set security headers to prevent interception of entered data.','hima-art-utility'); ?></p>
</label>
<details class="accordion"  style="margin: 5px 0px 0px 0px;overflow: hidden;">
<summary class="accordion__title" style="cursor: pointer;"><?php esc_html_e('View detailed description','hima-art-utility'); ?></summary>
<div class="accordion__content">
<ul>
<li><?php esc_html_e('By enabling "301 redirect for all content" in the previous section, all non-SSL communication will be converted to SSL communication, and you will be able to operate the site safely with a high probability.','hima-art-utility'); ?></li>
<li><?php esc_html_e('However, malicious individuals still manage to obtain information illegally.','hima-art-utility'); ?></li>
<li><?php esc_html_e('The simple purpose of HSTS is to prevent this fraudulent act from leaking information from the browser by changing the settings of the browser used by the visitor only when browsing your site.','hima-art-utility'); ?></li>
<li><?php esc_html_e('This function adds the following directives to the header to improve the security of data transmission and reception.','hima-art-utility'); ?></li>
	<ul style="list-style: inside; padding-left:2em;">
		<li>X-Frame-Options 'SAMEORIGIN'</li>
		<li>X-Content-Type-Options 'nosniff'</li>
		<li>X-XSS-Protection '1;mode=block'</li>
		<li>Referrer-Policy 'no-referrer-when-downgrade'</li>
		<li>Content-Security-Policy "frame-ancestors 'self'"</li>
		<li>Strict-Transport-Security 'max-age=31536000;includeSubDomains; preload'</li>
		<li>Cross-Origin-Resource-Policy 'same-origin'</li>
		<li>Cross-Origin-Opener-Policy 'same-origin-allow-popups'</li>
		<li>Cross-Origin-Embedder-Policy 'unsafe-none'</li>
		<li>Permissions-Policy 'geolocation=(), midi=(),sync-xhr=(),accelerometer=(), gyroscope=(), magnetometer=(), payment=(), camera=(), microphone=(),usb=(),fullscreen=(self)'</li>
	</ul>
	
	
<li style="color:red; font-weight:bold;"><?php esc_html_e('However, there is one important caveat. That is, once the settings are saved in the browser of the person who accessed it, the settings will not be rewritten for a certain number of days.','hima-art-utility'); ?></li>
<li style="color:red; font-weight:bold;"><?php esc_html_e('If you enable it by mistake, all access from that person will be denied, and there is a possibility that you will not be able to browse.','hima-art-utility'); ?></li>
<li style="color:red; font-weight:bold;"><?php esc_html_e('Also, there may be cases where some functions of WordPress cannot be used effectively, so please consider carefully whether to enable them.','hima-art-utility'); ?></li>
</ul>
</div>
</details>
<?php echo wp_kses_post(haup_usage_info_security_header()); ?>
<div style="text-align:right;margin-top:1rem;"><a href="<?php echo esc_url(HAUP_MANUAL_DIR); ?>/howtouse-security-header" target="_blank"><?php echo esc_html(haup_manual_text()); ?></a></div>
<?php
}