File: /var/www/html/wp-content/plugins/backup-guard-security-platinum/com/lib/LimitLoginAttempts.php
<?php
namespace BackupGuard\Security;
class LimitLoginAttempts
{
private $failedLoginLimit = BGS_DEFAULT_FAILED_LOGIN_LIMIT;
private $lockoutDuration = 1800;
private $transientName = 'attempted_login';
public function __construct()
{
$this->failedLoginLimit = Config::get("BGS_FAILED_LOGIN_LIMIT")?Config::get("BGS_FAILED_LOGIN_LIMIT"):BGS_DEFAULT_FAILED_LOGIN_LIMIT;
add_filter('authenticate', array($this, 'check_attempted_login'), 30, 3);
add_action('wp_login_failed', array($this, 'login_failed'), 10, 1);
}
public function check_attempted_login($user, $username, $password)
{
$ip = $this->getIPaddress();
$ipHash = md5($ip);
if ($user instanceof \WP_Error) {
if (get_transient($this->transientName.'_'.$ipHash)) {
$datas = get_transient($this->transientName.'_'.$ipHash);
if ($datas['tried'] >= $this->failedLoginLimit) {
$until = get_option('_transient_timeout_'.$this->transientName.'_'.$ipHash);
$time = $this->when($until);
return new \WP_Error('too_many_tried', sprintf(__('<strong>Error</strong>: Too many failed login attempts. Please try after %1$s.'), $time));
}
else {
$remain = $this->failedLoginLimit - $datas['tried'];
return new \WP_Error('number_of_attamts', sprintf(__('<strong>Error</strong>: %1$s attempts remain'), $remain));
}
}
}
else if ($user instanceof \WP_User) {
delete_transient($this->transientName.'_'.$ipHash);
}
return $user;
}
public function login_failed($username)
{
$ip = $this->getIPaddress();
$ipHash = md5($ip);
if (get_transient($this->transientName.'_'.$ipHash)) {
$datas = get_transient($this->transientName.'_'.$ipHash);
$datas['tried']++;
if ($datas['tried'] <= $this->failedLoginLimit) {
set_transient($this->transientName.'_'.$ipHash, $datas, $this->lockoutDuration);
}
}
else {
$datas = array(
'tried' => 1
);
set_transient($this->transientName.'_'.$ipHash, $datas, $this->lockoutDuration);
}
}
private function when($time)
{
if (!$time) {
return;
}
$right_now = time();
$diff = abs($right_now - $time);
$second = 1;
$minute = $second * 60;
$hour = $minute * 60;
$day = $hour * 24;
if ($diff < $minute) {
return floor($diff / $second).' seconds';
}
if ($diff < $minute * 2) {
return "1 minute";
}
if ($diff < $hour) {
return floor($diff / $minute).' minutes';
}
if ($diff < $hour * 2) {
return '1 hour';
}
return floor($diff / $hour).' hours';
}
private function getIPaddress()
{
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
else if (!empty($_SERVER['HTTP_X_SUCURI_CLIENTIP']) && filter_var($_SERVER['HTTP_X_SUCURI_CLIENTIP'], FILTER_VALIDATE_IP)) {
$ip = $_SERVER['HTTP_X_SUCURI_CLIENTIP'];
}
else if (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
else {
$ip = '';
}
$ip = preg_replace('/^(\d+\.\d+\.\d+\.\d+):\d+$/', '\1', $ip);
return $ip;
}
}