Prerequisites.php 10.2 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
<?php
/**
 * Prerequisite handler.
 *
 * @package ContentControl\Utils
 */

namespace ContentControl\Plugin;

defined( 'ABSPATH' ) || exit;

/**
 * Prerequisite handler.
 *
 * @version 1.0.0
 */
class Prerequisites {

	/**
	 * Cache accessible across instances.
	 *
	 * @var array<string,array<string,mixed>>
	 */
	public static $cache = [];

	/**
	 * Array of checks to perform.
	 *
	 * @var array{type:string,version:string}[]
	 */
	protected $checks = [];

	/**
	 * Array of detected failures.
	 *
	 * @var array{type:string,version:string}[]
	 */
	protected $failures = [];

	/**
	 * Instantiate prerequisite checker.
	 *
	 * @param array{type:string,version:string}[] $requirements Array of requirements.
	 */
	public function __construct( $requirements = [] ) {
		foreach ( $requirements as $arguments ) {
			switch ( $arguments['type'] ) {
				case 'php':
					$this->checks[] = wp_parse_args(
						$arguments,
						[
							'type'    => 'php',
							'version' => '5.6',
						]
					);
					break;
				// phpcs:ignore WordPress.WP.CapitalPDangit.MisspelledInText
				case 'wordpress':
				case 'wp':
					$this->checks[] = wp_parse_args(
						$arguments,
						[
							'type'    => 'wp',
							'version' => '5.6',
						]
					);
					break;
				case 'plugin':
					$this->checks[] = wp_parse_args(
						$arguments,
						[
							'type'            => 'plugin',
							'slug'            => '',
							'name'            => '',
							'version'         => '',
							'check_installed' => false,
							'dep_label'       => '',
						]
					);
					break;
				default:
					break;
			}
		}
	}

	/**
	 * Check requirements.
	 *
	 * @param boolean $return_on_fail Whether it should stop processing if one fails.
	 *
	 * @return bool
	 */
	public function check( $return_on_fail = false ) {
		$end_result = true;

		foreach ( $this->checks as $check ) {
			$result = $this->check_handler( $check );

			if ( false === $result ) {
				if ( true === $return_on_fail ) {
					return false;
				}

				$end_result = false;
			}
		}

		return $end_result;
	}

	/**
	 * Render notices when appropriate.
	 *
	 * @return void
	 */
	public function setup_notices() {
		add_action( 'admin_notices', [ $this, 'render_notices' ] );
	}

	/**
	 * Handle individual checks by mapping them to methods.
	 *
	 * @param array{type:string,version:string} $check Requirement check arguments.
	 *
	 * @return bool
	 */
	public function check_handler( $check ) {
		return method_exists( $this, 'check_' . $check['type'] ) ? $this->{'check_' . $check['type']}( $check ) : false;
	}

	/**
	 * Report failure notice to the queue.
	 *
	 * @param array{type:string,version:string} $check_args Array of check arguments.
	 *
	 * @return void
	 */
	public function report_failure( $check_args ) {
		$this->failures[] = $check_args;
	}

	/**
	 * Get a list of failures.
	 *
	 * @return array{type:string,version:string}[]
	 */
	public function get_failures() {
		return $this->failures;
	}

	/**
	 * Check PHP version against args.
	 *
	 * @param array{type:string,version:string} $check_args Array of args.
	 *
	 * @return bool
	 */
	public function check_php( $check_args ) {
		if ( false === version_compare( phpversion(), $check_args['version'], '>=' ) ) {
			$this->report_failure( $check_args );
			return false;
		}

		return true;
	}


	/**
	 * Check PHP version against args.
	 *
	 * @param array{type:string,version:string} $check_args Array of args.
	 *
	 * @return bool
	 */
	public function check_wp( $check_args ) {
		global $wp_version;

		if ( false === version_compare( $wp_version, $check_args['version'], '>=' ) ) {
			$this->report_failure( $check_args );
			return false;
		}

		return true;
	}

	/**
	 * Check plugin requirements.
	 *
	 * @param array{type:string,version:string,name:string,slug:string,version:string,check_installed:bool,dep_label:string} $check_args Array of args.
	 *
	 * @return bool
	 */
	public function check_plugin( $check_args ) {
		$active = $this->plugin_is_active( $check_args['slug'] );

		/**
		 * The following checks are performed in this order for performance reasons.
		 *
		 * We start with most cached option, to least in hopes of a hit early.
		 *
		 * 1. If active and not checking version.
		 * 2. If active and outdated.
		 * 3. If not active and installed.
		 * 4. If not installed
		 */
		if ( true === $active ) {
			// If required version is set & plugin is active, check that first.
			if ( ! empty( $check_args['version'] ) ) {
				$version = $this->get_plugin_data( $check_args['slug'], 'Version' );

				// If its higher than the required version, we can bail now > true.
				if ( version_compare( $version, $check_args['version'], '>=' ) ) {
					return true;
				} else {
					// If not updated, report the failure and bail > false.
					$this->report_failure(
						array_merge(
							$check_args,
							[
								// Report not_updated status.
								'not_updated' => true,
							]
						)
					);
					return false;
				}
			} else {
				// If the plugin is active, with no required version, were done > true.
				return true;
			}
		}

		if ( $check_args['check_installed'] ) {
			// Check if installed, if so the plugin is not activated.
			if ( $check_args['name'] === $this->get_plugin_data( $check_args['slug'], 'Name' ) ) {
				$this->report_failure(
					array_merge(
						$check_args,
						[
							// Report not_activated status.
							'not_activated' => true,
						]
					)
				);
			} else {
				$this->report_failure(
					array_merge(
						$check_args,
						[
							// Report not_installed status.
							'not_installed' => true,
						]
					)
				);
			}
		}

		return false;
	}

	/**
	 * Internally cached get_plugin_data/get_file_data wrapper.
	 *
	 * @param string $slug Plugins `folder/file.php` slug.
	 * @param string $header Specific plugin header needed.
	 * @return mixed
	 */
	private function get_plugin_data( $slug, $header = null ) {
		if ( ! isset( static::$cache['get_plugin_data'][ $slug ] ) ) {
			$headers = \get_file_data( WP_PLUGIN_DIR . '/' . $slug, [
				'Name'    => 'Plugin Name',
				'Version' => 'Version',
			], 'plugin' );

			static::$cache['get_plugin_data'][ $slug ] = $headers;
		}

		$plugin_data = static::$cache['get_plugin_data'][ $slug ];

		if ( empty( $header ) ) {
			return $plugin_data;
		}

		return isset( $plugin_data[ $header ] ) ? $plugin_data[ $header ] : null;
	}

	/**
	 * Check if plugin is active.
	 *
	 * @param string $slug Slug to check for.
	 *
	 * @return bool
	 */
	protected function plugin_is_active( $slug ) {
		$active_plugins = \get_option( 'active_plugins', [] );

		return in_array( $slug, $active_plugins, true );
	}


	/**
	 * Get php error message.
	 *
	 * @param array{type:string,version:string} $failed_check_args Check arguments.
	 *
	 * @return string
	 */
	public function get_php_message( $failed_check_args ) {
		/* translators: 1. Requirement name (WordPress|PHP)., 2. Version Number. */
		$message = __( 'This plugin requires <b>%1$s %2$s</b> or higher in order to run.', 'content-control' );
		return sprintf(
			$message,
			__( 'PHP', 'default' ),
		$failed_check_args['version'] );
	}

	/**
	 * Get wp error message.
	 *
	 * @param array{type:string,version:string} $failed_check_args Check arguments.
	 *
	 * @return string
	 */
	public function get_wp_message( $failed_check_args ) {
		/* translators: 1. Requirement name (WordPress|PHP)., 2. Version Number. */
		$message = __( 'This plugin requires <b>%1$s %2$s</b> or higher in order to run.', 'content-control' );
		return sprintf(
			$message,
			__( 'WordPress', 'default' ),
			$failed_check_args['version']
		);
	}

	/**
	 * Get plugin error message.
	 *
	 * @param array{type:string,version:string,name:string,slug:string,version:string,check_installed:bool,dep_label:string,not_activated?:bool|null,not_updated?:bool|null} $failed_check_args Get helpful error message.
	 *
	 * @return string
	 */
	public function get_plugin_message( $failed_check_args ) {
		$slug = $failed_check_args['slug'];
		// Without file path.
		$short_slug = explode( '/', $slug );
		$short_slug = $short_slug[0];
		$name       = $failed_check_args['name'];
		$dep_label  = $failed_check_args['dep_label'];

		if ( isset( $failed_check_args['not_activated'] ) ) {
			$url  = esc_url( wp_nonce_url( admin_url( 'plugins.php?action=activate&plugin=' . $slug ), 'activate-plugin_' . $slug ) );
			$link = '<a href="' . $url . '">' . __( 'activate it', 'content-control' ) . '</a>';

			$text = sprintf(
				/* translators: 1. Plugin Name, 2. Required Plugin Name, 4. `activate it` link. */
				__( 'The plugin "%1$s" requires %2$s! Please %3$s to continue!', 'content-control' ),
				$dep_label,
				'<strong>' . $name . '</strong>',
				$link
			);
		} elseif ( isset( $failed_check_args['not_updated'] ) ) {
			$url  = esc_url( wp_nonce_url( admin_url( 'update.php?action=upgrade-plugin&plugin=' . $slug ), 'upgrade-plugin_' . $slug ) );
			$link = '<a href="' . $url . '">' . __( 'update it', 'content-control' ) . '</a>';

			$text = sprintf(
				/* translators: 1. Plugin Name, 2. Required Plugin Name, 3. Version number, 4. `update it` link. */
				__( 'The plugin "%1$s" requires %2$s v%3$s or higher! Please %4$s to continue!', 'content-control' ),
				$dep_label,
				'<strong>' . $name . '</strong>',
				'<strong>' . $failed_check_args['version'] . '</strong>',
				$link
			);
		} else {
			$url  = esc_url( wp_nonce_url( self_admin_url( 'update.php?action=install-plugin&plugin=' . $short_slug ), 'install-plugin_' . $short_slug ) );
			$link = '<a href="' . $url . '">' . __( 'install it', 'content-control' ) . '</a>';

			$text = sprintf(
				/* translators: 1. Plugin Name, 2. Required Plugin Name, 3. `install it` link. */
				__( 'The plugin "%1$s" requires %2$s! Please %3$s to continue!', 'content-control' ),
				$dep_label,
				'<strong>' . $name . '</strong>',
				$link
			);
		}

		return $text;
	}

	/**
	 * Render needed admin notices.
	 *
	 * @return void
	 */
	public function render_notices() {
		foreach ( $this->failures as $failure ) {
			$class   = 'notice notice-error';
			$message = method_exists( $this, 'get_' . $failure['type'] . '_message' ) ? $this->{'get_' . $failure['type'] . '_message'}( $failure ) : false;

			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), $message );
		}
	}
}