class-fs-api.php 19.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
<?php
	/**
	 * @package     Freemius
	 * @copyright   Copyright (c) 2015, Freemius, Inc.
	 * @license     https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License Version 3
	 * @since       1.0.4
	 */

	if ( ! defined( 'ABSPATH' ) ) {
		exit;
	}

	/**
	 * Class FS_Api
	 *
	 * Wraps Freemius API SDK to handle:
	 *      1. Clock sync.
	 *      2. Fallback to HTTP when HTTPS fails.
	 *      3. Adds caching layer to GET requests.
	 *      4. Adds consistency for failed requests by using last cached version.
	 */
	class FS_Api {
		/**
		 * @var FS_Api[]
		 */
		private static $_instances = array();

		/**
		 * @var FS_Option_Manager Freemius options, options-manager.
		 */
		private static $_options;

		/**
		 * @var FS_Cache_Manager API Caching layer
		 */
		private static $_cache;

		/**
		 * @var int Clock diff in seconds between current server to API server.
		 */
		private static $_clock_diff;

		/**
		 * @var Freemius_Api_WordPress
		 */
		private $_api;

		/**
		 * @var string
		 */
		private $_slug;

		/**
		 * @var FS_Logger
		 * @since 1.0.4
		 */
		private $_logger;

        /**
         * @author Leo Fajardo (@leorw)
         * @since 2.3.0
         *
         * @var string
         */
        private $_sdk_version;

        /**
		 * @param string      $slug
		 * @param string      $scope      'app', 'developer', 'user' or 'install'.
		 * @param number      $id         Element's id.
		 * @param string      $public_key Public key.
		 * @param bool        $is_sandbox
		 * @param bool|string $secret_key Element's secret key.
		 * @param null|string $sdk_version
		 *
		 * @return FS_Api
		 */
		static function instance(
		    $slug,
            $scope,
            $id,
            $public_key,
            $is_sandbox,
            $secret_key = false,
            $sdk_version = null
        ) {
			$identifier = md5( $slug . $scope . $id . $public_key . ( is_string( $secret_key ) ? $secret_key : '' ) . json_encode( $is_sandbox ) );

			if ( ! isset( self::$_instances[ $identifier ] ) ) {
				self::_init();

				self::$_instances[ $identifier ] = new FS_Api( $slug, $scope, $id, $public_key, $secret_key, $is_sandbox, $sdk_version );
			}

			return self::$_instances[ $identifier ];
		}

		private static function _init() {
			if ( isset( self::$_options ) ) {
				return;
			}

			if ( ! class_exists( 'Freemius_Api_WordPress' ) ) {
				require_once WP_FS__DIR_SDK . '/FreemiusWordPress.php';
			}

			self::$_options = FS_Option_Manager::get_manager( WP_FS__OPTIONS_OPTION_NAME, true, true );
			self::$_cache   = FS_Cache_Manager::get_manager( WP_FS__API_CACHE_OPTION_NAME );

			self::$_clock_diff = self::$_options->get_option( 'api_clock_diff', 0 );
			Freemius_Api_WordPress::SetClockDiff( self::$_clock_diff );

			if ( self::$_options->get_option( 'api_force_http', false ) ) {
				Freemius_Api_WordPress::SetHttp();
			}
		}

		/**
		 * @param string      $slug
		 * @param string      $scope      'app', 'developer', 'user' or 'install'.
		 * @param number      $id         Element's id.
		 * @param string      $public_key Public key.
		 * @param bool|string $secret_key Element's secret key.
		 * @param bool        $is_sandbox
		 * @param null|string $sdk_version
		 */
		private function __construct(
		    $slug,
            $scope,
            $id,
            $public_key,
            $secret_key,
            $is_sandbox,
            $sdk_version
        ) {
			$this->_api = new Freemius_Api_WordPress( $scope, $id, $public_key, $secret_key, $is_sandbox );

			$this->_slug        = $slug;
			$this->_sdk_version = $sdk_version;
			$this->_logger      = FS_Logger::get_logger( WP_FS__SLUG . '_' . $slug . '_api', WP_FS__DEBUG_SDK, WP_FS__ECHO_DEBUG_SDK );
		}

		/**
		 * Find clock diff between server and API server, and store the diff locally.
		 *
		 * @param bool|int $diff
		 *
		 * @return bool|int False if clock diff didn't change, otherwise returns the clock diff in seconds.
		 */
		private function _sync_clock_diff( $diff = false ) {
			$this->_logger->entrance();

			// Sync clock and store.
			$new_clock_diff = ( false === $diff ) ?
				Freemius_Api_WordPress::FindClockDiff() :
				$diff;

			if ( $new_clock_diff === self::$_clock_diff ) {
				return false;
			}

			self::$_clock_diff = $new_clock_diff;

			// Update API clock's diff.
			Freemius_Api_WordPress::SetClockDiff( self::$_clock_diff );

			// Store new clock diff in storage.
			self::$_options->set_option( 'api_clock_diff', self::$_clock_diff, true );

			return $new_clock_diff;
		}

		/**
		 * Override API call to enable retry with servers' clock auto sync method.
		 *
		 * @param string $path
		 * @param string $method
		 * @param array  $params
		 * @param bool   $retry Is in retry or first call attempt.
		 *
		 * @return array|mixed|string|void
		 */
		private function _call( $path, $method = 'GET', $params = array(), $retry = false ) {
            $this->_logger->entrance( $method . ':' . $path );

            if ( self::is_temporary_down() ) {
                $result = $this->get_temporary_unavailable_error();
            } else {
                /**
                 * @since 2.3.0 Include the SDK version with all API requests that going through the API manager. IMPORTANT: Only pass the SDK version if the caller didn't include it yet.
                 */
                if ( ! empty( $this->_sdk_version ) ) {
                    if ( false === strpos( $path, 'sdk_version=' ) &&
                         ! isset( $params['sdk_version'] )
                    ) {
                        // Always add the sdk_version param in the querystring. DO NOT INCLUDE IT IN THE BODY PARAMS, OTHERWISE, IT MAY LEAD TO AN UNEXPECTED PARAMS PARSING IN CASES WHERE THE $params IS A REGULAR NON-ASSOCIATIVE ARRAY.
                        $path = add_query_arg( 'sdk_version', $this->_sdk_version, $path );
                    }
                }

                $result = $this->_api->Api( $path, $method, $params );

                if ( null !== $result &&
                     isset( $result->error ) &&
                     isset( $result->error->code ) &&
                     'request_expired' === $result->error->code
                ) {
                    if ( ! $retry ) {
                        $diff = isset( $result->error->timestamp ) ?
                            ( time() - strtotime( $result->error->timestamp ) ) :
                            false;

                        // Try to sync clock diff.
                        if ( false !== $this->_sync_clock_diff( $diff ) ) {
                            // Retry call with new synced clock.
                            return $this->_call( $path, $method, $params, true );
                        }
                    }
                }
            }

            if ( $this->_logger->is_on() && self::is_api_error( $result ) ) {
                // Log API errors.
                $this->_logger->api_error( $result );
            }

            return $result;
        }

		/**
		 * Override API call to wrap it in servers' clock sync method.
		 *
		 * @param string $path
		 * @param string $method
		 * @param array  $params
		 *
		 * @return array|mixed|string|void
		 * @throws Freemius_Exception
		 */
		function call( $path, $method = 'GET', $params = array() ) {
			return $this->_call( $path, $method, $params );
		}

		/**
		 * Get API request URL signed via query string.
		 *
		 * @param string $path
		 *
		 * @return string
		 */
		function get_signed_url( $path ) {
			return $this->_api->GetSignedUrl( $path );
		}

		/**
		 * @param string $path
		 * @param bool   $flush
		 * @param int    $expiration (optional) Time until expiration in seconds from now, defaults to 24 hours
		 *
		 * @return stdClass|mixed
		 */
		function get( $path = '/', $flush = false, $expiration = WP_FS__TIME_24_HOURS_IN_SEC ) {
			$this->_logger->entrance( $path );

			$cache_key = $this->get_cache_key( $path );

			// Always flush during development.
			if ( WP_FS__DEV_MODE || $this->_api->IsSandbox() ) {
				$flush = true;
			}

			$cached_result = self::$_cache->get( $cache_key );

			if ( $flush || ! self::$_cache->has_valid( $cache_key, $expiration ) ) {
				$result = $this->call( $path );

				if ( ! is_object( $result ) || isset( $result->error ) ) {
					// Api returned an error.
					if ( is_object( $cached_result ) &&
					     ! isset( $cached_result->error )
					) {
						// If there was an error during a newer data fetch,
						// fallback to older data version.
						$result = $cached_result;

						if ( $this->_logger->is_on() ) {
							$this->_logger->warn( 'Fallback to cached API result: ' . var_export( $cached_result, true ) );
						}
					} else {
					    if ( is_object( $result ) && isset( $result->error->http ) && 404 == $result->error->http ) {
                            /**
                             * If the response code is 404, cache the result for half of the `$expiration`.
                             *
                             * @author Leo Fajardo (@leorw)
                             * @since 2.2.4
                             */
					        $expiration /= 2;
                        } else {
                            // If no older data version and the response code is not 404, return result without
                            // caching the error.
                            return $result;
                        }
					}
				}

				self::$_cache->set( $cache_key, $result, $expiration );

				$cached_result = $result;
			} else {
				$this->_logger->log( 'Using cached API result.' );
			}

			return $cached_result;
		}

		/**
		 * Check if there's a cached version of the API request.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.2.1
		 *
		 * @param string $path
		 * @param string $method
		 * @param array  $params
		 *
		 * @return bool
		 */
		function is_cached( $path, $method = 'GET', $params = array() ) {
			$cache_key = $this->get_cache_key( $path, $method, $params );

			return self::$_cache->has_valid( $cache_key );
		}

		/**
		 * Invalidate a cached version of the API request.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.2.1.5
		 *
		 * @param string $path
		 * @param string $method
		 * @param array  $params
		 */
		function purge_cache( $path, $method = 'GET', $params = array() ) {
			$this->_logger->entrance( "{$method}:{$path}" );

			$cache_key = $this->get_cache_key( $path, $method, $params );

			self::$_cache->purge( $cache_key );
		}

        /**
         * Invalidate a cached version of the API request.
         *
         * @author Vova Feldman (@svovaf)
         * @since  2.0.0
         *
         * @param string $path
         * @param int    $expiration
         * @param string $method
         * @param array  $params
         */
        function update_cache_expiration( $path, $expiration = WP_FS__TIME_24_HOURS_IN_SEC, $method = 'GET', $params = array() ) {
            $this->_logger->entrance( "{$method}:{$path}:{$expiration}" );

            $cache_key = $this->get_cache_key( $path, $method, $params );

            self::$_cache->update_expiration( $cache_key, $expiration );
        }

        /**
		 * @param string $path
		 * @param string $method
		 * @param array  $params
		 *
		 * @return string
		 * @throws \Freemius_Exception
		 */
		private function get_cache_key( $path, $method = 'GET', $params = array() ) {
			$canonized = $this->_api->CanonizePath( $path );
//			$exploded = explode('/', $canonized);
//			return $method . '_' . array_pop($exploded) . '_' . md5($canonized . json_encode($params));
			return strtolower( $method . ':' . $canonized ) . ( ! empty( $params ) ? '#' . md5( json_encode( $params ) ) : '' );
		}

		/**
		 * Test API connectivity.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.0.9 If fails, try to fallback to HTTP.
		 * @since  1.1.6 Added a 5-min caching mechanism, to prevent from overloading the server if the API if
		 *         temporary down.
		 *
		 * @return bool True if successful connectivity to the API.
		 */
		static function test() {
			self::_init();

			$cache_key = 'ping_test';

			$test = self::$_cache->get_valid( $cache_key, null );

			if ( is_null( $test ) ) {
				$test = Freemius_Api_WordPress::Test();

				if ( false === $test && Freemius_Api_WordPress::IsHttps() ) {
					// Fallback to HTTP, since HTTPS fails.
					Freemius_Api_WordPress::SetHttp();

					self::$_options->set_option( 'api_force_http', true, true );

					$test = Freemius_Api_WordPress::Test();

					if ( false === $test ) {
						/**
						 * API connectivity test fail also in HTTP request, therefore,
						 * fallback to HTTPS to keep connection secure.
						 *
						 * @since 1.1.6
						 */
						self::$_options->set_option( 'api_force_http', false, true );
					}
				}

				self::$_cache->set( $cache_key, $test, WP_FS__TIME_5_MIN_IN_SEC );
			}

			return $test;
		}

		/**
		 * Check if API is temporary down.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.1.6
		 *
		 * @return bool
		 */
		static function is_temporary_down() {
			self::_init();

			$test = self::$_cache->get_valid( 'ping_test', null );

			return ( false === $test );
		}

		/**
		 * @author Vova Feldman (@svovaf)
		 * @since  1.1.6
		 *
		 * @return object
		 */
		private function get_temporary_unavailable_error() {
			return (object) array(
				'error' => (object) array(
					'type'    => 'TemporaryUnavailable',
					'message' => 'API is temporary unavailable, please retry in ' . ( self::$_cache->get_record_expiration( 'ping_test' ) - WP_FS__SCRIPT_START_TIME ) . ' sec.',
					'code'    => 'temporary_unavailable',
					'http'    => 503
				)
			);
		}

		/**
		 * Ping API for connectivity test, and return result object.
		 *
		 * @author   Vova Feldman (@svovaf)
		 * @since    1.0.9
		 *
		 * @param null|string $unique_anonymous_id
		 * @param array       $params
		 *
		 * @return object
		 */
		function ping( $unique_anonymous_id = null, $params = array() ) {
			$this->_logger->entrance();

			if ( self::is_temporary_down() ) {
				return $this->get_temporary_unavailable_error();
			}

			$pong = is_null( $unique_anonymous_id ) ?
				Freemius_Api_WordPress::Ping() :
				$this->_call( 'ping.json?' . http_build_query( array_merge(
						array( 'uid' => $unique_anonymous_id ),
						$params
					) ) );

			if ( $this->is_valid_ping( $pong ) ) {
				return $pong;
			}

			if ( self::should_try_with_http( $pong ) ) {
				// Fallback to HTTP, since HTTPS fails.
				Freemius_Api_WordPress::SetHttp();

				self::$_options->set_option( 'api_force_http', true, true );

				$pong = is_null( $unique_anonymous_id ) ?
					Freemius_Api_WordPress::Ping() :
					$this->_call( 'ping.json?' . http_build_query( array_merge(
							array( 'uid' => $unique_anonymous_id ),
							$params
						) ) );

				if ( ! $this->is_valid_ping( $pong ) ) {
					self::$_options->set_option( 'api_force_http', false, true );
				}
			}

			return $pong;
		}

		/**
		 * Check if based on the API result we should try
		 * to re-run the same request with HTTP instead of HTTPS.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.1.6
		 *
		 * @param $result
		 *
		 * @return bool
		 */
		private static function should_try_with_http( $result ) {
			if ( ! Freemius_Api_WordPress::IsHttps() ) {
				return false;
			}

			return ( ! is_object( $result ) ||
			         ! isset( $result->error ) ||
			         ! isset( $result->error->code ) ||
			         ! in_array( $result->error->code, array(
				         'curl_missing',
				         'cloudflare_ddos_protection',
				         'maintenance_mode',
				         'squid_cache_block',
				         'too_many_requests',
			         ) ) );

		}

		/**
		 * Check if valid ping request result.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.1.1
		 *
		 * @param mixed $pong
		 *
		 * @return bool
		 */
		function is_valid_ping( $pong ) {
			return Freemius_Api_WordPress::Test( $pong );
		}

		function get_url( $path = '' ) {
			return Freemius_Api_WordPress::GetUrl( $path, $this->_api->IsSandbox() );
		}

		/**
		 * Clear API cache.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.0.9
		 */
		static function clear_cache() {
			self::_init();

			self::$_cache = FS_Cache_Manager::get_manager( WP_FS__API_CACHE_OPTION_NAME );
			self::$_cache->clear();
		}

		#----------------------------------------------------------------------------------
		#region Error Handling
		#----------------------------------------------------------------------------------

		/**
		 * @author Vova Feldman (@svovaf)
		 * @since  1.2.1.5
		 *
		 * @param mixed $result
		 *
		 * @return bool Is API result contains an error.
		 */
		static function is_api_error( $result ) {
			return ( is_object( $result ) && isset( $result->error ) ) ||
			       is_string( $result );
		}

        /**
         * @author Vova Feldman (@svovaf)
         * @since  2.0.0
         *
         * @param mixed $result
         *
         * @return bool Is API result contains an error.
         */
        static function is_api_error_object( $result ) {
            return (
                is_object( $result ) &&
                isset( $result->error ) &&
                isset( $result->error->message )
            );
        }

		/**
		 * Checks if given API result is a non-empty and not an error object.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.2.1.5
		 *
		 * @param mixed       $result
		 * @param string|null $required_property Optional property we want to verify that is set.
		 *
		 * @return bool
		 */
		static function is_api_result_object( $result, $required_property = null ) {
			return (
				is_object( $result ) &&
				! isset( $result->error ) &&
				( empty( $required_property ) || isset( $result->{$required_property} ) )
			);
		}

		/**
		 * Checks if given API result is a non-empty entity object with non-empty ID.
		 *
		 * @author Vova Feldman (@svovaf)
		 * @since  1.2.1.5
		 *
		 * @param mixed $result
		 *
		 * @return bool
		 */
		static function is_api_result_entity( $result ) {
			return self::is_api_result_object( $result, 'id' ) &&
			       FS_Entity::is_valid_id( $result->id );
		}

        /**
         * Get API result error code. If failed to get code, returns an empty string.
         *
         * @author Vova Feldman (@svovaf)
         * @since  2.0.0
         *
         * @param mixed $result
         *
         * @return string
         */
        static function get_error_code( $result ) {
            if ( is_object( $result ) &&
                 isset( $result->error ) &&
                 is_object( $result->error ) &&
                 ! empty( $result->error->code )
            ) {
                return $result->error->code;
            }

            return '';
        }

		#endregion
	}