Jump to content

css-sanitizer/zh

From mediawiki.org
This page is a translated version of the page Css-sanitizer and the translation is 26% complete.

CSS Sanitizer 函式庫以PHP實作 CSS token轉化器、語法解析器、及語法匹配器,其設計主要遵循以下規範:CSS 語法模組第 3 版候選建議書(2014年2月20 日)CSS值與單位模組第3版,以及 CSS 選擇器第3版 語法規範。 它還提供一款淨化器(StylePropertySanitizer),能識別多種CSS3模組

此函式庫是為在MediaWiki的Extension:TemplateStyles(模板样式) 模組中使用而開發。

用法

.php
use Wikimedia\CSS\Parser\Parser;
use Wikimedia\CSS\Sanitizer\StylesheetSanitizer;

/** Parse a stylesheet from a string **/

$parser = Parser::newFromString( $cssText );
$stylesheet = $parser->parseStylesheet();

/** Report any parser errors **/

foreach ( $parser->getParseErrors() as list( $code, $line, $pos ) ) {
	// $code is a string that should be suitable as a key for an i18n library.
	// See errors.md for details.
	$error = lookupI18nMessage( "css-parse-error-$code" );
	echo "Parse error: $error at line $line character $pos\n";
}

/** Apply sanitization to the stylesheet **/

// If you need to customize the defaults, copy the code of this method and modify it.
$sanitizer = StylesheetSanitizer::newDefault();
$newStylesheet = $sanitizer->sanitize( $stylesheet );

/** Report any sanitizer errors **/

foreach ( $sanitizer->getSanitizationErrors() as list( $code, $line, $pos ) ) {
	// $code is a string that should be suitable as a key for an i18n library.
	// See errors.md for details.
	$error = lookupI18nMessage( "css-sanitization-error-$code" );
	echo "Sanitization error: $error at line $line character $pos\n";
}

/** Convert the sanitized stylesheet back to text **/

$newText = (string)$newStylesheet;

// Or if you'd rather have it minified too
$minifiedText = Wikimedia\CSS\Util::stringify( $newStylesheet, [ 'minify' => true ] );

历史

We required a CSS sanitizer with several properties:

  • Strict parsing according to modern standards.
  • Includes line and character position for all errors.
  • Configurable to limit unsafe constructs such as external URL references.
  • Errors are easily localizable.

We could not find a library that fit these requirements, so we created one.

外部链接