: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated in
* Copyright 2016 Freemius, Inc.
* Licensed under the GPL v2 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
* http://choosealicense.com/licenses/gpl-v2/
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
if ( ! defined( 'ABSPATH' ) ) {
require_once dirname( __FILE__ ) . '/FreemiusBase.php';
if ( ! defined( 'FS_SDK__USER_AGENT' ) ) {
define( 'FS_SDK__USER_AGENT', 'fs-php-' . Freemius_Api_Base::VERSION );
if ( ! defined( 'FS_SDK__SIMULATE_NO_CURL' ) ) {
define( 'FS_SDK__SIMULATE_NO_CURL', false );
if ( ! defined( 'FS_SDK__SIMULATE_NO_API_CONNECTIVITY_CLOUDFLARE' ) ) {
define( 'FS_SDK__SIMULATE_NO_API_CONNECTIVITY_CLOUDFLARE', false );
if ( ! defined( 'FS_SDK__SIMULATE_NO_API_CONNECTIVITY_SQUID_ACL' ) ) {
define( 'FS_SDK__SIMULATE_NO_API_CONNECTIVITY_SQUID_ACL', false );
if ( ! defined( 'FS_SDK__HAS_CURL' ) ) {
if ( FS_SDK__SIMULATE_NO_CURL ) {
define( 'FS_SDK__HAS_CURL', false );
$curl_required_methods = array(
foreach ( $curl_required_methods as $m ) {
if ( ! function_exists( $m ) ) {
define( 'FS_SDK__HAS_CURL', $has_curl );
if ( ! defined( 'FS_SDK__SSLVERIFY' ) ) {
define( 'FS_SDK__SSLVERIFY', false );
$curl_version = FS_SDK__HAS_CURL ?
array( 'version' => '7.37' );
if ( ! defined( 'FS_API__PROTOCOL' ) ) {
define( 'FS_API__PROTOCOL', version_compare( $curl_version['version'], '7.37', '>=' ) ? 'https' : 'http' );
if ( ! defined( 'FS_API__LOGGER_ON' ) ) {
define( 'FS_API__LOGGER_ON', false );
if ( ! defined( 'FS_API__ADDRESS' ) ) {
define( 'FS_API__ADDRESS', '://api.freemius.com' );
if ( ! defined( 'FS_API__SANDBOX_ADDRESS' ) ) {
define( 'FS_API__SANDBOX_ADDRESS', '://sandbox-api.freemius.com' );
if ( ! class_exists( 'Freemius_Api_WordPress' ) ) {
class Freemius_Api_WordPress extends Freemius_Api_Base {
private static $_logger = array();
* @param string $pScope 'app', 'developer', 'user' or 'install'.
* @param number $pID Element's id.
* @param string $pPublic Public key.
* @param string|bool $pSecret Element's secret key.
* @param bool $pSandbox Whether or not to run API in sandbox mode.
public function __construct( $pScope, $pID, $pPublic, $pSecret = false, $pSandbox = false ) {
// If secret key not provided, use public key encryption.
if ( is_bool( $pSecret ) ) {
parent::Init( $pScope, $pID, $pPublic, $pSecret, $pSandbox );
public static function GetUrl( $pCanonizedPath = '', $pIsSandbox = false ) {
$address = ( $pIsSandbox ? FS_API__SANDBOX_ADDRESS : FS_API__ADDRESS );
if ( ':' === $address[0] ) {
$address = self::$_protocol . $address;
return $address . $pCanonizedPath;
#----------------------------------------------------------------------------------
#region Servers Clock Diff
#----------------------------------------------------------------------------------
* @var int Clock diff in seconds between current server to API server.
private static $_clock_diff = 0;
* Set clock diff for all API calls.
public static function SetClockDiff( $pSeconds ) {
self::$_clock_diff = $pSeconds;
* Find clock diff between current server to API server.
* @return int Clock diff in seconds.
public static function FindClockDiff() {
return ( $time - strtotime( $pong->timestamp ) );
* @var string http or https
private static $_protocol = FS_API__PROTOCOL;
* Set API connection protocol.
public static function SetHttp() {
self::$_protocol = 'http';
* Sets API connection protocol to HTTPS.
public static function SetHttps() {
self::$_protocol = 'https';
public static function IsHttps() {
return ( 'https' === self::$_protocol );
* Sign request with the following HTTP headers:
* Content-MD5: MD5(HTTP Request body)
* Date: Current date (i.e Sat, 14 Feb 2016 20:24:46 +0000)
* Authorization: FS {scope_entity_id}:{scope_entity_public_key}:base64encode(sha256(string_to_sign,
* {scope_entity_secret_key}))
* @param string $pResourceUrl
* @param array $pWPRemoteArgs
function SignRequest( $pResourceUrl, $pWPRemoteArgs ) {
$auth = $this->GenerateAuthorizationParams(
$pWPRemoteArgs['method'],
! empty( $pWPRemoteArgs['body'] ) ? $pWPRemoteArgs['body'] : ''
$pWPRemoteArgs['headers']['Date'] = $auth['date'];
$pWPRemoteArgs['headers']['Authorization'] = $auth['authorization'];
if ( ! empty( $auth['content_md5'] ) ) {
$pWPRemoteArgs['headers']['Content-MD5'] = $auth['content_md5'];
* Generate Authorization request headers:
* Content-MD5: MD5(HTTP Request body)
* Date: Current date (i.e Sat, 14 Feb 2016 20:24:46 +0000)
* Authorization: FS {scope_entity_id}:{scope_entity_public_key}:base64encode(sha256(string_to_sign,
* {scope_entity_secret_key}))
* @param string $pResourceUrl
* @param string $pPostParams
* @throws Freemius_Exception
function GenerateAuthorizationParams(
$pMethod = strtoupper( $pMethod );
$now = ( time() - self::$_clock_diff );
$date = date( 'r', $now );
if ( in_array( $pMethod, array( 'POST', 'PUT' ) ) ) {
$content_type = 'application/json';
if ( ! empty( $pPostParams ) ) {
$content_md5 = md5( $pPostParams );
$string_to_sign = implode( $eol, array(
// If secret and public keys are identical, it means that
// the signature uses public key hash encoding.
$auth_type = ( $this->_secret !== $this->_public ) ? 'FS' : 'FSP';
'authorization' => $auth_type . ' ' . $this->_id . ':' .
self::Base64UrlEncode( hash_hmac(
'sha256', $string_to_sign, $this->_secret
if ( ! empty( $content_md5 ) ) {
$auth['content_md5'] = $content_md5;
* Get API request URL signed via query string.
* @since 1.2.3 Stopped using http_build_query(). Instead, use urlencode(). In some environments the encoding of http_build_query() can generate a URL that once used with a redirect, the `&` querystring separator is escaped to `&` which breaks the URL (Added by @svovaf).
* @throws Freemius_Exception
function GetSignedUrl( $pPath ) {
$resource = explode( '?', $this->CanonizePath( $pPath ) );
$pResourceUrl = $resource[0];
$auth = $this->GenerateAuthorizationParams( $pResourceUrl );
return Freemius_Api_WordPress::GetUrl(
( 1 < count( $resource ) && ! empty( $resource[1] ) ? $resource[1] . '&' : '' ) .
'authorization=' . urlencode( $auth['authorization'] ) .
'&auth_date=' . urlencode( $auth['date'] )
* @param array $pWPRemoteArgs
private static function ExecuteRequest( $pUrl, &$pWPRemoteArgs ) {
$start = microtime( true );
$response = self::RemoteRequest( $pUrl, $pWPRemoteArgs );
if ( FS_API__LOGGER_ON ) {
$end = microtime( true );
$has_body = ( isset( $pWPRemoteArgs['body'] ) && ! empty( $pWPRemoteArgs['body'] ) );
$is_http_error = is_wp_error( $response );
self::$_logger[] = array(
'id' => count( self::$_logger ),
'total' => ( $end - $start ),
'method' => $pWPRemoteArgs['method'],
'body' => $has_body ? $pWPRemoteArgs['body'] : null,
'result' => ! $is_http_error ?
json_encode( $response->get_error_messages() ),
'code' => ! $is_http_error ? $response['response']['code'] : null,
* @author Leo Fajardo (@leorw)
* @param array $pWPRemoteArgs
* @return array|WP_Error The response array or a WP_Error on failure.
static function RemoteRequest( $pUrl, $pWPRemoteArgs ) {
$response = wp_remote_request( $pUrl, $pWPRemoteArgs );
empty( $response['headers'] ) ||
empty( $response['headers']['x-api-server'] )
// API is considered blocked if the response doesn't include the `x-api-server` header. When there's no error but this header doesn't exist, the response is usually not in the expected form (e.g., cannot be JSON-decoded).
$response = new WP_Error( 'api_blocked', htmlentities( $response['body'] ) );
static function GetLogger() {
* @param string $pCanonizedPath
* @param null|array $pWPRemoteArgs
* @param bool $pIsSandbox
* @param null|callable $pBeforeExecutionFunction
* @return object[]|object|null
* @throws \Freemius_Exception
private static function MakeStaticRequest(
$pBeforeExecutionFunction = null
// Connectivity errors simulation.
if ( FS_SDK__SIMULATE_NO_API_CONNECTIVITY_CLOUDFLARE ) {
self::ThrowCloudFlareDDoSException();
} else if ( FS_SDK__SIMULATE_NO_API_CONNECTIVITY_SQUID_ACL ) {
self::ThrowSquidAclException();
if ( empty( $pWPRemoteArgs ) ) {
$user_agent = 'Freemius/WordPress-SDK/' . Freemius_Api_Base::VERSION . '; ' .
'method' => strtoupper( $pMethod ),
'follow_redirects' => true,
'user-agent' => $user_agent,
if ( ! isset( $pWPRemoteArgs['headers'] ) ||
! is_array( $pWPRemoteArgs['headers'] )
$pWPRemoteArgs['headers'] = array();
if ( in_array( $pMethod, array( 'POST', 'PUT' ) ) ) {
$pWPRemoteArgs['headers']['Content-type'] = 'application/json';
if ( is_array( $pParams ) && 0 < count( $pParams ) ) {
$pWPRemoteArgs['body'] = json_encode( $pParams );
$request_url = self::GetUrl( $pCanonizedPath, $pIsSandbox );
$resource = explode( '?', $pCanonizedPath );
if ( FS_SDK__HAS_CURL ) {
// Disable the 'Expect: 100-continue' behaviour. This causes cURL to wait
// for 2 seconds if the server does not support this header.
$pWPRemoteArgs['headers']['Expect'] = '';
if ( 'https' === substr( strtolower( $request_url ), 0, 5 ) ) {
$pWPRemoteArgs['sslverify'] = FS_SDK__SSLVERIFY;
if ( false !== $pBeforeExecutionFunction &&
is_callable( $pBeforeExecutionFunction )
$pWPRemoteArgs = call_user_func( $pBeforeExecutionFunction, $resource[0], $pWPRemoteArgs );
$result = self::ExecuteRequest( $request_url, $pWPRemoteArgs );
if ( is_wp_error( $result ) ) {
if ( self::IsCurlError( $result ) ) {
* With dual stacked DNS responses, it's possible for a server to
* have IPv6 enabled but not have IPv6 connectivity. If this is
* the case, cURL will try IPv4 first and if that fails, then it will
* fall back to IPv6 and the error EHOSTUNREACH is returned by the
$regex = '/Failed to connect to ([^:].*): Network is unreachable/';
if ( preg_match( $regex, $result->get_error_message( 'http_request_failed' ), $matches ) ) {
* Validate IP before calling `inet_pton()` to avoid PHP un-catchable warning.
* @author Vova Feldman (@svovaf)
if ( filter_var( $matches[1], FILTER_VALIDATE_IP ) ) {
if ( strlen( inet_pton( $matches[1] ) ) === 16 ) {
* error_log('Invalid IPv6 configuration on server, Please disable or get native IPv6 on your server.');
* Hook to an action triggered just before cURL is executed to resolve the IP version to v4.
* @phpstan-ignore-next-line
add_action( 'http_api_curl', 'Freemius_Api_WordPress::CurlResolveToIPv4', 10, 1 );
$result = self::ExecuteRequest( $request_url, $pWPRemoteArgs );
if ( is_wp_error( $result ) ) {
self::ThrowWPRemoteException( $result );
$response_body = $result['body'];
if ( empty( $response_body ) ) {