| 1 |
<?php |
| 2 |
/** |
| 3 |
* Responsible for handling ALTCHA. |
| 4 |
* |
| 5 |
* @package WP_Defender\Component |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace WP_Defender\Component; |
| 9 |
|
| 10 |
use AltchaOrg\Altcha\ChallengeOptions; |
| 11 |
use AltchaOrg\Altcha\Altcha; |
| 12 |
|
| 13 |
/** |
| 14 |
* Provides methods for creating and verifying Altcha's challenge. |
| 15 |
*/ |
| 16 |
class Altcha_Handler { |
| 17 |
|
| 18 |
/** |
| 19 |
* The log file name. |
| 20 |
*/ |
| 21 |
public const LOG_FILE_NAME = 'altcha.log'; |
| 22 |
|
| 23 |
/** |
| 24 |
* The HMAC key used for generating and verifying challenges. |
| 25 |
* |
| 26 |
* @var string |
| 27 |
*/ |
| 28 |
private $hmac_key; |
| 29 |
|
| 30 |
/** |
| 31 |
* The option name for the HMAC key. |
| 32 |
*/ |
| 33 |
public const HMAC_KEY_OPTION_NAME = 'wpdef_hmac_key'; |
| 34 |
|
| 35 |
/** |
| 36 |
* Constructor for Altcha_Handler class. |
| 37 |
*/ |
| 38 |
public function __construct() { |
| 39 |
$this->hmac_key = $this->get_hmac_key(); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Generate or retrieve the HMAC key from the WordPress options. |
| 44 |
* |
| 45 |
* @return string The HMAC key. |
| 46 |
*/ |
| 47 |
private function get_hmac_key() { |
| 48 |
$hmac_key = get_option( self::HMAC_KEY_OPTION_NAME ); |
| 49 |
|
| 50 |
if ( ! $hmac_key ) { |
| 51 |
// Generate a random key if it doesn't exist. |
| 52 |
$hmac_key = wp_generate_password( 64, true, true ); |
| 53 |
|
| 54 |
update_option( self::HMAC_KEY_OPTION_NAME, $hmac_key ); |
| 55 |
} |
| 56 |
|
| 57 |
return $hmac_key; |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Create a new ALTCHA challenge. |
| 62 |
* |
| 63 |
* @param int $max_number Maximum random number for the challenge. |
| 64 |
* |
| 65 |
* @return array Challenge data. |
| 66 |
*/ |
| 67 |
public function create_challenge( $max_number = 100000 ) { |
| 68 |
$options = new ChallengeOptions( |
| 69 |
array( |
| 70 |
'hmacKey' => $this->hmac_key, |
| 71 |
'maxNumber' => $max_number, |
| 72 |
) |
| 73 |
); |
| 74 |
|
| 75 |
return Altcha::createChallenge( $options ); |
| 76 |
} |
| 77 |
|
| 78 |
/** |
| 79 |
* Verify the given solution against the challenge. |
| 80 |
* |
| 81 |
* @param array $payload Payload containing the solution details. |
| 82 |
* @param bool $strict_mode Enable or disable strict verification. |
| 83 |
* |
| 84 |
* @return bool Verification result. |
| 85 |
*/ |
| 86 |
public function verify_solution( array $payload, $strict_mode = true ) { |
| 87 |
return Altcha::verifySolution( $payload, $this->hmac_key, $strict_mode ); |
| 88 |
} |
| 89 |
} |
| 90 |
|