Debian Codegraph @

extensions/Scribunto/includes/Hooks.php

raw symbols SCIP
1 <?php
2 /**
3 * Wikitext scripting infrastructure for MediaWiki: hooks.
4 * Copyright (C) 2009-2012 Victor Vasiliev <[email protected]>
5 * https://www.mediawiki.org/
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 */
22
23 // phpcs:disable MediaWiki.NamingConventions.LowerCamelFunctionsName.FunctionName
24
25 namespace MediaWiki\Extension\Scribunto;
26
27 use Article;
28 use MediaWiki\Config\Config;
29 use MediaWiki\Content\Content;
30 use MediaWiki\Context\IContextSource;
31 use MediaWiki\EditPage\EditPage;
32 use MediaWiki\Hook\EditFilterMergedContentHook;
33 use MediaWiki\Hook\EditPage__showReadOnlyForm_initialHook;
34 use MediaWiki\Hook\EditPage__showStandardInputs_optionsHook;
35 use MediaWiki\Hook\EditPageBeforeEditButtonsHook;
36 use MediaWiki\Hook\ParserClearStateHook;
37 use MediaWiki\Hook\ParserClonedHook;
38 use MediaWiki\Hook\ParserFirstCallInitHook;
39 use MediaWiki\Hook\ParserLimitReportFormatHook;
40 use MediaWiki\Hook\ParserLimitReportPrepareHook;
41 use MediaWiki\Hook\SoftwareInfoHook;
42 use MediaWiki\Html\Html;
43 use MediaWiki\MediaWikiServices;
44 use MediaWiki\Output\OutputPage;
45 use MediaWiki\Page\Hook\ArticleViewHeaderHook;
46 use MediaWiki\Parser\Parser;
47 use MediaWiki\Parser\ParserOutput;
48 use MediaWiki\Parser\PPFrame;
49 use MediaWiki\Parser\PPNode;
50 use MediaWiki\Revision\Hook\ContentHandlerDefaultModelForHook;
51 use MediaWiki\Status\Status;
52 use MediaWiki\Title\Title;
53 use MediaWiki\User\User;
54 use MediaWiki\WikiMap\WikiMap;
55 use UtfNormal\Validator;
56 use Wikimedia\ObjectCache\EmptyBagOStuff;
57 use Wikimedia\PSquare;
58
59 /**
60 * Hooks for the Scribunto extension.
61 */
62 class Hooks implements
63 SoftwareInfoHook,
64 ParserFirstCallInitHook,
65 ParserLimitReportPrepareHook,
66 ParserLimitReportFormatHook,
67 ParserClearStateHook,
68 ParserClonedHook,
69 EditPage__showStandardInputs_optionsHook,
70 EditPage__showReadOnlyForm_initialHook,
71 EditPageBeforeEditButtonsHook,
72 EditFilterMergedContentHook,
73 ArticleViewHeaderHook,
74 ContentHandlerDefaultModelForHook
75 {
76 private Config $config;
77
78 public function __construct(
79 Config $config
80 ) {
81 $this->config = $config;
82 }
83
84 /**
85 * Define content handler constant upon extension registration
86 */
87 public static function onRegistration() {
88 define( 'CONTENT_MODEL_SCRIBUNTO', 'Scribunto' );
89 }
90
91 /**
92 * Get software information for Special:Version
93 *
94 * @param array &$software
95 * @return bool
96 */
97 public function onSoftwareInfo( &$software ) {
98 $engine = Scribunto::newDefaultEngine();
99 $engine->setTitle( Title::makeTitle( NS_SPECIAL, 'Version' ) );
100 $engine->getSoftwareInfo( $software );
101 return true;
102 }
103
104 /**
105 * Register parser hooks.
106 *
107 * @param Parser $parser
108 * @return void
109 */
110 public function onParserFirstCallInit( $parser ) {
111 $parser->setFunctionHook( 'invoke', [ $this, 'invokeHook' ], Parser::SFH_OBJECT_ARGS );
112 }
113
114 /**
115 * Called when the interpreter is to be reset.
116 *
117 * @param Parser $parser
118 * @return void
119 */
120 public function onParserClearState( $parser ) {
121 Scribunto::resetParserEngine( $parser );
122 }
123
124 /**
125 * Called when the parser is cloned
126 *
127 * @param Parser $parser
128 * @return void
129 */
130 public function onParserCloned( $parser ) {
131 $parser->scribunto_engine = null;
132 }
133
134 /**
135 * Hook function for {{#invoke:module|func}}
136 *
137 * @param Parser $parser
138 * @param PPFrame $frame
139 * @param PPNode[] $args
140 * @return string
141 */
142 public function invokeHook( Parser $parser, PPFrame $frame, array $args ) {
143 try {
144 if ( count( $args ) < 2 ) {
145 throw new ScribuntoException( 'scribunto-common-nofunction' );
146 }
147 $moduleName = trim( $frame->expand( $args[0] ) );
148 $engine = Scribunto::getParserEngine( $parser );
149
150 $title = Title::makeTitleSafe( NS_MODULE, $moduleName );
151 if ( !$title || !$title->hasContentModel( CONTENT_MODEL_SCRIBUNTO ) ) {
152 throw new ScribuntoException( 'scribunto-common-nosuchmodule',
153 [ 'args' => [ $moduleName ] ] );
154 }
155 $module = $engine->fetchModuleFromParser( $title );
156 if ( !$module ) {
157 throw new ScribuntoException( 'scribunto-common-nosuchmodule',
158 [ 'args' => [ $moduleName ] ] );
159 }
160 $functionName = trim( $frame->expand( $args[1] ) );
161
162 $bits = $args[1]->splitArg();
163 unset( $args[0] );
164 unset( $args[1] );
165
166 // If $bits['index'] is empty, then the function name was parsed as a
167 // key=value pair (because of an equals sign in it), and since it didn't
168 // have an index, we don't need the index offset.
169 $childFrame = $frame->newChild( $args, $title, $bits['index'] === '' ? 0 : 1 );
170
171 if ( $this->config->get( 'ScribuntoGatherFunctionStats' ) ) {
172 $u0 = $engine->getResourceUsage( $engine::CPU_SECONDS );
173 $result = $module->invoke( $functionName, $childFrame );
174 $u1 = $engine->getResourceUsage( $engine::CPU_SECONDS );
175
176 if ( $u1 > $u0 ) {
177 $timingMs = (int)( 1000 * ( $u1 - $u0 ) );
178 // Since the overhead of stats is worst when #invoke
179 // calls are very short, don't process measurements <= 20ms.
180 if ( $timingMs > 20 ) {
181 $this->reportTiming( $moduleName, $functionName, $timingMs );
182 }
183 }
184 } else {
185 $result = $module->invoke( $functionName, $childFrame );
186 }
187
188 return Validator::cleanUp( strval( $result ) );
189 } catch ( ScribuntoException $e ) {
190 $trace = $e->getScriptTraceHtml( [ 'msgOptions' => [ 'content' ] ] );
191 $html = Html::element( 'p', [], $e->getMessage() );
192 if ( $trace !== false ) {
193 $html .= Html::element( 'p',
194 [],
195 wfMessage( 'scribunto-common-backtrace' )->inContentLanguage()->text()
196 ) . $trace;
197 } else {
198 $html .= Html::element( 'p',
199 [],
200 wfMessage( 'scribunto-common-no-details' )->inContentLanguage()->text()
201 );
202 }
203
204 // Index this error by a uniq ID so that we are independent of
205 // page parse order. (T300979)
206 // (The only way this will conflict is if two exceptions have
207 // exactly the same backtrace, in which case we really only need
208 // one copy of the backtrace!)
209 $uuid = substr( sha1( $html ), -8 );
210 $parserOutput = $parser->getOutput();
211 $parserOutput->appendExtensionData( 'ScribuntoErrors', $uuid );
212 $parserOutput->setExtensionData( "ScribuntoErrors-$uuid", $html );
213
214 $parserOutput->appendJsConfigVar( 'ScribuntoErrors', $uuid );
215 $parserOutput->setJsConfigVar( "ScribuntoErrors-$uuid", $html );
216
217 // These methods are idempotent; doesn't hurt to call them every
218 // time.
219 $parser->addTrackingCategory( 'scribunto-common-error-category' );
220 $parserOutput->addModules( [ 'ext.scribunto.errors' ] );
221
222 $id = "mw-scribunto-error-$uuid";
223 $parserError = htmlspecialchars( $e->getMessage() );
224
225 // #iferror-compatible error element
226 return "<strong class=\"error\"><span class=\"scribunto-error $id\">" .
227 $parserError . "</span></strong>";
228 }
229 }
230
231 /**
232 * Record stats on slow function calls.
233 *
234 * @param string $moduleName
235 * @param string $functionName
236 * @param int $timing Function execution time in milliseconds.
237 */
238 private function reportTiming( $moduleName, $functionName, $timing ) {
239 if ( !$this->config->get( 'ScribuntoGatherFunctionStats' ) ) {
240 return;
241 }
242
243 $threshold = $this->config->get( 'ScribuntoSlowFunctionThreshold' );
244 if ( !( is_float( $threshold ) && $threshold > 0 && $threshold < 1 ) ) {
245 return;
246 }
247
248 $objectcachefactory = MediaWikiServices::getInstance()->getObjectCacheFactory();
249 static $cache;
250 if ( !$cache ) {
251 $cache = $objectcachefactory->getLocalServerInstance( CACHE_NONE );
252
253 }
254
255 // To control the sampling rate, we keep a compact histogram of
256 // observations in APC, and extract the Nth percentile (specified
257 // via $wgScribuntoSlowFunctionThreshold; defaults to 0.90).
258 // We need a non-empty local server cache for that (e.g. php-apcu).
259 if ( $cache instanceof EmptyBagOStuff ) {
260 return;
261 }
262
263 $cacheVersion = '3';
264 $key = $cache->makeGlobalKey( 'scribunto-stats', $cacheVersion, (string)$threshold );
265
266 // This is a classic "read-update-write" critical section with no
267 // mutual exclusion, but the only consequence is that some samples
268 // will be dropped. We only need enough samples to estimate the
269 // shape of the data, so that's fine.
270 $ps = $cache->get( $key ) ?: new PSquare( $threshold );
271 $ps->addObservation( $timing );
272 $cache->set( $key, $ps, 60 );
273
274 if ( $ps->getCount() < 1000 || $timing < $ps->getValue() ) {
275 return;
276 }
277
278 static $stats;
279 if ( !$stats ) {
280 $stats = MediaWikiServices::getInstance()->getStatsFactory();
281 }
282 $statAction = WikiMap::getCurrentWikiId() . '__' . $moduleName . '__' . $functionName;
283 $stats->getTiming( 'scribunto_traces_seconds' )
284 ->setLabel( 'action', $statAction )
285 ->copyToStatsdAt( 'scribunto.traces.' . $statAction )
286 ->observe( $timing );
287 }
288
289 /**
290 * Set the Scribunto content handler for modules
291 *
292 * @param Title $title
293 * @param string &$model
294 * @return void
295 */
296 public function onContentHandlerDefaultModelFor( $title, &$model ) {
297 if ( $model === 'sanitized-css' ) {
298 // Let TemplateStyles override Scribunto
299 return;
300 }
301 if ( $title->getNamespace() === NS_MODULE ) {
302 if ( str_ends_with( $title->getText(), '.json' ) ) {
303 $model = CONTENT_MODEL_JSON;
304 } elseif ( !Scribunto::isDocPage( $title ) ) {
305 $model = CONTENT_MODEL_SCRIBUNTO;
306 }
307 }
308 }
309
310 /**
311 * Adds report of number of evaluations by the single wikitext page.
312 *
313 * @param Parser $parser
314 * @param ParserOutput $parserOutput
315 * @return void
316 */
317 public function onParserLimitReportPrepare( $parser, $parserOutput ) {
318 if ( Scribunto::isParserEnginePresent( $parser ) ) {
319 $engine = Scribunto::getParserEngine( $parser );
320 $engine->reportLimitData( $parserOutput );
321 }
322 }
323
324 /**
325 * Formats the limit report data
326 *
327 * @param string $key
328 * @param mixed &$value
329 * @param string &$report
330 * @param bool $isHTML
331 * @param bool $localize
332 * @return bool
333 */
334 public function onParserLimitReportFormat( $key, &$value, &$report, $isHTML, $localize ) {
335 $engine = Scribunto::newDefaultEngine();
336 return $engine->formatLimitData( $key, $value, $report, $isHTML, $localize );
337 }
338
339 /**
340 * EditPage::showStandardInputs:options hook
341 *
342 * @param EditPage $editor
343 * @param OutputPage $output
344 * @param int &$tab Current tabindex
345 * @return void
346 */
347 public function onEditPage__showStandardInputs_options( $editor, $output, &$tab ) {
348 if ( $editor->getTitle()->hasContentModel( CONTENT_MODEL_SCRIBUNTO ) ) {
349 $output->addModules( 'ext.scribunto.edit' );
350 $editor->editFormTextAfterTools .= '<div id="mw-scribunto-console"></div>';
351 }
352 }
353
354 /**
355 * EditPage::showReadOnlyForm:initial hook
356 *
357 * @param EditPage $editor
358 * @param OutputPage $output
359 * @return void
360 */
361 public function onEditPage__showReadOnlyForm_initial( $editor, $output ) {
362 if ( $editor->getTitle()->hasContentModel( CONTENT_MODEL_SCRIBUNTO ) ) {
363 $output->addModules( 'ext.scribunto.edit' );
364 $editor->editFormTextAfterContent .= '<div id="mw-scribunto-console"></div>';
365 }
366 }
367
368 /**
369 * EditPageBeforeEditButtons hook
370 *
371 * @param EditPage $editor
372 * @param array &$buttons Button array
373 * @param int &$tabindex Current tabindex
374 * @return void
375 */
376 public function onEditPageBeforeEditButtons( $editor, &$buttons, &$tabindex ) {
377 if ( $editor->getTitle()->hasContentModel( CONTENT_MODEL_SCRIBUNTO ) ) {
378 unset( $buttons['preview'] );
379 }
380 }
381
382 /**
383 * @param IContextSource $context
384 * @param Content $content
385 * @param Status $status
386 * @param string $summary
387 * @param User $user
388 * @param bool $minoredit
389 * @return bool
390 */
391 public function onEditFilterMergedContent( IContextSource $context, Content $content,
392 Status $status, $summary, User $user, $minoredit
393 ) {
394 $title = $context->getTitle();
395
396 if ( !$content instanceof ScribuntoContent ) {
397 return true;
398 }
399 $contentHandlerFactory = MediaWikiServices::getInstance()->getContentHandlerFactory();
400 $contentHandler = $contentHandlerFactory->getContentHandler( $content->getModel() );
401
402 '@phan-var ScribuntoContentHandler $contentHandler';
403 $validateStatus = $contentHandler->validate( $content, $title );
404 if ( $validateStatus->isOK() ) {
405 return true;
406 }
407
408 $status->merge( $validateStatus );
409
410 if ( isset( $validateStatus->value->params['module'] ) ) {
411 $module = $validateStatus->value->params['module'];
412 $line = $validateStatus->value->params['line'];
413 if ( $module === $title->getPrefixedDBkey() && preg_match( '/^\d+$/', $line ) ) {
414 $out = $context->getOutput();
415 $out->addInlineScript( 'window.location.hash = ' . Html::encodeJsVar( "#mw-ce-l$line" ) );
416 }
417 }
418 if ( !$status->isOK() ) {
419 // @todo Remove this line after this extension do not support mediawiki version 1.36 and before
420 $status->value = EditPage::AS_HOOK_ERROR_EXPECTED;
421 return false;
422 }
423
424 return true;
425 }
426
427 /**
428 * @param Article $article
429 * @param bool|ParserOutput|null &$outputDone
430 * @param bool &$pcache
431 * @return void
432 */
433 public function onArticleViewHeader( $article, &$outputDone, &$pcache ) {
434 $title = $article->getTitle();
435 if ( Scribunto::isDocPage( $title, $forModule ) ) {
436 $article->getContext()->getOutput()->addHTML(
437 wfMessage( 'scribunto-doc-page-header', $forModule->getPrefixedText() )->parseAsBlock()
438 );
439 }
440 }
441 }