CoreFiles by mySites.guru
class-wp-icons-registry.php583 lines, 15,288 bytes, from wordpress-7.2-beta3.zip
Raw History Compare with 7.2-beta2
md5
8b4ea2a85e185ca89ea3135ef24a6841
sha1
b19f190c61f15bea76f30180fc7d174f9f302d70
sha256
fc9b63bad0d93ee8d0953ec744b63c4a909a097efa3c6fabcc96fde635b5e452
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
<?php
/**
 * Icons API: WP_Icons_Registry class
 *
 * @package WordPress
 * @since 7.0.0
 */

/**
 * Core class used for interacting with registered icons.
 *
 * @since 7.0.0
 */
class WP_Icons_Registry {
	/**
	 * Registered icons array.
	 *
	 * @since 7.0.0
	 * @var array[]
	 */
	protected $registered_icons = array();

	/**
	 * Resolved path of the core icon library directory.
	 *
	 * @since 7.2.0
	 * @var string|false|null
	 */
	private $core_icon_library_directory = null;

	/**
	 * Container for the main instance of the class.
	 *
	 * @since 7.0.0
	 * @var WP_Icons_Registry|null
	 */
	protected static $instance = null;

	/**
	 * Names of the icons that replace Dashicons, keyed by Dashicon class name.
	 *
	 * Built from the icon library manifest on first use.
	 *
	 * @since 7.2.0
	 * @var array<string, string>|null
	 */
	protected $dashicon_replacements = null;

	/**
	 * Constructor.
	 *
	 * WP_Icons_Registry is a singleton class, so keep this protected.
	 *
	 * Icons are populated via `_wp_register_default_icons()` during the
	 * `init` action. Third-party icons can be registered via
	 * {@see wp_register_icon()} once their collection is registered.
	 *
	 * @since 7.0.0
	 */
	protected function __construct() {}

	/**
	 * Registers an icon.
	 *
	 * @since 7.0.0
	 * @since 7.1.0 The icon name must be namespaced in the form "collection/icon-name".
	 * @since 7.2.0 Added the `keywords` property.
	 *
	 * @param string $icon_name       Namespaced icon name in the form "collection/icon-name"
	 *                                (e.g. "core/arrow-left").
	 * @param array  $icon_properties {
	 *     List of properties for the icon.
	 *
	 *     @type string   $label     Required. A human-readable label for the icon.
	 *     @type string   $content   Optional. SVG markup for the icon.
	 *                               If not provided, the content will be retrieved from the `file_path` if set.
	 *                               If both `content` and `file_path` are not set, the icon will not be registered.
	 *     @type string   $file_path Optional. The full path to the file containing the icon content.
	 *     @type string[] $keywords  Optional. Additional search terms for the icon, matched by
	 *                               `get_registered_icons()` alongside the name and label.
	 * }
	 * @return bool True if the icon was registered with success and false otherwise.
	 *
	 * @phpstan-param lowercase-string&non-falsy-string $icon_name
	 */
	public function register( $icon_name, $icon_properties ) {
		if ( ! isset( $icon_name ) || ! is_string( $icon_name ) ) {
			_doing_it_wrong(
				__METHOD__,
				__( 'Icon name must be a string.' ),
				'7.0.0'
			);
			return false;
		}

		// Require a namespaced name in the form "collection/icon-name".
		if ( ! str_contains( $icon_name, '/' ) ) {
			_doing_it_wrong(
				__METHOD__,
				__( 'Icon name must be namespaced in the form "collection/icon-name".' ),
				'7.1.0'
			);
			return false;
		}

		// Split the namespaced name into a collection slug and an unqualified icon name.
		list( $collection, $unqualified_name ) = explode( '/', $icon_name, 2 );

		if ( preg_match( '/[A-Z]/', $unqualified_name ) ) {
			_doing_it_wrong(
				__METHOD__,
				__( 'Icon names must not contain uppercase characters.' ),
				'7.1.0'
			);
			return false;
		}

		if ( ! preg_match( '/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/', $unqualified_name ) ) {
			_doing_it_wrong(
				__METHOD__,
				__( 'Icon names must start and end with a lowercase letter or digit and contain only lowercase letters, digits, hyphens, and underscores.' ),
				'7.1.0'
			);
			return false;
		}

		$allowed_keys = array_fill_keys( array( 'label', 'content', 'file_path', 'keywords' ), 1 );
		foreach ( array_keys( $icon_properties ) as $key ) {
			if ( ! array_key_exists( $key, $allowed_keys ) ) {
				_doing_it_wrong(
					__METHOD__,
					sprintf(
						/* translators: %s: The name of a user-provided key. */
						__( 'Invalid icon property: "%s".' ),
						$key
					),
					'7.0.0'
				);
				return false;
			}
		}

		if ( ! WP_Icon_Collections_Registry::get_instance()->is_registered( $collection ) ) {
			_doing_it_wrong(
				__METHOD__,
				sprintf(
					/* translators: %s: Icon collection slug. */
					__( 'Icon collection "%s" is not registered.' ),
					$collection
				),
				'7.1.0'
			);
			return false;
		}

		if ( ! isset( $icon_properties['label'] ) || ! is_string( $icon_properties['label'] ) ) {
			_doing_it_wrong(
				__METHOD__,
				__( 'Icon label must be a string.' ),
				'7.0.0'
			);
			return false;
		}

		if ( array_key_exists( 'keywords', $icon_properties ) ) {
			if ( ! is_array( $icon_properties['keywords'] ) ) {
				_doing_it_wrong(
					__METHOD__,
					__( 'Icon keywords must be an array of strings.' ),
					'7.2.0'
				);
				return false;
			}

			foreach ( $icon_properties['keywords'] as $keyword ) {
				if ( ! is_string( $keyword ) ) {
					_doing_it_wrong(
						__METHOD__,
						__( 'Icon keywords must be an array of strings.' ),
						'7.2.0'
					);
					return false;
				}
			}
		}

		if (
			( ! isset( $icon_properties['content'] ) && ! isset( $icon_properties['file_path'] ) ) ||
			( isset( $icon_properties['content'] ) && isset( $icon_properties['file_path'] ) )
		) {
			_doing_it_wrong(
				__METHOD__,
				__( 'Icons must provide either `content` or `file_path`.' ),
				'7.0.0'
			);
			return false;
		}

		if ( isset( $icon_properties['content'] ) ) {
			if ( ! is_string( $icon_properties['content'] ) ) {
				_doing_it_wrong(
					__METHOD__,
					__( 'Icon content must be a string.' ),
					'7.0.0'
				);
				return false;
			}

			$sanitized_icon_content = $this->sanitize_icon_content( $icon_properties['content'] );
			if ( empty( $sanitized_icon_content ) ) {
				_doing_it_wrong(
					__METHOD__,
					__( 'Icon content does not contain valid SVG markup.' ),
					'7.0.0'
				);
				return false;
			}

			$icon_properties['content'] = $sanitized_icon_content;
		}

		$qualified_name = $collection . '/' . $unqualified_name;

		if ( $this->is_registered( $qualified_name ) ) {
			_doing_it_wrong(
				__METHOD__,
				__( 'Icon is already registered.' ),
				'7.1.0'
			);
			return false;
		}

		$icon = array_merge(
			$icon_properties,
			array(
				'name'       => $qualified_name,
				'collection' => $collection,
			)
		);

		$this->registered_icons[ $qualified_name ] = $icon;

		return true;
	}

	/**
	 * Unregisters an icon.
	 *
	 * @since 7.1.0
	 *
	 * @param string $icon_name Namespaced icon name in the form "collection/icon-name"
	 *                          (e.g. "core/arrow-left").
	 * @return bool True if the icon was unregistered successfully, false otherwise.
	 */
	public function unregister( $icon_name ) {
		if ( ! $this->is_registered( $icon_name ) ) {
			_doing_it_wrong(
				__METHOD__,
				sprintf(
					/* translators: %s: Icon name. */
					__( 'Icon "%s" is not registered.' ),
					$icon_name
				),
				'7.1.0'
			);
			return false;
		}

		unset( $this->registered_icons[ $icon_name ] );
		return true;
	}

	/**
	 * Builds the allowed attribute list for wp_kses() from attribute names.
	 *
	 * @since 7.2.0
	 *
	 * @param non-falsy-string ...$attribute_names Attribute names to allow.
	 * @return array<non-falsy-string, true> Attribute names mapped to true.
	 */
	private function get_allowed_attribute_list( ...$attribute_names ): array {
		return array_fill_keys( $attribute_names, true );
	}

	/**
	 * Sanitizes the icon SVG content.
	 *
	 * @since 7.0.0
	 *
	 * @param string $icon_content The icon SVG content to sanitize.
	 * @return string The sanitized icon SVG content.
	 */
	protected function sanitize_icon_content( $icon_content ) {
		$stroke_attributes = $this->get_allowed_attribute_list(
			'style',
			'stroke',
			'stroke-width',
			'stroke-linecap',
			'stroke-linejoin',
			'stroke-miterlimit',
			'vector-effect',
		);

		$allowed_tags = array(
			'svg'     => array_merge(
				$this->get_allowed_attribute_list(
					'class',
					'xmlns',
					'width',
					'height',
					'viewbox',
					'aria-hidden',
					'role',
					'focusable',
					'fill',
					'fill-rule',
					'clip-rule',
				),
				$stroke_attributes
			),
			'path'    => array_merge(
				$this->get_allowed_attribute_list(
					'fill',
					'fill-rule',
					'clip-rule',
					'd',
					'opacity',
					'transform',
				),
				$stroke_attributes
			),
			'polygon' => array_merge(
				$this->get_allowed_attribute_list(
					'fill',
					'fill-rule',
					'clip-rule',
					'points',
					'transform',
					'focusable',
				),
				$stroke_attributes
			),
			'rect'    => array_merge(
				$this->get_allowed_attribute_list(
					'fill',
					'fill-rule',
					'clip-rule',
					'x',
					'y',
					'width',
					'height',
					'rx',
					'ry',
					'transform',
				),
				$stroke_attributes
			),
			'circle'  => array_merge(
				$this->get_allowed_attribute_list(
					'fill',
					'fill-rule',
					'clip-rule',
					'cx',
					'cy',
					'r',
					'transform',
				),
				$stroke_attributes
			),
		);
		return wp_kses( $icon_content, $allowed_tags );
	}

	/**
	 * Retrieves the content of a registered icon.
	 *
	 * @since 7.0.0
	 * @since 7.2.0 Core icons skip sanitization.
	 *
	 * @param string $icon_name Icon name including namespace.
	 * @return string|null The content of the icon, if found.
	 */
	protected function get_content( $icon_name ) {
		if ( ! isset( $this->registered_icons[ $icon_name ]['content'] ) ) {
			$file_path  = $this->registered_icons[ $icon_name ]['file_path'] ?? '';
			$is_stringy = is_string( $file_path ) || ( is_object( $file_path ) && method_exists( $file_path, '__toString' ) );
			$icon_path  = $is_stringy ? realpath( (string) $file_path ) : false;

			if (
				! is_string( $icon_path ) ||
				! str_ends_with( $icon_path, '.svg' ) ||
				! is_file( $icon_path ) ||
				! is_readable( $icon_path )
			) {
				wp_trigger_error(
					__METHOD__,
					__( 'Icon file is missing or unreadable.' )
				);
				return null;
			}

			$content = file_get_contents( $icon_path );

			// Core icons are trusted, so skip the costly sanitization.
			if ( ! $this->is_core_icon_file( $icon_path ) ) {
				$content = $this->sanitize_icon_content( $content );
			}

			if ( empty( $content ) ) {
				wp_trigger_error(
					__METHOD__,
					__( 'Icon content does not contain valid SVG markup.' )
				);
				return null;
			}

			$this->registered_icons[ $icon_name ]['content'] = $content;
		}
		return $this->registered_icons[ $icon_name ]['content'];
	}

	/**
	 * Determines whether an icon file is a core icon.
	 *
	 * @since 7.2.0
	 *
	 * @param string $icon_path Icon file path, resolved with `realpath()`.
	 * @return bool Whether the file is in the core icon library.
	 */
	private function is_core_icon_file( $icon_path ) {
		if ( null === $this->core_icon_library_directory ) {
			$this->core_icon_library_directory = realpath( ABSPATH . WPINC . '/images/icon-library' );
		}

		return is_string( $this->core_icon_library_directory ) && str_starts_with( $icon_path, $this->core_icon_library_directory . DIRECTORY_SEPARATOR );
	}

	/**
	 * Retrieves an array containing the properties of a registered icon.
	 *
	 * @since 7.0.0
	 *
	 * @param string $icon_name Icon name including namespace.
	 * @return array|null Registered icon properties or `null` if the icon is not registered.
	 */
	public function get_registered_icon( $icon_name ) {
		if ( ! $this->is_registered( $icon_name ) ) {
			return null;
		}

		$icon              = $this->registered_icons[ $icon_name ];
		$icon['content'] ??= $this->get_content( $icon_name );

		return $icon;
	}

	/**
	 * Determines whether an icon matches a search term.
	 *
	 * The term is matched case-insensitively against the icon's name, its label,
	 * and any of its keywords.
	 *
	 * @since 7.2.0
	 *
	 * @param array  $icon   Registered icon properties.
	 * @param string $search Search term.
	 * @return bool True if the icon matches the search term, false otherwise.
	 */
	protected function icon_matches_search( $icon, $search ) {
		if ( false !== stripos( $icon['name'], $search ) ) {
			return true;
		}

		if ( false !== stripos( $icon['label'], $search ) ) {
			return true;
		}

		foreach ( $icon['keywords'] ?? array() as $keyword ) {
			if ( false !== stripos( $keyword, $search ) ) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Retrieves all registered icons.
	 *
	 * @since 7.0.0
	 * @since 7.1.0 Search also matches icon labels.
	 * @since 7.2.0 Search also matches icon keywords.
	 *
	 * @param string $search Optional. Search term matched against each icon's name,
	 *                       label, and keywords. Default empty string, which returns
	 *                       every registered icon.
	 * @return array[] Array of arrays containing the registered icon properties.
	 */
	public function get_registered_icons( $search = '' ) {
		$icons = array();

		foreach ( $this->registered_icons as $icon ) {
			if ( ! empty( $search ) && ! $this->icon_matches_search( $icon, $search ) ) {
				continue;
			}

			$icon['content'] ??= $this->get_content( $icon['name'] );
			$icons[]           = $icon;
		}

		return $icons;
	}

	/**
	 * Checks if an icon is registered.
	 *
	 * @since 7.0.0
	 *
	 * @param string $icon_name Icon name including namespace.
	 * @return bool True if the icon is registered, false otherwise.
	 */
	public function is_registered( $icon_name ) {
		return isset( $this->registered_icons[ $icon_name ] );
	}

	/**
	 * Returns the name of the icon that replaces a Dashicon in the admin interface.
	 *
	 * The replacements come from the `dashicons` property of the `core-admin`
	 * icons in the icon library manifest.
	 *
	 * @since 7.2.0
	 *
	 * @param string $dashicon Dashicon class name, such as `dashicons-admin-post`.
	 * @return string|null Namespaced name of the replacement icon, such as `core-admin/pin`,
	 *                     or null if the Dashicon has no replacement or the replacement
	 *                     is not registered.
	 */
	public function get_admin_icon_name_for_dashicon( $dashicon ) {
		if ( ! is_string( $dashicon ) ) {
			return null;
		}

		if ( null === $this->dashicon_replacements ) {
			$this->dashicon_replacements = array();

			$manifest_path = ABSPATH . WPINC . '/assets/icon-library-manifest.php';
			$manifest      = is_readable( $manifest_path ) ? include $manifest_path : array();

			foreach ( is_array( $manifest ) ? $manifest : array() as $icon_name => $icon_data ) {
				if (
					empty( $icon_data['dashicons'] ) ||
					! in_array( 'core-admin', $icon_data['collections'] ?? array(), true )
				) {
					continue;
				}

				foreach ( $icon_data['dashicons'] as $replaced_dashicon ) {
					$this->dashicon_replacements[ $replaced_dashicon ] = 'core-admin/' . $icon_name;
				}
			}
		}

		$icon_name = $this->dashicon_replacements[ $dashicon ] ?? null;

		return null !== $icon_name && $this->is_registered( $icon_name ) ? $icon_name : null;
	}

	/**
	 * Utility method to retrieve the main instance of the class.
	 *
	 * The instance will be created if it does not exist yet.
	 *
	 * @since 7.0.0
	 *
	 * @return WP_Icons_Registry The main instance.
	 */
	public static function get_instance() {
		self::$instance ??= new self();

		return self::$instance;
	}
}

The same content is in 6 releases, WordPress 7.2-beta2 to 7.2-RC2. See them all, or every version of this file.