License.php 12.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
<?php
/**
 * Upgrade management.
 *
 * @copyright (c) 2023, Code Atlantic LLC.
 *
 * @package ContentControl
 */

namespace ContentControl\Plugin;

defined( 'ABSPATH' ) || exit;

/**
 * License management.
 *
 * NOTE: For wordpress.org admins: This is only used if:
 * - The user explicitly entered a license key.
 *
 * @package ContentControl
 */
class License {

	/**
	 * EDD API URL.
	 *
	 * @var string
	 */
	const API_URL = 'https://contentcontrolplugin.com/edd-sl-api/';

	/**
	 * Item ID.
	 *
	 * @var int
	 */
	const ID = 45;

	/**
	 * Option key.
	 *
	 * @var string
	 */
	const OPTION_KEY = 'content_control_license';

	/**
	 * License data
	 *
	 * @var array<string,mixed>|null
	 */
	private $license_data;

	/**
	 * Initialize license management.
	 */
	public function __construct() {
		$this->register_hooks();
	}

	/**
	 * Register hooks.
	 *
	 * @return void
	 */
	public function register_hooks() {
		add_action( 'init', [ $this, 'autoregister' ] );
		add_action( 'content_control_license_status_check', [ $this, 'refresh_license_status' ] );
		add_action( 'admin_init', [ $this, 'schedule_crons' ] );
	}

	/**
	 * Autoregister license.
	 *
	 * @return void
	 */
	public function autoregister() {
		$key = defined( '\CONTENT_CONTROL_LICENSE_KEY' ) && '' !== \CONTENT_CONTROL_LICENSE_KEY ? \CONTENT_CONTROL_LICENSE_KEY : false;

		if ( $key && '' === $this->get_license_key() ) {
			try {
				$this->activate_license( \CONTENT_CONTROL_LICENSE_KEY );
			// phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
			} catch ( \Exception $e ) {
				// Do nothing.
			}
		}
	}

	/**
	 * Schedule cron jobs.
	 *
	 * @return void
	 */
	public function schedule_crons() {
		if ( ! wp_next_scheduled( 'content_control_license_status_check' ) ) {
			wp_schedule_event( time(), 'daily', 'content_control_license_status_check' );
		}
	}

	/**
	 * Get license data.
	 *
	 * @return array{key:string|null,status:array<string,mixed>|null}
	 */
	public function get_license_data() {
		if ( ! isset( $this->license_data ) ) {
			$this->license_data = \get_option( self::OPTION_KEY, [
				'key'    => '',
				'status' => [
					'success'          => false, // bool.
					'license'          => 'invalid', // valid or invalid.
					'item_id'          => self::ID, // int or false.
					'item_name'        => '', // string.
					'license_limit'    => 1, // int. 0 = unlimited.
					'site_count'       => 0,
					'expires'          => '', // date or 'lifetime'.
					'activations_left' => 0, // int or 'unlimited'.
					'checksum'         => '', // string.
					'payment_id'       => 0, // int.
					'customer_name'    => '', // string.
					'customer_email'   => '', // string.
					'price_id'         => 0, // string or int.
					'error'            => null, // string. expired, missing, invalid, item_name_mismatch, no_activations_left etc.
				],
			] );
		}

		return $this->license_data;
	}

	/**
	 * Get license key.
	 *
	 * @return string
	 */
	public function get_license_key() {
		$license_data = $this->get_license_data();
		return ! empty( $license_data['key'] ) ? $license_data['key'] : '';
	}

	/**
	 * Get license status.
	 *
	 * @param bool $refresh Whether to refresh license status.
	 *
	 * @return array<string,mixed> Array of license status data.
	 */
	public function get_license_status( $refresh = false ) {
		if ( $refresh ) {
			$this->refresh_license_status();
		}

		$license_data = $this->get_license_data();

		$license_status = isset( $license_data['status'] ) ? $license_data['status'] : [];

		return $license_status;
	}

	/**
	 * Get license level.
	 *
	 * Only used in pro version.
	 *
	 * @return int Integer representing license level.
	 */
	public function get_license_level() {
		$license_status = $this->get_license_status();

		if ( empty( $license_status ) ) {
			return -1;
		}

		$price_id = isset( $license_status['price_id'] ) ? $license_status['price_id'] : null;

		switch ( $price_id ) {
			default:
				return -1;

			case false:
			case 0:
				return 0;

			case 1:
			case 2:
			case 3:
			case 4:
				return absint( $price_id );
		}
	}

	/**
	 * Update license data.
	 *
	 * @param array{key:string|null,status:array<string,mixed>|null} $license_data License data.
	 *
	 * @return bool
	 */
	public function udpate_license_data( $license_data ) {
		if ( \update_option( self::OPTION_KEY, $license_data ) ) {
			$this->license_data = $license_data;
			return true;
		}

		return false;
	}

	/**
	 * Update license key.
	 *
	 * @param string $key License key.
	 *
	 * @return void
	 */
	public function update_license_key( $key ) {
		$license_data = $this->get_license_data();

		$old_key = isset( $license_data['key'] ) ? $license_data['key'] : '';

		$license_data['key'] = trim( $key );

		$this->udpate_license_data( $license_data );

		/**
		 * Fires when license key is changed.
		 *
		 * @param string $key License key.
		 * @param string $old_key Old license key.
		 */
		\do_action( 'content_control_license_key_changed', $key, $old_key );
	}

	/**
	 * Update license status.
	 *
	 * @param array<string,mixed> $license_status License status data.
	 *
	 * @return void
	 */
	public function update_license_status( $license_status ) {
		$license_data = $this->get_license_data();

		$previous_status = isset( $license_data['status'] ) ? $license_data['status'] : [];

		if ( ! empty( $license_status['error'] ) ) {
			$license_status['error_message'] = $this->get_license_error_message( $license_status );
		}

		$license_data['status'] = $license_status;

		$this->udpate_license_data( $license_data );

		/**
		 * Fires when license status is updated.
		 *
		 * @param array $license_status License status data.
		 * @param array $previous_status Previous license status data.
		 */
		\do_action( 'content_control_license_status_updated', $license_status, $previous_status );
	}

	/**
	 * Get license expiration from license status data.
	 *
	 * @param bool $as_datetime Whether to return as DateTime object.
	 *
	 * @return \DateTime|false|null
	 */
	public function get_license_expiration( $as_datetime = false ) {
		$status = $this->get_license_status();

		$expiration = isset( $status['expires'] ) ? $status['expires'] : null;

		return $as_datetime ?
			\DateTime::createFromFormat( 'Y-m-d H:i:s', $expiration ) :
			$expiration;
	}

	/**
	 * Fetch license status from remote server.
	 * This is a blocking request.
	 *
	 * @return void
	 */
	public function refresh_license_status() {
		$key = $this->get_license_key();

		if ( empty( $key ) ) {
			return;
		}

		try {
			$status = $this->check_license();
		} catch ( \Exception $e ) {
			$status = [];
		}

		$this->update_license_status( $status );
	}

	/**
	 * Get license status from remote server.
	 *
	 * @return array<string,mixed> License status data.
	 *
	 * @throws \Exception If there is an error.
	 */
	private function check_license() {
		$api_params = [
			'edd_action'  => 'check_license',
			'license'     => $this->get_license_key(),
			'item_id'     => self::ID,
			'item_name'   => rawurlencode( 'Content Control Pro' ),
			'url'         => home_url(),
			'environment' => function_exists( 'wp_get_environment_type' ) ? wp_get_environment_type() : 'production',
		];

		// Call the custom API.
		$response = wp_remote_post(
			self::API_URL,
			[
				'timeout'   => 15,
				'sslverify' => false,
				'body'      => $api_params,
			]
		);

		if ( is_wp_error( $response ) ) {
			throw new \Exception( esc_html( $response->get_error_message() ) );
		}

		$license_status = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( empty( $license_status ) ) {
			return [];
		}

		return $license_status;
	}

	/**
	 * Activate license.
	 *
	 * @param string $key License key.
	 *
	 * @return array<string,mixed> License status data.
	 *
	 * @throws \Exception If there is an error.
	 */
	public function activate_license( $key = null ) {
		if ( ! empty( $key ) ) {
			$this->update_license_key( $key );
		} else {
			$key = $this->get_license_key();
		}

		$api_params = [
			'edd_action'  => 'activate_license',
			'license'     => $key,
			'item_id'     => self::ID,
			'url'         => home_url(),
			'environment' => function_exists( 'wp_get_environment_type' ) ? wp_get_environment_type() : 'production',
		];

		// Call the custom API.
		$response = wp_remote_post(
			self::API_URL,
			[
				'timeout'   => 15,
				'sslverify' => false,
				'body'      => $api_params,
			]
		);

		// Make sure the response came back okay.
		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
			if ( is_wp_error( $response ) ) {
				$message = $response->get_error_message();
			} else {
				$message = __( 'An error occurred, please try again.', 'content-control' );
			}

			throw new \Exception( esc_html( $message ) );
		}

		$license_status = json_decode( wp_remote_retrieve_body( $response ), true );

		$this->update_license_status( $license_status );

		if ( $this->is_license_active() ) {
			if ( ! \get_option( 'content_control_pro_activation_date', false ) ) {
				\update_option( 'content_control_pro_activation_date', time() );
			}
		}

		return $this->get_license_status();
	}

	/**
	 * Deactivate license.
	 *
	 * @return array<string,mixed> License status data.
	 *
	 * @throws \Exception If there is an error.
	 */
	public function deactivate_license() {
		$api_params = [
			'edd_action'  => 'deactivate_license',
			'license'     => $this->get_license_key(),
			'item_id'     => self::ID,
			'item_name'   => rawurlencode( 'Content Control' ),
			'url'         => home_url(),
			'environment' => function_exists( 'wp_get_environment_type' ) ? wp_get_environment_type() : 'production',
		];

		// Call the custom API.
		$response = wp_remote_post(
			self::API_URL,
			[
				'timeout'   => 15,
				'sslverify' => false,
				'body'      => $api_params,
			]
		);

		// Make sure the response came back okay.
		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
			if ( is_wp_error( $response ) ) {
				$message = $response->get_error_message();
			} else {
				$message = __( 'An error occurred, please try again.', 'content-control' );
			}

			throw new \Exception( esc_html( $message ) );
		}

		$license_status = json_decode( wp_remote_retrieve_body( $response ), true );

		$this->update_license_status( $license_status );

		return $license_status;
	}

	/**
	 * Convert license error to human readable message.
	 *
	 * @param array<string,mixed> $license_status License status data.
	 *
	 * @return string
	 */
	public function get_license_error_message( $license_status ) {
		switch ( $license_status['error'] ) {
			case 'expired':
				$message = sprintf(
					/* translators: the license key expiration date */
					__( 'Your license key expired on %s.', 'content-control' ),
					date_i18n( \get_option( 'date_format' ), strtotime( $license_status['expires'], time() ) )
				);
				break;

			case 'disabled':
			case 'revoked':
				$message = __( 'Your license key has been disabled.', 'content-control' );
				break;

			case 'missing':
					$message = __( 'Invalid license.', 'content-control' );
				break;

			case 'invalid':
			case 'site_inactive':
				$message = __( 'Your license is not active for this URL.', 'content-control' );
				break;

			case 'item_name_mismatch':
				$message = sprintf(
					/* translators: the plugin name */
					__( 'This appears to be an invalid license key for %s.', 'content-control' ),
					__( 'Content Control', 'content-control' )
				);
				break;

			case 'no_activations_left':
				$message = __( 'Your license key has reached its activation limit.', 'content-control' );
				break;

			default:
				$message = __( 'An error occurred, please try again.', 'content-control' );
				break;
		}

		return $message;
	}

	/**
	 * Remove license.
	 *
	 * @return void
	 */
	public function remove_license() {
		try {
			$deactivated = $this->deactivate_license();
		} catch ( \Exception $e ) {
			$deactivated = [];
		}

		if ( ! empty( $deactivated['license'] ) && 'active' !== $deactivated['license'] ) {
			\delete_option( self::OPTION_KEY );
		}
	}

	/**
	 * Check if license is active.
	 *
	 * @return bool
	 */
	public function is_license_active() {
		$license_status = $this->get_license_status();

		if ( empty( $license_status ) ) {
			return false;
		}

		return 'valid' === $license_status['license'];
	}
}