Help:Extension:Translate/バリデーター

This page is a translated version of the page Help:Extension:Translate/Validators and the translation is 43% complete.

翻訳対象の文字列は、翻訳結果でもそのまま保持されるべきマークアップを含むことがよくあります。 マークアップは特殊な文字を多く含むため、タイプするのが低速・困難になる場合があります。 Translate 拡張機能は、翻訳者がボタンをクリックすると、現在のカーソル位置にマークアップの一部が挿入されるようにすることができます。 さらに、翻訳に特定のマークアップが欠けている場合、Translate 拡張機能は翻訳者に警告するか、または翻訳を拒否できます。これは、エンド ユーザーにメッセージを正しく表示するためには、通常、このようなマークアップが必須だからです。

例えば、

Adapted by %{name} from a work by %{original}

という文字列の中には、%{name}%{original} という 2 つの挿入可能な文字列が存在します。

翻訳者がこれらを追加して翻訳しないと、ソフトウェアを使用するエンド ユーザーには適切なメッセージが表示されません。

翻訳の検証を支援する目的で、MessageValidator フレームワークが追加されました。 翻訳されたメッセージに対してバリデーターが実行され、設定に基づいて警告またはエラー メッセージが翻訳者に表示されます。 警告がある翻訳は保存できますが、エラーがある翻訳は保存できません。 translate-manage の権限がある利用者のみが、エラーのある翻訳を保存できます。

バリデーターを設定する際、必須となるマークアップを識別するための正規表現を定義します。 バリデーターは挿入可能としてマークすることもでき、その場合はそのマークアップを翻訳に追加するためのボタンが翻訳者に表示されます。

カスタム バリデーターを追加でき、これはより専門的な検証をするために必要となります。

設定

以下はバリデーターの設定の要約です。

VALIDATORS:
    # 例 1
    - id: InsertableRegex
      enforce: true
      insertable: true
      params: /\$[a-z0-9]+/
      keymatch:
        - 'untranslated' # 翻訳されていないキーに直接マッチする
        - 
          type: 'wildcard'
          pattern: '*translated*' # 翻訳されたものが含まれるキーにマッチする
    # 例 2
    - id: InsertableRegex
      insertable: true
      params:
          regex: /(?<pre>\[)[^]]+(?<post>\]\([^)]+\))/
          display: $pre $post
          pre: $pre
          post: $post
    # 例 3
    - class: MathJaxMessageValidator
      enforce: true
    # 例 4
    - id: BraceBalance

上記の例では:

  1. InsertableRegex は、カスタム正規表現を受け取って検証を実行できる同梱されているバリデーターです。
  2. MathJaxMessageValidator はカスタム バリデーター クラスです。
  3. BraceBalance は別の同梱されているバリデーターです。

VALIDATORS は配列の書式を使用します。 ここで、各配列の項目で使用されているさまざまなパラメーターを見てみましょう。

パラメーター

プロパティ 説明
id 文字列 同梱/提供済みのバリデーターを使用する場合は、バリデーターの ID を指定します。 class が指定されていない場合は必須です。
class 文字列 カスタム バリデーターを使用する場合は、id の代わりにこのオプションを使用します。 バリデーター クラスの名前を指定します。 上記の設定の例 3 を参照。 AUTOLOAD オプションを使用すると、クラスを読み込めます。 id が指定されていない場合は必須です。
enforce 真偽値 Whether the validator should be enforced. If set to true, and a translation fails validation, an error will be displayed which must be fixed in order to save the translation.
insertable 真偽値 Whether the validator should also be an insertable.
keymatch 配列 With this option it is possible to limit certain validations to certain messages. Keymatch is an array with each option being either a string or a prototype. If it is a string, a direct comparison with the message key is done. 上記の設定の例 1 を参照。
keymatch[i].type 文字列 Type is either regex or wildcard. This is the approach that will be used to check if the message key matches a given pattern.
keymatch[i].pattern 文字列 Pattern is a string that will be used for matching.
params 文字列 / 連想配列 If params is specified as a string, it is used as the regex. 例 1 を参照

In this case if insertable is true,

  1. display is the first value from the regex match.
  2. pre is also the first value from the regex match.
  3. post is left empty.

If params is specified as an associative array (see example #2), see below for further details.

params.regex 文字列 The regex to be used for validator. Must use named captures. When specifying named captures, do not use the $ symbol in the name.

In example #2, two named captures are used - pre and post.

params.display 文字列 Mandatory value. The display value for the insertable. Named captures prefixed with $ are used here. 例 2 を参照。
params.pre 文字列 The pre value for the insertable. Value inserted before the cursor position. Named captures prefixed with $ are used here. If not specified, is set to the display value. 例 2 を参照。
params.post 文字列 The post value for the insertable. Value inserted after the cursor position. Named captures prefixed with $ are used here. 例 2 を参照。 If not specified, defaults to an empty string.

Pre-provided / Bundled validators

Following is a list of bundled validators,

BraceBalance

ID: BraceBalance

Ensures that the number of open braces / brackets, matches the number of closed braces / brackets in the translation.

For example, the following translations would pass,

  • {{ }}
  • [ ]

whereas, the following would fail,

  • [ ]]
  • {{ }

This validator cannot be marked as insertable.

EscapeCharacter

ID: EscapeCharacter

The validator ensures that only the specified escape character are present in a translation.

The allowed escape characters can be specified when adding the validator, and can only include,

  • \t
  • \n
  • \'
  • \"
  • \f
  • \r
  • \a
  • \b
  • \\

このバリデーターは挿入可能ではありません。

GettextNewline

ID: GettextNewline

This works specifically for GetText based message groups.

Ensures that the translation has the same number of newlines as the source message at the beginning and end of the string.

GettextPlural

ID: GettextPlural

This works specifically on GetText based message groups.

Ensures that if the source / definition contains a plural in the format - foo {{PLURAL:GETTEXT|one|many}} bar, the translation must contain it as well. Based on the language this also checks if the translation has the correct number of plural forms. For example, English has two, but Hebrew has four.

InsertableRegex

ID: InsertableRegex

A generic reusable validator that can be used to specify custom validations and insertables.

For example, take the following configuration where the validator is marked as insertable and enforced,

- id: InsertableRegex
  enforce: true
  insertable: true
  params: "/\$[a-zA-Z0-9]+/"

Given the following source message - Hello $name. My name is $myName. that is being translated, the translation must have the parameters - $name and $myName. They will also be displayed as insertables to make it easier for translators to use them in the translation. An absence of these parameters will cause an error to be displayed to the translator.

InsertableRubyVariable

ID: InsertableRubyVariable

This is a validator that matches ruby variables in the translations. Internally it extends InsertableRegexValidator and uses the following regex - %{[a-zA-Z_]+}. このバリデーターは挿入可能です。

例: %{abc}

IosVariable

ID: IosVariable

An insertable variable validator for Ios. Regex is used from this Rubustrings source. このバリデーターは挿入可能です。

例: %@

MatchSet

ID: MatchSet

Ensures that the translation is present in the list of values. Also takes a parameter - caseSensitive that can be either true (default) or false.

For example the following configuration, the validator will validate the message with key - html.dir and ensure that the values for it can either be ltr or rtl. Note that LTR or RTL will not be valid values, since caseSensitive is true by default.

  - id: MatchSet
    enforce: true
    keymatch:
      - html.dir
    params:
      values:
        - ltr
        - rtl

MediaWikiLink

ID: MediaWikiLink

Checks if the translation uses links that are discouraged. Valid links are those that link to Special: pages, {{ns:special}}: or project pages trough MediaWiki messages like {{MediaWiki:helppage-url}}:. Also links in the definition are allowed.

MediaWikiPageName

ID: MediaWikiPageName

Ensures that if the source / definition contains a namespace such as {{ns:project}}:hello the translations made do not try to translate the namespaces itself.

MediaWikiParameter

ID: MediaWikiParameter

This is a validator that matches wiki parameters in the translations. Internally it extends InsertableRegexValidator and uses the following regex - /\$[1-9]/. このバリデーターは挿入可能です。

例: $1, $2.

MediaWikiPlural

ID: MediaWikiPlural

Ensures that if the source / definition contains a {{PLURAL:$1|message|messages}}, the translation should also have it. It can also be used as an insertable. Based on the language this also checks if the translation has the correct number of plural forms. 例えば、英語には 2 個、ヘブライ語には 3 個あります。

MediaWikiTimeList

ID: MediaWikiTimeList

Provides validations for expiry options and IP block options specified in the MediaWiki core. These are usually in the format,

indefinite:indefinite,3 hours:3 hours,12 hours:12 hours,24 hours:24 hours,31 hours:31 hours,36 hours:36 hours,48 hours:48 hours,60 hours:60 hours,72 hours:72 hours,1 week:1 week,2 weeks:2 weeks,1 month:1 month,3 months:3 months,6 months:6 months,1 year:1 year,2 years:2 years,3 years:3 years,infinite:indefinite

The validations ensure that the translations have the exact same number of key-value pairs. These validations are run only on messages with keys,

  1. protect-expiry-options
  2. ipboptions

Newline

ID: Newline

Ensures that the translation has the same number of newlines as the source / definition message at the beginning of the string. このバリデーターは挿入可能ではありません。

NotEmpty

ID: NotEmpty

Ensures that the translation has some content, and that content is not just whitespace. このバリデーターは挿入可能ではありません。

NumericalParameter

ID: NumericalParameter

This validator matches numerical parameters by using the following regex: /\$\d+/. このバリデーターは挿入可能です。

例: $33, $1 etc.

Printf

ID: Printf

This validator checks for missing and unknown printf formatting characters in translations. このバリデーターは挿入可能です。

例: %2$f, %d etc.

PythonInterpolation

ID: PythonInterpolation

This validator matches python string interpolation variables by using the following regex: /\%(?:\([a-zA-Z0-9]*?\))?[diouxXeEfFgGcrs]/U. このバリデーターは挿入可能です。

例: %s, %(name)s

Replacement

ID: Replacement

Checks if a translation is using the search string, and instead suggests the translator to use the string mentioned under replacement. このバリデーターは挿入可能ではありません。

  - id: Replacement
    enforce: true
    params:
      search: '{{PLURAL:'
      replace: '{PLURAL:'

SmartFormatPlural

ID: SmartFormatPlural

This works specifically on SmartFormat based message groups.

Ensures that if the source / definition contains a plural in the format - {1:test|tests}{0:message|messages}, the translation must contain it as well. Based on the language this also checks if the translation has the correct number of plural forms. 例えば、英語には 2 個、ヘブライ語には 4 個あります。

UnicodePlural

ID: UnicodePlural

Ensures that if the source / definition contains a plural in the format - foo {{PLURAL|one=one|many}} bar, the translation must contain it as well. Based on the language this also checks if the translation has the correct number of plural forms. 例えば、英語には 2 個、ヘブライ語には 3 個あります。

User interface

The user interface has been updated to differentiate between errors and warnings.

 
A warning and error shown on top of a translation

During translation, if an error is noticed with the translation, the Save translation button is disabled unless the user who is translating has translate-manage permission.

Additionally validation is also done on the server when the user is saving the translation. This will still allow users who have the translate-manage permission to save the translation even if it has errors.

Custom validators

Certain complicated validations might still require a custom validator to be written. Custom validators must implement the MediaWiki\Extensions\Translate\Validation\MessageValidator interface [1].

Below is an example of a custom validator,

<?php
// Filename: Validator.php
use MediaWiki\Extensions\Translate\Validation\MessageValidator;
use MediaWiki\Extensions\Translate\Validation\ValidationIssue;
use MediaWiki\Extensions\Translate\Validation\ValidationIssues;

/**
 * My Custom Validator
 */
class MyCustomValidator implements MessageValidator {
	
	public function getIssues( TMessage $message, string $targetLanguage ): ValidationIssues {
		$issues = new ValidationIssues();
	    
	    // Validation code goes here. Push ValidationIssue into the ValidationIssues. E.g.:
	    $issue = new ValidationIssue(
			'value-not-present',                                // type
		    'invalid',                                          // sub-type
			'translate-checks-value-not-present',               // message key
			[                                                   // message params
				[ 'PLAIN-PARAMS', $this->possibleValues ],
				[ 'COUNT', count( $this->possibleValues ) ]
			]
		);

		$issues->add( $issue );
	    
	    return $issues;
	}
}

Also see the following classes,

  1. ValidationIssues - https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/extensions/Translate/+/master/src/Validation/ValidationIssues.php
  2. ValidationIssue - https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/extensions/Translate/+/master/src/Validation/ValidationIssue.php

The add the custom validator in the configuration file,

VALIDATORS:
  - class: MyCustomValidator
    enforce: true

AUTOLOAD:
  MyCustomValidator: Validator.php