: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated in
require_once(dirname(__FILE__) . '/wfDB.php');
require_once(dirname(__FILE__) . '/wfUtils.php');
require_once(dirname(__FILE__) . '/wfBrowscap.php');
public $canLogHit = true;
private $effectiveUserID = 0;
private $wp_version = '';
private $googlePattern = '/\.(?:googlebot\.com|google\.[a-z]{2,3}|google\.[a-z]{2}\.[a-z]{2}|1e100\.net)$/i';
private $loginsTable, $statusTable;
private static $gbSafeCache = array();
public static function shared() {
$_shared = new wfLog(wfConfig::get('apiKey'), wfUtils::getWPVersion());
* Returns whether or not we have a cached record identifying the visitor as human. This is used both by certain
* rate limiting features and by Live Traffic.
public static function isHumanRequest($IP = false, $UA = false) {
if ($UA === false || $UA === null) {
$UA = (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
$ipHex = wfDB::binaryValueToSQLHex(wfUtils::inet_pton($IP));
$table = wfDB::networkTable('wfLiveTrafficHuman');
if ($wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE IP = {$ipHex} AND identifier = %s AND expiration >= UNIX_TIMESTAMP()", hash('sha256', $UA, true)))) {
* Creates a cache record for the requester to tag it as human.
public static function cacheHumanRequester($IP = false, $UA = false) {
$UA = (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
$ipHex = wfDB::binaryValueToSQLHex(wfUtils::inet_pton($IP));
$table = wfDB::networkTable('wfLiveTrafficHuman');
if ($wpdb->get_var($wpdb->prepare("INSERT IGNORE INTO {$table} (IP, identifier, expiration) VALUES ({$ipHex}, %s, UNIX_TIMESTAMP() + 86400)", hash('sha256', $UA, true)))) {
* Prunes any expired records from the human cache.
public static function trimHumanCache() {
$table = wfDB::networkTable('wfLiveTrafficHuman');
$wpdb->query("DELETE FROM {$table} WHERE `expiration` < UNIX_TIMESTAMP()");
public function __construct($apiKey, $wp_version){
$this->wp_version = $wp_version;
$this->hitsTable = wfDB::networkTable('wfHits');
$this->loginsTable = wfDB::networkTable('wfLogins');
$this->statusTable = wfDB::networkTable('wfStatus');
add_filter('determine_current_user', array($this, '_userIDDetermined'), 99, 1);
public function _userIDDetermined($userID) {
//Needed because the REST API will clear the authenticated user if it fails a nonce check on the request
$this->effectiveUserID = (int) $userID;
public function initLogRequest() {
if ($this->currentRequest === null) {
$this->currentRequest = new wfRequestModel();
$this->currentRequest->ctime = sprintf('%.6f', microtime(true));
$this->currentRequest->statusCode = 200;
$this->currentRequest->isGoogle = (wfCrawl::isGoogleCrawler() ? 1 : 0);
$this->currentRequest->IP = wfUtils::inet_pton(wfUtils::getIP());
$this->currentRequest->userID = $this->getCurrentUserID();
$this->currentRequest->URL = wfUtils::getRequestedURL();
$this->currentRequest->referer = (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '');
$this->currentRequest->UA = (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '');
$this->currentRequest->jsRun = 0;
add_action('wp_loaded', array($this, 'actionSetRequestJSEnabled'));
add_action('init', array($this, 'actionSetRequestOnInit'), 9999);
if (function_exists('register_shutdown_function')) {
register_shutdown_function(array($this, 'logHit'));
public function actionSetRequestJSEnabled() {
if (get_current_user_id() > 0) {
$this->currentRequest->jsRun = true;
$UA = $this->currentRequest->UA;
$this->currentRequest->jsRun = wfLog::isHumanRequest($IP, $UA);
* CloudFlare's plugin changes $_SERVER['REMOTE_ADDR'] on init.
public function actionSetRequestOnInit() {
$this->currentRequest->IP = wfUtils::inet_pton(wfUtils::getIP());
$this->currentRequest->userID = $this->getCurrentUserID();
public function getCurrentRequest() {
return $this->currentRequest;
public function logLogin($action, $fail, $username){
$user = get_user_by('login', $username);
$user = get_user_by('email', $username);
// change the action flag here if the user does not exist.
if ($action == 'loginFailValidUsername' && $userID == 0) {
$action = 'loginFailInvalidUsername';
if ($this->currentRequest !== null) {
$this->currentRequest->userID = $userID;
$this->currentRequest->action = $action;
$this->currentRequest->save();
$hitID = $this->currentRequest->getPrimaryKey();
//Else userID stays 0 but we do log this even though the user doesn't exist.
$ipHex = wfDB::binaryValueToSQLHex(wfUtils::inet_pton(wfUtils::getIP()));
$this->getDB()->queryWrite("insert into " . $this->loginsTable . " (hitID, ctime, fail, action, username, userID, IP, UA) values (%d, %f, %d, '%s', '%s', %s, {$ipHex}, '%s')",
sprintf('%.6f', microtime(true)),
(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '')
private function getCurrentUserID(){
if (!function_exists('get_current_user_id') || !defined('AUTH_COOKIE')) { //If pluggable.php is loaded early by some other plugin on a multisite installation, it leads to an error because AUTH_COOKIE is undefined and WP doesn't check for it first
$id = get_current_user_id();
public function logLeechAndBlock($type) { //404 or hit
if (!wfRateLimit::mightRateLimit($type)) {
wfRateLimit::countHit($type, wfUtils::getIP());
if (wfRateLimit::globalRateLimit()->shouldEnforce($type)) {
$this->takeBlockingAction('maxGlobalRequests', __("Exceeded the maximum global requests per minute for crawlers or humans.", 'wordfence'));
else if (wfRateLimit::crawlerViewsRateLimit()->shouldEnforce($type)) {
$this->takeBlockingAction('maxRequestsCrawlers', __("Exceeded the maximum number of requests per minute for crawlers.", 'wordfence')); //may not exit
else if (wfRateLimit::crawler404sRateLimit()->shouldEnforce($type)) {
$this->takeBlockingAction('max404Crawlers', __("Exceeded the maximum number of page not found errors per minute for a crawler.", 'wordfence'));
else if (wfRateLimit::humanViewsRateLimit()->shouldEnforce($type)) {
$this->takeBlockingAction('maxRequestsHumans', __("Exceeded the maximum number of page requests per minute for humans.", 'wordfence'));
else if (wfRateLimit::human404sRateLimit()->shouldEnforce($type)) {
$this->takeBlockingAction('max404Humans', __("Exceeded the maximum number of page not found errors per minute for humans.", 'wordfence'));
public function tagRequestForBlock($reason, $wfsn = false) {
if ($this->currentRequest !== null) {
$this->currentRequest->statusCode = 403;
$this->currentRequest->action = 'blocked:' . ($wfsn ? 'wfsn' : 'wordfence');
$this->currentRequest->actionDescription = $reason;
public function tagRequestForLockout($reason) {
if ($this->currentRequest !== null) {
$this->currentRequest->statusCode = 503;
$this->currentRequest->action = 'lockedOut';
$this->currentRequest->actionDescription = $reason;
public function logHit() {
$liveTrafficEnabled = wfConfig::liveTrafficEnabled();
$action = $this->currentRequest->action;
$logHitOK = $this->logHitOK();
if (!$liveTrafficEnabled && !$action) {
if ($this->currentRequest !== null) {
if ($this->currentRequest->save()) {
return $this->currentRequest->getPrimaryKey();
public function getHits($hitType /* 'hits' or 'logins' */, $type, $afterTime, $limit = 50, $IP = false){
$ipHex = wfDB::binaryValueToSQLHex(wfUtils::inet_pton($IP));
$IPSQL = " and IP={$ipHex} ";
$sqlArgs = array($afterTime, $limit);
$sqlArgs = array($afterTime, $limit);
$securityOnly = !wfConfig::liveTrafficEnabled();
$delayedHumanBotFiltering = false;
} else if($type == 'crawler'){
$delayedHumanBotFiltering = true;
$typeSQL = " and jsRun = 0 and {$now} - ctime > 30 ";
} else if($type == 'gCrawler'){
$typeSQL = " and isGoogle = 1 ";
} else if($type == '404'){
$typeSQL = " and statusCode = 404 ";
} else if($type == 'human'){
$delayedHumanBotFiltering = true;
$typeSQL = " and jsRun = 1 ";
} else if($type == 'ruser'){
$typeSQL = " and userID > 0 ";
wordfence::status(1, 'error', sprintf(/* translators: Error message. */ __("Invalid log type to wfLog: %s", 'wordfence'), $type));
array_unshift($sqlArgs, "select h.*, u.display_name from {$this->hitsTable} h
LEFT JOIN {$wpdb->users} u on h.userID = u.ID
where ctime > %f $IPSQL $typeSQL order by ctime desc limit %d");
$results = call_user_func_array(array($this->getDB(), 'querySelect'), $sqlArgs);
if ($delayedHumanBotFiltering) {
$browscap = wfBrowscap::shared();
foreach ($results as $index => $res) {
$b = $browscap->getBrowser($res['UA']);
if ($b && $b['Parent'] != 'DefaultProperties') {
$jsRun = wfUtils::truthyToBoolean($res['jsRun']);
if (!wfConfig::liveTrafficEnabled() && !$jsRun) {
$jsRun = !(isset($b['Crawler']) && $b['Crawler']);
if ($type == 'crawler' && $jsRun || $type == 'human' && !$jsRun) {
} else if($hitType == 'logins'){
array_unshift($sqlArgs, "select l.*, u.display_name from {$this->loginsTable} l
LEFT JOIN {$wpdb->users} u on l.userID = u.ID
where ctime > %f $IPSQL order by ctime desc limit %d");
$results = call_user_func_array(array($this->getDB(), 'querySelect'), $sqlArgs );
wordfence::status(1, 'error', sprintf(/* translators: Error message. */ __("getHits got invalid hitType: %s", 'wordfence'), $hitType));
$this->processGetHitsResults($type, $results);
private function processActionDescription($description) {
case wfWAFIPBlocksController::WFWAF_BLOCK_UAREFIPRANGE:
return __('UA/Hostname/Referrer/IP Range not allowed', 'wordfence');
public function processGetHitsResults($type, &$results) {
$serverTime = $this->getDB()->querySingle("select unix_timestamp()");
$this->resolveIPs($results);
$ourURL = parse_url(site_url());
$ourHost = strtolower($ourURL['host']);
$ourHost = preg_replace('/^www\./i', '', $ourHost);
$browscap = wfBrowscap::shared();
$patternBlocks = wfBlock::patternBlocks(true);
foreach($results as &$res){
$res['IP'] = wfUtils::inet_ntop($res['IP']);
$res['timeAgo'] = wfUtils::makeTimeAgo($serverTime - $res['ctime']);
$res['rangeBlocked'] = false;
if (array_key_exists('actionDescription', $res))
$res['actionDescription'] = $this->processActionDescription($res['actionDescription']);
$ipBlock = wfBlock::findIPBlock($res['IP']);
if ($ipBlock !== false) {
$res['blockID'] = $ipBlock->id;
foreach ($patternBlocks as $b) {
if (empty($b->ipRange)) { continue; }
$range = new wfUserIPRange($b->ipRange);
if ($range->isIPInRange($res['IP'])) {
$res['rangeBlocked'] = true;
$res['ipRangeID'] = $b->id;
$res['extReferer'] = false;
if(isset( $res['referer'] ) && $res['referer']){
if(wfUtils::hasXSS($res['referer'] )){ //filtering out XSS
if( isset( $res['referer'] ) && $res['referer']){
$refURL = parse_url($res['referer']);
if(is_array($refURL) && isset($refURL['host']) && $refURL['host']){
$refHost = strtolower(preg_replace('/^www\./i', '', $refURL['host']));
if($refHost != $ourHost){
$res['extReferer'] = true;
//now extract search terms
if(preg_match('/(?:google|bing|alltheweb|aol|ask)\./i', $refURL['host'])){
} else if(stristr($refURL['host'], 'yahoo.')){
} else if(stristr($refURL['host'], 'baidu.')){
if( isset( $refURL['query'] ) ) {
parse_str($refURL['query'], $queryVars);
if(isset($queryVars[$q])){
$res['searchTerms'] = urlencode($queryVars[$q]);
if ( isset( $referringPage ) && stristr( $referringPage['host'], 'google.' ) )
parse_str( $referringPage['query'], $queryVars );
// echo $queryVars['q']; // This is the search term used
$b = $browscap->getBrowser($res['UA']);
if($b && $b['Parent'] != 'DefaultProperties'){
'browser' => !empty($b['Browser']) ? $b['Browser'] : "",
'version' => !empty($b['Version']) ? $b['Version'] : "",
'platform' => !empty($b['Platform']) ? $b['Platform'] : "",
'isMobile' => !empty($b['isMobileDevice']) ? $b['isMobileDevice'] : "",
'isCrawler' => !empty($b['Crawler']) ? $b['Crawler'] : "",
if (isset($res['jsRun']) && !wfConfig::liveTrafficEnabled() && !wfUtils::truthyToBoolean($res['jsRun'])) {
$res['jsRun'] = !(isset($b['Crawler']) && $b['Crawler']) ? '1' : '0';
'isCrawler' => !wfLog::isHumanRequest($IP, $res['UA']) ? 'true' : ''
$ud = get_userdata($res['userID']);
'editLink' => wfUtils::editUserLink($res['userID']),
'display_name' => $res['display_name'],
public function resolveIPs(&$results){
if(sizeof($results) < 1){ return; }
foreach($results as &$res){
if($res['IP']){ //Can also be zero in case of non IP events
$IPLocs = wfUtils::getIPsGeo($IPs); //Creates an array with IP as key and data as value
foreach($results as &$res){
$ip_printable = wfUtils::inet_ntop($res['IP']);
if(isset($IPLocs[$ip_printable])){
$res['loc'] = $IPLocs[$ip_printable];
public function logHitOK(){