| 1 |
<?php |
| 2 |
if (!defined('ABSPATH')) exit; |
| 3 |
if (!class_exists('WPRWP2FAEmailOTPTemplate')) : |
| 4 |
class WPRWP2FAEmailOTPTemplate { |
| 5 |
const OTP_PLACEHOLDER = '{{otp}}'; |
| 6 |
const DURATION_PLACEHOLDER = '{{duration}}'; |
| 7 |
|
| 8 |
private $code; |
| 9 |
private $site_name; |
| 10 |
private $duration; |
| 11 |
|
| 12 |
public function __construct($code, $lifetime) { |
| 13 |
$this->code = $code; |
| 14 |
$this->site_name = $this->siteName(); |
| 15 |
$this->duration = $this->duration($lifetime); |
| 16 |
} |
| 17 |
|
| 18 |
public function subject() { |
| 19 |
return sprintf('Your sign-in code for %s', $this->site_name); |
| 20 |
} |
| 21 |
|
| 22 |
public function body() { |
| 23 |
$custom_body = $this->customBody(); |
| 24 |
|
| 25 |
return $custom_body !== null ? $custom_body : $this->defaultBody(); |
| 26 |
} |
| 27 |
|
| 28 |
public function headers() { |
| 29 |
return array('Content-Type: text/plain; charset=UTF-8'); |
| 30 |
} |
| 31 |
|
| 32 |
private function defaultBody() { |
| 33 |
return sprintf("Your sign-in code is %s.\n\nSite: %s (%s)\nThis code expires in %s.\n\nIf you did not request this code, you can ignore this email and review your account security.", $this->code, $this->site_name, home_url('/'), $this->duration); |
| 34 |
} |
| 35 |
|
| 36 |
private function customBody() { |
| 37 |
$payload = $this->getPayload(); |
| 38 |
if (!is_array($payload) || !isset($payload['body_b64']) || !is_string($payload['body_b64'])) { |
| 39 |
return null; |
| 40 |
} |
| 41 |
|
| 42 |
$body = base64_decode($payload['body_b64'], true); |
| 43 |
if ($body === false) { |
| 44 |
return null; |
| 45 |
} |
| 46 |
|
| 47 |
$body = wp_strip_all_tags($body); |
| 48 |
if (strpos($body, self::OTP_PLACEHOLDER) === false || strpos($body, self::DURATION_PLACEHOLDER) === false) { |
| 49 |
return null; |
| 50 |
} |
| 51 |
|
| 52 |
return str_replace(array(self::OTP_PLACEHOLDER, self::DURATION_PLACEHOLDER), array($this->code, $this->duration), $body); |
| 53 |
} |
| 54 |
|
| 55 |
private function getPayload() { |
| 56 |
$settings = new WPRWPSettings(); |
| 57 |
$site_settings = $settings->getOption('bv_site_settings'); |
| 58 |
|
| 59 |
return is_array($site_settings) && isset($site_settings['wp_email_otp_template']) ? $site_settings['wp_email_otp_template'] : null; |
| 60 |
} |
| 61 |
|
| 62 |
private function siteName() { |
| 63 |
$site_name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES); |
| 64 |
|
| 65 |
return trim(preg_replace('/[\x00-\x1F\x7F]/', ' ', $site_name)); |
| 66 |
} |
| 67 |
|
| 68 |
private function duration($lifetime) { |
| 69 |
$minutes = max(1, intval(round($lifetime / MINUTE_IN_SECONDS))); |
| 70 |
|
| 71 |
return sprintf('%d %s', $minutes, $minutes === 1 ? 'minute' : 'minutes'); |
| 72 |
} |
| 73 |
} |
| 74 |
endif; |
| 75 |
|