Config.php 13.5 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
<?php
/**
 * Class Config
 *
 * @package ContentControl\Vendor\TrustedLogin\Client
 *
 * @copyright 2021 Katz Web Services, Inc.
 *
 * @license GPL-2.0-or-later
 * Modified by code-atlantic on 21-June-2024 using {@see https://github.com/BrianHenryIE/strauss}.
 */

namespace ContentControl\Vendor\TrustedLogin;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use ArrayAccess;
use \Exception;
use \WP_Error;

final class Config {

	/**
	 * @var string[] These namespaces cannot be used, lest they result in confusion.
	 */
	private static $reserved_namespaces = array( 'trustedlogin', 'client', 'vendor', 'admin', 'wordpress' );

	/**
	 * @var array Default settings values
	 * @since 1.0.0
	 * @link https://www.trustedlogin.com/configuration/ Read the configuration settings documentation
	 */
	private $default_settings = array(
		'auth'           => array(
			'api_key'     => null,
			'license_key' => null,
		),
		'caps'           => array(
			'add'    => array(),
			'remove' => array(),
		),
		'decay'          => WEEK_IN_SECONDS,
		'logging'        => array(
			'enabled'   => false,
			'directory' => null,
			'threshold' => 'notice',
			'options'   => array(
				'extension'      => 'log',
				'dateFormat'     => 'Y-m-d G:i:s.u',
				'filename'       => null, // Overridden in Logging.php
				'flushFrequency' => false,
				'logFormat'      => false,
				'appendContext'  => true,
			),
		),
		'menu'           => array(
			'slug'     => null,
			'title'    => null,
			'priority' => null,
			'icon_url' => '',
			'position' => null,
		),
		'paths'          => array(
			'css' => null,
			'js'  => null, // Default is defined in get_default_settings()
		),
		'reassign_posts' => true,
		'require_ssl'    => true,
		'role'           => 'editor',
		'clone_role'     => true,
		'terms_of_service' => array(
			'url' => null,
		),
		'vendor'         => array(
			'namespace'             => null,
			'title'                 => null,
			'email'                 => null,
			'website'               => null,
			'support_url'           => null,
			'display_name'          => null,
			'logo_url'              => null,
			'about_live_access_url' => null,
		),
		'webhook'        => array(
			'url'           => null,
			'debug_data'    => false,
			'create_ticket' => false,
		),
	);

	/**
	 * @var array $settings Configuration array after parsed and validated
	 * @since 1.0.0
	 */
	private $settings = array();

	/**
	 * Config constructor.
	 *
	 * @param array $settings
	 *
	 * @throws \Exception
	 */
	public function __construct( array $settings = array() ) {

		if ( empty( $settings ) ) {
			throw new Exception( 'Developer: TrustedLogin requires a configuration array. See https://trustedlogin.com/configuration/ for more information.', 400 );
		}

		$this->settings = $settings;
	}


	/**
	 * @return true|\WP_Error[]
	 * @throws \Exception
	 *
	 */
	public function validate() {

		if ( in_array( __NAMESPACE__, array(
				'ReplaceMe',
				'ReplaceMe\GravityView\TrustedLogin',
			) ) && ! defined( 'TL_DOING_TESTS' ) ) {
			throw new Exception( 'Developer: make sure to change the namespace for the TrustedLogin class. See https://trustedlogin.com/configuration/ for more information.', 501 );
		}

		$errors = array();

		if ( ! isset( $this->settings['auth']['api_key'] ) ) {
			$errors[] = new \WP_Error( 'missing_configuration', 'You need to set an API key. Get yours at https://app.trustedlogin.com' );
		}

		if ( isset( $this->settings['vendor']['website'] ) ) {
			if ( 'https://www.example.com' === $this->settings['vendor']['website'] && ! defined( 'TL_DOING_TESTS' ) ) {
				$errors[] = new \WP_Error( 'missing_configuration', 'You need to configure the "website" URL to point to the URL where the Vendor plugin is installed.' );
			}
		}

		foreach ( array( 'namespace', 'title', 'website', 'support_url', 'email' ) as $required_vendor_field ) {
			if ( ! isset( $this->settings['vendor'][ $required_vendor_field ] ) ) {
				$errors[] = new \WP_Error( 'missing_configuration', sprintf( 'Missing required configuration: `vendor/%s`', $required_vendor_field ) );
			}
		}

		if ( isset( $this->settings['decay'] ) ) {
			if ( ! is_int( $this->settings['decay'] ) ) {
				$errors[] = new \WP_Error( 'invalid_configuration', 'Decay must be an integer (number of seconds).' );
			} elseif ( $this->settings['decay'] > MONTH_IN_SECONDS ) {
				$errors[] = new \WP_Error( 'invalid_configuration', 'Decay must be less than or equal to 30 days.' );
			} elseif ( $this->settings['decay'] < DAY_IN_SECONDS ) {
				$errors[] = new \WP_Error( 'invalid_configuration', 'Decay must be greater than 1 day.' );
			}
		}

		if ( isset( $this->settings['vendor']['namespace'] ) ) {

			/**
			 * This seems like a reasonable max limit on the ns length.
			 *
			 * @see https://developer.wordpress.org/reference/functions/set_transient/#more-information
			 */
			if ( strlen( $this->settings['vendor']['namespace'] ) > 96 ) {
				$errors[] = new \WP_Error( 'invalid_configuration', 'Namespace length must be shorter than 96 characters.' );
			}

			if ( in_array( strtolower( $this->settings['vendor']['namespace'] ), self::$reserved_namespaces, true ) ) {
				$errors[] = new \WP_Error( 'invalid_configuration', 'The defined namespace is reserved.' );
			}
		}

		if ( isset( $this->settings['vendor']['email'] ) && ! filter_var( $this->settings['vendor']['email'], FILTER_VALIDATE_EMAIL ) ) {
			$errors[] = new \WP_Error( 'invalid_configuration', 'An invalid `vendor/email` setting was passed to the TrustedLogin Client.' );
		}

		// TODO: Add ns collision check?

		foreach ( array( 'webhook/url', 'webhook_url', 'vendor/support_url', 'vendor/website' ) as $settings_key ) {
			$value = $this->get_setting( $settings_key, '', $this->settings );
			$url   = wp_kses_bad_protocol( $value, array( 'http', 'https' ) );
			if ( $value && ! filter_var( $url, FILTER_VALIDATE_URL ) ) {
				$errors[] = new \WP_Error(
					'invalid_configuration',
					sprintf( 'An invalid `%s` setting was passed to the TrustedLogin Client: %s',
						$settings_key,
						print_r( $this->get_setting( $settings_key, null, $this->settings ), true )
					)
				);
			}
		}

		if ( false !== $this->get_setting( 'clone_role', true, $this->settings ) ) {
			$added_caps = $this->get_setting( 'caps/add', array(), $this->settings );

			foreach ( SupportRole::$prevented_caps as $invalid_cap ) {
				if ( array_key_exists( $invalid_cap, $added_caps ) ) {
					$errors[] = new \WP_Error( 'invalid_configuration', 'TrustedLogin users cannot be allowed to: ' . $invalid_cap );
				}
			}
		} else {
			$added_caps = $this->get_setting( 'caps/add', array(), $this->settings );
			$removed_caps = $this->get_setting( 'caps/remove', array(), $this->settings );

			$added_caps = array_filter( $added_caps );
			$removed_caps = array_filter( $removed_caps );

			if ( ! empty( $added_caps ) || ! empty( $removed_caps ) ) {
				$errors[] = new \WP_Error( 'invalid_configuration', 'When `clone_role` is disabled, TrustedLogin cannot add or remove capabilities.' );
			}
		}

		if ( $errors ) {
			$error_text = array();
			foreach ( $errors as $error ) {
				if ( is_wp_error( $error ) ) {
					$error_text[] = $error->get_error_message();
				}
			}

			$exception_text = 'Invalid TrustedLogin Configuration. Learn more at https://www.trustedlogin.com/configuration/';
			$exception_text .= "\n- " . implode( "\n- ", $error_text );

			throw new Exception( $exception_text, 406 );
		}

		return true;
	}

	/**
	 * Returns a timestamp that is the current time + decay time setting
	 *
	 * Note: This is a server timestamp, not a WordPress timestamp
	 *
	 * @param int $decay_time If passed, override the `decay` setting
	 * @param bool $gmt Whether to use server time (false) or GMT time (true). Default: false.
	 *
	 * @return int|false Timestamp in seconds. Default is WEEK_IN_SECONDS from creation (`time()` + 604800). False if no expiration.
	 */
	public function get_expiration_timestamp( $decay_time = null, $gmt = false ) {

		if ( is_null( $decay_time ) ) {
			$decay_time = $this->get_setting( 'decay' );
		}

		if ( 0 === $decay_time ) {
			return false;
		}

		$time = current_time( 'timestamp', $gmt );

		return $time + (int) $decay_time;
	}

	/**
	 * Returns the display name for the vendor; otherwise, the title
	 *
	 * @return string
	 */
	public function get_display_name() {
		return $this->get_setting( 'vendor/display_name', $this->get_setting( 'vendor/title', '' ) );
	}

	/**
	 * Validate and initialize settings array passed to the Client contructor
	 *
	 * @param array|string $config Configuration array or JSON-encoded configuration array
	 *
	 * @return bool|WP_Error[] true: Initialization succeeded; array of WP_Error objects if there are any issues.
	 */
	protected function parse_settings( $config ) {

		if ( is_string( $config ) ) {
			$config = json_decode( $config, true );
		}

		if ( ! is_array( $config ) || empty( $config ) ) {
			return array( new \WP_Error( 'empty_configuration', 'Configuration array cannot be empty. See https://www.trustedlogin.com/configuration/ for more information.' ) );
		}

		$defaults = $this->get_default_settings();

		$filtered_config = array_filter( $config, array( $this, 'is_not_null' ) );

		return shortcode_atts( $defaults, $filtered_config );
	}

	/**
	 * Filter out null input values
	 *
	 * @internal Used for parsing settings
	 *
	 * @param mixed $input Input to test against.
	 *
	 * @return bool True: not null. False: null
	 */
	public function is_not_null( $input ) {
		return ! is_null( $input );
	}

	/**
	 * Gets the default settings for the Client and define dynamic defaults (like paths/css and paths/js)
	 *
	 * @since 1.0.0
	 *
	 * @return array Array of default settings.
	 */
	public function get_default_settings() {

		$default_settings = $this->default_settings;

		$default_settings['paths']['css'] = plugin_dir_url( __FILE__ ) . 'assets/trustedlogin.css';
		$default_settings['paths']['js']  = plugin_dir_url( __FILE__ ) . 'assets/trustedlogin.js';

		return $default_settings;
	}

	/**
	 * @return string Vendor namespace, sanitized with dashes
	 */
	public function ns() {

		static $namespace;

		if ( ! $namespace ) {
			$ns = $this->get_setting( 'vendor/namespace' );

			$namespace = sanitize_title_with_dashes( $ns );
		}

		return $namespace;
	}

	/**
	 * Helper Function: Get a specific setting or return a default value.
	 *
	 * @since 1.0.0
	 *
	 * @param string $key The setting to fetch, nested results are delimited with forward slashes (eg vendor/name => settings['vendor']['name'])
	 * @param mixed $default - if no setting found or settings not init, return this value.
	 * @param array $settings Pass an array to fetch value for instead of using the default settings array
	 *
	 * @return string|array
	 */
	public function get_setting( $key, $default = null, $settings = array() ) {

		if ( empty( $settings ) ) {
			$settings = $this->settings;
		}

		if ( is_null( $default ) ) {
			$default = $this->get_multi_array_value( $this->get_default_settings(), $key );
		}

		if ( empty( $settings ) || ! is_array( $settings ) ) {
			return $default;
		}

		return $this->get_multi_array_value( $settings, $key, $default );
	}

	/**
	 * Returns the full settings array
	 *
	 * @since 1.5.0
	 *
	 * @return array Settings as passed to the constructor.
	 */
	public function get_settings() {
		return $this->settings;
	}

	/**
	 * Gets a specific property value within a multidimensional array.
	 *
	 * @param array $array The array to search in.
	 * @param string $name The name of the property to find.
	 * @param string $default Optional. Value that should be returned if the property is not set or empty. Defaults to null.
	 *
	 * @return null|string|mixed The value
	 */
	private function get_multi_array_value( $array, $name, $default = null ) {

		if ( ! is_array( $array ) && ! ( is_object( $array ) && $array instanceof ArrayAccess ) ) {
			return $default;
		}

		$names = explode( '/', $name );
		$val   = $array;
		foreach ( $names as $current_name ) {
			$val = $this->get_array_value( $val, $current_name, $default );
		}

		return $val;
	}

	/**
	 * Get a specific property of an array without needing to check if that property exists.
	 *
	 * Provide a default value if you want to return a specific value if the property is not set.
	 *
	 * @param array $array Array from which the property's value should be retrieved.
	 * @param string $prop Name of the property to be retrieved.
	 * @param string $default Optional. Value that should be returned if the property is not set or empty. Defaults to null.
	 *
	 * @return null|string|mixed The value
	 */
	private function get_array_value( $array, $prop, $default = null ) {
		if ( ! is_array( $array ) && ! ( is_object( $array ) && $array instanceof ArrayAccess ) ) {
			return $default;
		}

		// Directly fetch the value if it exists, otherwise use the default.
		$value = isset( $array[ $prop ] ) ? $array[ $prop ] : $default;

		// Special handling for zero and false.
		if ( 0 === $value || false === $value ) {
			return $value;
		}

		// If the value is empty and a default is provided, use the default.
		if ( empty( $value ) && null !== $default ) {
			return $default;
		}

		return $value;
	}

	/**
	 * Checks whether SSL requirements are met.
	 *
	 * @since 1.0.0
	 *
	 * @return bool  Whether the vendor-defined SSL requirements are met.
	 */
	public function meets_ssl_requirement() {

		$return = true;

		if ( $this->get_setting( 'require_ssl', true ) && ! is_ssl() ) {
			$return = false;
		}

		/**
		 * @internal Do not rely on this!!!!
		 * @todo Remove this
		 *
		 * @param bool $return Does this site meet the SSL requirement?
		 */
		return apply_filters( 'trustedlogin/' . $this->ns() . '/meets_ssl_requirement', $return );
	}

}