<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

trait WPMR_Session_Mgt {


	function destroy_sessions( $id = false ) {
		$users = $this->get_users_loggedin();
		if ( ! $id ) {
			return;
		}
		foreach ( $users as $user ) {
			$sessions = WP_Session_Tokens::get_instance( $user->ID );
			if ( $user->ID != $id ) {
				$sessions->destroy_all();
			} else {
				$sessions->destroy_others( wp_get_session_token() );
			}
		}
		// wp_send_json_success();
	}

	function ajax_shuffle_salts() {
		WP_Filesystem();
		global $wp_filesystem;
		$config_path = $this->get_wp_config_path();
		if ( ! $config_path ) {
			return 'Failed to get location of wp-config.php';
		}
		$is_writable = $wp_filesystem->is_writable( $config_path );
		if ( ! $is_writable ) {
			return 'wp-config.php is not writable.';
		}
		$config  = $wp_filesystem->get_contents( $config_path );
		$defines = array(
			'AUTH_KEY',
			'SECURE_AUTH_KEY',
			'LOGGED_IN_KEY',
			'NONCE_KEY',
			'AUTH_SALT',
			'SECURE_AUTH_SALT',
			'LOGGED_IN_SALT',
			'NONCE_SALT',
		);
		foreach ( $defines as $define ) {
			if ( empty( $salts ) ) {
				$salts = $this->generate_salt();
			}
			$salt = array_pop( $salts );
			if ( empty( $salt ) ) {
				$salt = wp_generate_password( 64, true, true );
			}
			$salt   = str_replace( '$', '\\$', $salt );
			$regex  = "/(define\s*\(\s*(['\"])$define\\2\s*,\s*)(['\"]).+?\\3(\s*\)\s*;)/";
			$config = preg_replace( $regex, "\${1}'$salt'\${4}", $config );
		}
		if ( $wp_filesystem->put_contents( $config_path, $config ) ) {
			return '<p>Successfully shuffled WordPress salts. You\'ll need to login again to continue.</p>';
		} else {
			return '<p>Failed to write to wp-config.php.</p>';
		}
		return '<p>Failed to get wp-config.php location or it is not writable.</p>';
	}

}
