Manual:パーサー関数かんすう

From mediawiki.org
This page is a translated version of the page Manual:Parser functions and the translation is 58% complete.
Outdated translations are marked like this.
MediaWiki extensions

MediaWiki 1.7で追加ついかされたパーサー関数かんすうは、パーサーと密接みっせつ連動れんどうする拡張かくちょう機能きのういちしゅです。 「パーサー関数かんすう」という言葉ことばを、単純たんじゅんなパーサー関数かんすうあつまりである Extension:ParserFunctions 混同こんどうしないようにしてください。 (これについては Help:Extension:ParserFunctions 参照さんしょうしてください。)

説明せつめい

タグ拡張かくちょう機能きのう処理しょりのテキストをんでブラウザに HTML をかえすのにたいして、パーサー関数かんすうはページじょうのその要素ようそと「相互そうご作用さよう」ができます。たとえばパーサ関数かんすう出力しゅつりょくテンプレート変数へんすうとして利用りようしたりリンク作成さくせい使つかうことができます。

パーサー関数かんすう典型てんけいてき構文こうぶん以下いかとおりです:

{{ #functionname: param1 | param2 | param3 }}

詳細しょうさいについて、Parser::setFunctionHook ( $id, $callback, $flags = 0 )説明せつめいthe documentation参照さんしょうしてください。その説明せつめい文書ぶんしょつぎ内容ないようあつかいます。

コールバック関数かんすう構文こうぶんつぎのとおりです。
function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }
あるいは SFH_OBJECT_ARGS:
function myParserFunction( $parser, $frame, $args ) { ... }

The first variant of the call passes all arguments as plain text. The second passes all arguments as an array of PPNode s, except for the first ($args[0]), which is currently text, though this may change in the future. These represent the unexpanded wikitext. The $frame parameter can be used to expand these arguments as needed. This is commonly used for conditional processing so that only the "true" case is evaluated with an if- or switch-like parser function. The frame object can also climb up the document tree to get information about the caller and has functions to determine and manage call depth, time-to-live, and whether the result of the parser function is volatile.

パーサー関数かんすう作成さくせいは、タグフックを作成さくせいする場合ばあいよりも多少たしょうっています。これは、関数かんすうめいマジックワードでなければならないためです; マジックワードは、別名べつめいおよび言語げんご対応たいおうをサポートする一種いっしゅのキーワードです。

単純たんじゅんれい

パーサー関数かんすう生成せいせいする拡張かくちょう機能きのうれい以下いかしめします。

登録とうろくextension.json に、コードは src/ExampleExtensionHooks.php にそれぞれはいります:

{
	"name": "ExampleExtension",
	"author": "Me",
	"version": "1.0.0",
	"url": "https://www.mediawiki.org/wiki/Extension:ExampleExtension",
	"descriptionmsg": "exampleextension-desc",
	"license-name": "GPL-2.0-or-later",
	"type": "parserhook",
	"MessagesDirs": {
		"ExampleExtension": [
			"i18n"
		]
	},
	"AutoloadClasses": {
		"ExampleExtensionHooks": "src/ExampleExtensionHooks.php"
	},
	"ExtensionMessagesFiles": {
		"ExampleExtensionMagic": "ExampleExtension.i18n.php"
	},
	"Hooks": {
		"ParserFirstCallInit": "ExampleExtensionHooks::onParserFirstCallInit"
	},
	"manifest_version": 1
}
<?php
class ExampleExtensionHooks {
   // レンダリング コールバックをパーサーに登録とうろくします
   public static function onParserFirstCallInit( Parser $parser ) {

      // 関数かんすうフックを作成さくせいし、"example" マジックワードとrenderExample()を対応たいおうさせます
      $parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] );
   }

   // {{#example:}}の出力しゅつりょく表示ひょうじ
   public static function renderExample( Parser $parser, $param1 = '', $param2 = '', $param3 = '' ) {

      // 入力にゅうりょくパラメーターがウィキテキストでテンプレートを展開てんかいします。
      // 出力しゅつりょくもウィキテキストになります。
      $output = "param1 is $param1 and param2 is $param2 and param3 is $param3";

      return $output;
   }
}

拡張かくちょう機能きのうディレクトリ(src/ サブディレクトリではない)にあるべつのファイル ExampleExtension.i18n.php には以下いか内容ないようふくめておく必要ひつようがあります。

<?php
/**
 * @license GPL-2.0-or-later
 * @author Your Name (YourUserName)
 */

$magicWords = [];

/** English
 * @author Your Name (YourUserName)
 */
$magicWords['en'] = [
   'example' => [ 0, 'example' ],
];

この拡張かくちょう機能きのう有効ゆうこうにすると、

  • {{#example: hello | hi | hey}}

出力しゅつりょく結果けっか:

  • param1 is hello and param2 is hi and param3 is hey
magicWords引数ひきすう必須ひっすでありオプションではありません。省略しょうりゃくするとパーサー関数かんすうはまったく機能きのうしません。{{#example: hello | hi}} は拡張かくちょう機能きのうがインストールされていない状態じょうたいとして表示ひょうじされます。 If only the language-specific array is initialized and not the magicWords array itself, this can cause localization errors as translations from other extensions leak into yours. マジックワードの関連かんれんけは、国際こくさいファイルではなく、PHP のインラインでおこなうことができます。 これは、LocalSettings.php でフックを定義ていぎするさい便利べんりです
MediaWiki\MediaWikiServices::getInstance()->getContentLanguage()->mMagicExtensions['wikicodeToHtml'] = ['MAG_CUSTOM', 'custom'];

Within LocalSettings.php

Magic words and their handling parser functions can be defined entirely in LocalSettings.php.

$wgHooks['ParserFirstCallInit'][] = function ( Parser $parser ) 
{
	MediaWiki\MediaWikiServices::getInstance()->getContentLanguage()->mMagicExtensions['wikicodeToHtml'] = ['wikicodeToHtml', 'wikicodeToHtml'];

	$parser->setFunctionHook( 'wikicodeToHtml', 'wikicodeToHtml' );
};
 
function wikicodeToHtml( Parser $parser, $code = '' ) 
{
	$title = $parser->getTitle();
	$options = $parser->Options();
	$options->enableLimitReport(false);
	$parser = $parser->getFreshParser();
	return [$parser->parse($code, $title, $options)->getText(), 'isHTML' => true];
}

よりなが関数かんすう

より複雑ふくざつ関数かんすう記述きじゅつする場合ばあいには、フック関数かんすうを _body.php または .hooks.php ファイルに分離ぶんりし、これらを適当てきとうなクラスの静的せいてき関数かんすうとしてもよいでしょう。この場合ばあい、クラスは $wgAutoloadClasses でロードして、フックから静的せいてき関数かんすうせます。 たとえば:

以下いかのコードを extension.json ファイルに追加ついかします:

"Hooks": {
	"ParserFirstCallInit": "ExampleExtensionHooks::onParserFirstCallInit"
},
"AutoloadClasses": {
	"ExampleExtensionHooks": "src/ExampleExtensionHooks.php"
}

つぎに、以下いかのコードを src/ExampleExtensionHooks.php ファイルに追加ついかします:

class ExampleExtensionHooks {
      public static function onParserFirstCallInit( Parser $parser ) {
           $parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] );
      }
}

パーサー インターフェイス

出力しゅつりょく構文こうぶん解析かいせき制御せいぎょ

作成さくせいしたパーサー関数かんすうかえすウィキテキストが完全かんぜん構文こうぶん解析かいせきされるようにする (テンプレートの展開てんかいふくむ) には、もどnoparse オプションに false を設定せっていします:

return [ $output, 'noparse' => false ];

noparse既定きていは、ある時点じてん、バージョン 1.12 付近ふきんのどこかで、false から true に変更へんこうされたようです。

ぎゃくに、作成さくせいしたパーサー関数かんすうが、ウィキテキストをかえすのではなく、構文こうぶん解析かいせきされないままの HTML をかえすようにするには、以下いかのように指定していします:

return [ $output, 'noparse' => true, 'isHTML' => true ];

命名めいめい

MW は既定きていでそれぞれのパーサー関数かんすうめい先頭せんとうにハッシュ記号きごう (「#」) を追加ついかします。 追加ついかさせない (パーサー関数かんすうめい接頭せっとう「#」をけない) ためには、以下いか説明せつめいしているように、SFH_NO_HASH定数ていすうをオプションのflags引数ひきすうのsetFunctionHookに挿入そうにゅうします。

もしハッシュ記号きごう接頭せっとう使つかわない名称めいしょうえら場合ばあいは、その関数かんすうめいうしろにコロンをけてつくったページめい参照さんしょう呼出よびだししできないことにご留意りゅういください。とくに、関数かんすうめい名前なまえ空間くうかんめい同名どうめいにしてはいけません。ウィキあいだ参照さんしょうみの[1]有効ゆうこうにした場合ばあいには、関数かんすうめいをウィキあいだ接頭せっとう同名どうめいにしてはいけません。

setFunctionHook フック

パーサーに関連かんれんするインターフェースの詳細しょうさいは、includes/Parser.phpにどうこりした説明せつめい文書ぶんしょ setFunctionHook を参照さんしょうしてください。 以下いかはこれらのコメントを転写てんしゃしたものです (ふる可能かのうせいあり) 。

function setFunctionHook( $id, $callback, $flags = 0 )

パラメーター:

  • string $id - マジックワード ID
  • mixed $callback - 使用しようするコールバック関数かんすう (とオブジェクト)
  • integer $flags - (省略しょうりゃく可能かのう) 関数かんすうを「#」なしですようにするには、SFH_NO_HASH 定数ていすう設定せっていします。

Set it to SFH_OBJECT_ARGS (2) to pass a PPFrame object and array of arguments instead of a series of function arguments, for which see above. Defaults to 0 (no flags).

もど: この名前なまえもとのコールバック関数かんすう (ある場合ばあい)

たとえば{{#sum:1|2|3}}など関数かんすう作成さくせい。コールバック関数かんすう構文こうぶんかたしめします。

function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }

コールバックのもど関数かんすう出力しゅつりょくした文字もじれつもしくはまたはテキストをふく配列はいれつ要素ようそ0と、要素ようそのフラグいくつかをしめします。フラグの名前なまえはキーで指定していします。 有効ゆうこうなフラグは以下いかのとおりです。

Name Type Default Description
found Boolean true もどのテキストは有効ゆうこうで、テンプレートの処理しょり停止ていし。これは既定きてい有効ゆうこうです。
text ? ? The text to return from the function. If isChildObj or isLocalObj are specified, this should be a DOM node instead.
noparse Boolean true true if text should not be preprocessed to a DOM tree, e.g. unsafe HTML tags should not be stripped, etc.
isHTML Boolean ? もど文字もじれつは HTMLで、ウィキテキスト変換へんかんから保護ほごする必要ひつようがある But see discussion
nowiki Boolean usually false true if wiki markup in the return value (text) should be escaped.
isChildObj Boolean ? true if the text is a DOM node needing expansion in a child frame.
isLocalObj Boolean ? true if he text is a DOM node needing expansion in the current frame. The default value depends on other values and outcomes.
preprocessFlags ? false Optional PPFrame flags to use when parsing the returned text. This only applies when noparse is false.
title ? false The Title object where the text came from.
forceRawInterwiki Boolean ? true if interwiki transclusion must be forced to be done in raw mode and not rendered.


Expensive parser functions

Some parser functions represent a significant use of a wiki's resources and should be marked as "expensive". The number of expensive parser functions on any given page is limited by the $wgExpensiveParserFunctionLimit setting. What counts as expensive is left up to the function itself, but typically, anything that is likely to cause a delay that extends beyond simple processing of data should be considered. This includes things like database reads and writes, launching a shell script synchronously, or file manipulation. On the other hand, not all such functions should necessarily be tagged. Semantic MediaWiki, for example, only marks a percentage of its database reads as expensive. This is due to the fact that on certain data-intensive pages, it could easily overflow the normal expensive parser function limits. In cases like this, the potential for noticeably slower performance that doesn't get flagged as expensive is a trade-off to having the functionality that SMW offers.

To mark your parser function as expensive, from within the body of the function's code, use $result = $parser->incrementExpensiveFunctionCount();. The return value will be false if the expensive function limit has been reached or exceeded.

名前なまえきパラメーター

パーサー関数かんすうはテンプレートもしくはタグ拡張かくちょう機能きのうことなり、名前なまえきパラメーターをサポートしないものの、ときにはそれを回避かいひするやくちます。利用りようしゃ引数ひきすうけるためにたてぼう ( | ) を使つかれているため、パーサー関数かんすうのコンテキストでも同様どうよう記述きじゅつができると便利べんりです。これを実現じつげんする方法ほうほう簡単かんたんれいしめします。

function ExampleExtensionRenderParserFunction( &$parser ) {
	// Suppose the user invoked the parser function like so:
	// {{#myparserfunction: foo=bar | apple=orange | banana }}

	$options = extractOptions( array_slice( func_get_args(), 1 ) );

	// Now you've got an array that looks like this:
	// [foo] => 'bar'
	// [apple] => 'orange'
	// [banana] => true
	// Continue writing your code...
}

/**
 * Converts an array of values in form [0] => "name=value"
 * into a real associative array in form [name] => value
 * If no = is provided, true is assumed like this: [name] => true
 *
 * @param array string $options
 * @return array $results
 */
function extractOptions( array $options ) {
	$results = [];
	foreach ( $options as $option ) {
		$pair = array_map( 'trim', explode( '=', $option, 2 ) );
		if ( count( $pair ) === 2 ) {
			$results[ $pair[0] ] = $pair[1];
		}
		if ( count( $pair ) === 1 ) {
			$results[ $pair[0] ] = true;
		}
	}
	return $results;
}

関連かんれん項目こうもく

General and related guides:

Code:

Examples: