MediaWiki REL1_31
ApiHelp.php
Go to the documentation of this file.
1<?php
23use HtmlFormatter\HtmlFormatter;
25
32class ApiHelp extends ApiBase {
33 public function execute() {
35 $modules = [];
36
37 foreach ( $params['modules'] as $path ) {
38 $modules[] = $this->getModuleFromPath( $path );
39 }
40
41 // Get the help
42 $context = new DerivativeContext( $this->getMain()->getContext() );
43 $context->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'apioutput' ) );
44 $context->setLanguage( $this->getMain()->getLanguage() );
45 $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
46 $out = new OutputPage( $context );
47 $out->setCopyrightUrl( 'https://www.mediawiki.org/wiki/Special:MyLanguage/Copyright' );
48 $context->setOutput( $out );
49
51
52 // Grab the output from the skin
53 ob_start();
54 $context->getOutput()->output();
55 $html = ob_get_clean();
56
57 $result = $this->getResult();
58 if ( $params['wrap'] ) {
59 $data = [
60 'mime' => 'text/html',
61 'filename' => 'api-help.html',
62 'help' => $html,
63 ];
64 ApiResult::setSubelementsList( $data, 'help' );
65 $result->addValue( null, $this->getModuleName(), $data );
66 } else {
67 $result->reset();
68 $result->addValue( null, 'text', $html, ApiResult::NO_SIZE_CHECK );
69 $result->addValue( null, 'mime', 'text/html', ApiResult::NO_SIZE_CHECK );
70 $result->addValue( null, 'filename', 'api-help.html', ApiResult::NO_SIZE_CHECK );
71 }
72 }
73
93 public static function getHelp( IContextSource $context, $modules, array $options ) {
95
96 if ( !is_array( $modules ) ) {
97 $modules = [ $modules ];
98 }
99
101 $out->addModuleStyles( [
102 'mediawiki.hlist',
103 'mediawiki.apihelp',
104 ] );
105 if ( !empty( $options['toc'] ) ) {
106 $out->addModules( 'mediawiki.toc' );
107 }
108 $out->setPageTitle( $context->msg( 'api-help-title' ) );
109
110 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
111 $cacheKey = null;
112 if ( count( $modules ) == 1 && $modules[0] instanceof ApiMain &&
113 $options['recursivesubmodules'] && $context->getLanguage() === $wgContLang
114 ) {
115 $cacheHelpTimeout = $context->getConfig()->get( 'APICacheHelpTimeout' );
116 if ( $cacheHelpTimeout > 0 ) {
117 // Get help text from cache if present
118 $cacheKey = $cache->makeKey( 'apihelp', $modules[0]->getModulePath(),
119 (int)!empty( $options['toc'] ),
120 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
121 $cached = $cache->get( $cacheKey );
122 if ( $cached ) {
123 $out->addHTML( $cached );
124 return;
125 }
126 }
127 }
128 if ( $out->getHTML() !== '' ) {
129 // Don't save to cache, there's someone else's content in the page
130 // already
131 $cacheKey = null;
132 }
133
134 $options['recursivesubmodules'] = !empty( $options['recursivesubmodules'] );
135 $options['submodules'] = $options['recursivesubmodules'] || !empty( $options['submodules'] );
136
137 // Prepend lead
138 if ( empty( $options['nolead'] ) ) {
139 $msg = $context->msg( 'api-help-lead' );
140 if ( !$msg->isDisabled() ) {
141 $out->addHTML( $msg->parseAsBlock() );
142 }
143 }
144
145 $haveModules = [];
147 if ( !empty( $options['toc'] ) && $haveModules ) {
148 $out->addHTML( Linker::generateTOC( $haveModules, $context->getLanguage() ) );
149 }
150 $out->addHTML( $html );
151
152 $helptitle = isset( $options['helptitle'] ) ? $options['helptitle'] : null;
153 $html = self::fixHelpLinks( $out->getHTML(), $helptitle, $haveModules );
154 $out->clearHTML();
155 $out->addHTML( $html );
156
157 if ( $cacheKey !== null ) {
158 $cache->set( $cacheKey, $out->getHTML(), $cacheHelpTimeout );
159 }
160 }
161
170 public static function fixHelpLinks( $html, $helptitle = null, $localModules = [] ) {
171 $formatter = new HtmlFormatter( $html );
172 $doc = $formatter->getDoc();
173 $xpath = new DOMXPath( $doc );
174 $nodes = $xpath->query( '//a[@href][not(contains(@class,\'apihelp-linktrail\'))]' );
175 foreach ( $nodes as $node ) {
176 $href = $node->getAttribute( 'href' );
177 do {
178 $old = $href;
179 $href = rawurldecode( $href );
180 } while ( $old !== $href );
181 if ( preg_match( '!Special:ApiHelp/([^&/|#]+)((?:#.*)?)!', $href, $m ) ) {
182 if ( isset( $localModules[$m[1]] ) ) {
183 $href = $m[2] === '' ? '#' . $m[1] : $m[2];
184 } elseif ( $helptitle !== null ) {
185 $href = Title::newFromText( str_replace( '$1', $m[1], $helptitle ) . $m[2] )
186 ->getFullURL();
187 } else {
188 $href = wfAppendQuery( wfScript( 'api' ), [
189 'action' => 'help',
190 'modules' => $m[1],
191 ] ) . $m[2];
192 }
193 $node->setAttribute( 'href', $href );
194 $node->removeAttribute( 'title' );
195 }
196 }
197
198 return $formatter->getText();
199 }
200
209 private static function wrap( Message $msg, $class, $tag = 'span' ) {
210 return Html::rawElement( $tag, [ 'class' => $class ],
211 $msg->parse()
212 );
213 }
214
225 array $options, &$haveModules
226 ) {
227 $out = '';
228
229 $level = empty( $options['headerlevel'] ) ? 2 : $options['headerlevel'];
230 if ( empty( $options['tocnumber'] ) ) {
231 $tocnumber = [ 2 => 0 ];
232 } else {
233 $tocnumber = &$options['tocnumber'];
234 }
235
236 foreach ( $modules as $module ) {
237 $tocnumber[$level]++;
238 $path = $module->getModulePath();
239 $module->setContext( $context );
240 $help = [
241 'header' => '',
242 'flags' => '',
243 'description' => '',
244 'help-urls' => '',
245 'parameters' => '',
246 'examples' => '',
247 'submodules' => '',
248 ];
249
250 if ( empty( $options['noheader'] ) || !empty( $options['toc'] ) ) {
251 $anchor = $path;
252 $i = 1;
253 while ( isset( $haveModules[$anchor] ) ) {
254 $anchor = $path . '|' . ++$i;
255 }
256
257 if ( $module->isMain() ) {
258 $headerContent = $context->msg( 'api-help-main-header' )->parse();
259 $headerAttr = [
260 'class' => 'apihelp-header',
261 ];
262 } else {
263 $name = $module->getModuleName();
264 $headerContent = $module->getParent()->getModuleManager()->getModuleGroup( $name ) .
265 "=$name";
266 if ( $module->getModulePrefix() !== '' ) {
267 $headerContent .= ' ' .
268 $context->msg( 'parentheses', $module->getModulePrefix() )->parse();
269 }
270 // Module names are always in English and not localized,
271 // so English language and direction must be set explicitly,
272 // otherwise parentheses will get broken in RTL wikis
273 $headerAttr = [
274 'class' => 'apihelp-header apihelp-module-name',
275 'dir' => 'ltr',
276 'lang' => 'en',
277 ];
278 }
279
280 $headerAttr['id'] = $anchor;
281
282 $haveModules[$anchor] = [
283 'toclevel' => count( $tocnumber ),
284 'level' => $level,
285 'anchor' => $anchor,
286 'line' => $headerContent,
287 'number' => implode( '.', $tocnumber ),
288 'index' => false,
289 ];
290 if ( empty( $options['noheader'] ) ) {
291 $help['header'] .= Html::element(
292 'h' . min( 6, $level ),
293 $headerAttr,
294 $headerContent
295 );
296 }
297 } else {
298 $haveModules[$path] = true;
299 }
300
301 $links = [];
302 $any = false;
303 for ( $m = $module; $m !== null; $m = $m->getParent() ) {
304 $name = $m->getModuleName();
305 if ( $name === 'main_int' ) {
306 $name = 'main';
307 }
308
309 if ( count( $modules ) === 1 && $m === $modules[0] &&
310 !( !empty( $options['submodules'] ) && $m->getModuleManager() )
311 ) {
312 $link = Html::element( 'b', [ 'dir' => 'ltr', 'lang' => 'en' ], $name );
313 } else {
314 $link = SpecialPage::getTitleFor( 'ApiHelp', $m->getModulePath() )->getLocalURL();
315 $link = Html::element( 'a',
316 [ 'href' => $link, 'class' => 'apihelp-linktrail', 'dir' => 'ltr', 'lang' => 'en' ],
317 $name
318 );
319 $any = true;
320 }
321 array_unshift( $links, $link );
322 }
323 if ( $any ) {
324 $help['header'] .= self::wrap(
325 $context->msg( 'parentheses' )
326 ->rawParams( $context->getLanguage()->pipeList( $links ) ),
327 'apihelp-linktrail', 'div'
328 );
329 }
330
331 $flags = $module->getHelpFlags();
332 $help['flags'] .= Html::openElement( 'div',
333 [ 'class' => 'apihelp-block apihelp-flags' ] );
334 $msg = $context->msg( 'api-help-flags' );
335 if ( !$msg->isDisabled() ) {
336 $help['flags'] .= self::wrap(
337 $msg->numParams( count( $flags ) ), 'apihelp-block-head', 'div'
338 );
339 }
340 $help['flags'] .= Html::openElement( 'ul' );
341 foreach ( $flags as $flag ) {
342 $help['flags'] .= Html::rawElement( 'li', null,
343 self::wrap( $context->msg( "api-help-flag-$flag" ), "apihelp-flag-$flag" )
344 );
345 }
346 $sourceInfo = $module->getModuleSourceInfo();
347 if ( $sourceInfo ) {
348 if ( isset( $sourceInfo['namemsg'] ) ) {
349 $extname = $context->msg( $sourceInfo['namemsg'] )->text();
350 } else {
351 // Probably English, so wrap it.
352 $extname = Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $sourceInfo['name'] );
353 }
354 $help['flags'] .= Html::rawElement( 'li', null,
355 self::wrap(
356 $context->msg( 'api-help-source', $extname, $sourceInfo['name'] ),
357 'apihelp-source'
358 )
359 );
360
361 $link = SpecialPage::getTitleFor( 'Version', 'License/' . $sourceInfo['name'] );
362 if ( isset( $sourceInfo['license-name'] ) ) {
363 $msg = $context->msg( 'api-help-license', $link,
364 Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $sourceInfo['license-name'] )
365 );
366 } elseif ( SpecialVersion::getExtLicenseFileName( dirname( $sourceInfo['path'] ) ) ) {
367 $msg = $context->msg( 'api-help-license-noname', $link );
368 } else {
369 $msg = $context->msg( 'api-help-license-unknown' );
370 }
371 $help['flags'] .= Html::rawElement( 'li', null,
372 self::wrap( $msg, 'apihelp-license' )
373 );
374 } else {
375 $help['flags'] .= Html::rawElement( 'li', null,
376 self::wrap( $context->msg( 'api-help-source-unknown' ), 'apihelp-source' )
377 );
378 $help['flags'] .= Html::rawElement( 'li', null,
379 self::wrap( $context->msg( 'api-help-license-unknown' ), 'apihelp-license' )
380 );
381 }
382 $help['flags'] .= Html::closeElement( 'ul' );
383 $help['flags'] .= Html::closeElement( 'div' );
384
385 foreach ( $module->getFinalDescription() as $msg ) {
386 $msg->setContext( $context );
387 $help['description'] .= $msg->parseAsBlock();
388 }
389
390 $urls = $module->getHelpUrls();
391 if ( $urls ) {
392 $help['help-urls'] .= Html::openElement( 'div',
393 [ 'class' => 'apihelp-block apihelp-help-urls' ]
394 );
395 $msg = $context->msg( 'api-help-help-urls' );
396 if ( !$msg->isDisabled() ) {
397 $help['help-urls'] .= self::wrap(
398 $msg->numParams( count( $urls ) ), 'apihelp-block-head', 'div'
399 );
400 }
401 if ( !is_array( $urls ) ) {
402 $urls = [ $urls ];
403 }
404 $help['help-urls'] .= Html::openElement( 'ul' );
405 foreach ( $urls as $url ) {
406 $help['help-urls'] .= Html::rawElement( 'li', null,
407 Html::element( 'a', [ 'href' => $url, 'dir' => 'ltr' ], $url )
408 );
409 }
410 $help['help-urls'] .= Html::closeElement( 'ul' );
411 $help['help-urls'] .= Html::closeElement( 'div' );
412 }
413
414 $params = $module->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
415 $dynamicParams = $module->dynamicParameterDocumentation();
416 $groups = [];
417 if ( $params || $dynamicParams !== null ) {
418 $help['parameters'] .= Html::openElement( 'div',
419 [ 'class' => 'apihelp-block apihelp-parameters' ]
420 );
421 $msg = $context->msg( 'api-help-parameters' );
422 if ( !$msg->isDisabled() ) {
423 $help['parameters'] .= self::wrap(
424 $msg->numParams( count( $params ) ), 'apihelp-block-head', 'div'
425 );
426 }
427 $help['parameters'] .= Html::openElement( 'dl' );
428
429 $descriptions = $module->getFinalParamDescription();
430
431 foreach ( $params as $name => $settings ) {
432 if ( !is_array( $settings ) ) {
433 $settings = [ ApiBase::PARAM_DFLT => $settings ];
434 }
435
436 $help['parameters'] .= Html::rawElement( 'dt', null,
437 Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $module->encodeParamName( $name ) )
438 );
439
440 // Add description
441 $description = [];
442 if ( isset( $descriptions[$name] ) ) {
443 foreach ( $descriptions[$name] as $msg ) {
444 $msg->setContext( $context );
445 $description[] = $msg->parseAsBlock();
446 }
447 }
448
449 // Add usage info
450 $info = [];
451
452 // Required?
453 if ( !empty( $settings[ApiBase::PARAM_REQUIRED] ) ) {
454 $info[] = $context->msg( 'api-help-param-required' )->parse();
455 }
456
457 // Custom info?
458 if ( !empty( $settings[ApiBase::PARAM_HELP_MSG_INFO] ) ) {
459 foreach ( $settings[ApiBase::PARAM_HELP_MSG_INFO] as $i ) {
460 $tag = array_shift( $i );
461 $info[] = $context->msg( "apihelp-{$path}-paraminfo-{$tag}" )
462 ->numParams( count( $i ) )
463 ->params( $context->getLanguage()->commaList( $i ) )
464 ->params( $module->getModulePrefix() )
465 ->parse();
466 }
467 }
468
469 // Type documentation
470 if ( !isset( $settings[ApiBase::PARAM_TYPE] ) ) {
471 $dflt = isset( $settings[ApiBase::PARAM_DFLT] )
472 ? $settings[ApiBase::PARAM_DFLT]
473 : null;
474 if ( is_bool( $dflt ) ) {
475 $settings[ApiBase::PARAM_TYPE] = 'boolean';
476 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
477 $settings[ApiBase::PARAM_TYPE] = 'string';
478 } elseif ( is_int( $dflt ) ) {
479 $settings[ApiBase::PARAM_TYPE] = 'integer';
480 }
481 }
482 if ( isset( $settings[ApiBase::PARAM_TYPE] ) ) {
483 $type = $settings[ApiBase::PARAM_TYPE];
484 $multi = !empty( $settings[ApiBase::PARAM_ISMULTI] );
485 $hintPipeSeparated = true;
486 $count = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT2] )
487 ? $settings[ApiBase::PARAM_ISMULTI_LIMIT2] + 1
489
490 if ( is_array( $type ) ) {
491 $count = count( $type );
492 $deprecatedValues = isset( $settings[ApiBase::PARAM_DEPRECATED_VALUES] )
494 : [];
495 $links = isset( $settings[ApiBase::PARAM_VALUE_LINKS] )
496 ? $settings[ApiBase::PARAM_VALUE_LINKS]
497 : [];
498 $values = array_map( function ( $v ) use ( $links, $deprecatedValues ) {
499 $attr = [];
500 if ( $v !== '' ) {
501 // We can't know whether this contains LTR or RTL text.
502 $attr['dir'] = 'auto';
503 }
504 if ( isset( $deprecatedValues[$v] ) ) {
505 $attr['class'] = 'apihelp-deprecated-value';
506 }
507 $ret = $attr ? Html::element( 'span', $attr, $v ) : $v;
508 if ( isset( $links[$v] ) ) {
509 $ret = "[[{$links[$v]}|$ret]]";
510 }
511 return $ret;
512 }, $type );
513 $i = array_search( '', $type, true );
514 if ( $i === false ) {
515 $values = $context->getLanguage()->commaList( $values );
516 } else {
517 unset( $values[$i] );
518 $values = $context->msg( 'api-help-param-list-can-be-empty' )
519 ->numParams( count( $values ) )
520 ->params( $context->getLanguage()->commaList( $values ) )
521 ->parse();
522 }
523 $info[] = $context->msg( 'api-help-param-list' )
524 ->params( $multi ? 2 : 1 )
525 ->params( $values )
526 ->parse();
527 $hintPipeSeparated = false;
528 } else {
529 switch ( $type ) {
530 case 'submodule':
531 $groups[] = $name;
532
533 if ( isset( $settings[ApiBase::PARAM_SUBMODULE_MAP] ) ) {
534 $map = $settings[ApiBase::PARAM_SUBMODULE_MAP];
535 $defaultAttrs = [];
536 } else {
537 $prefix = $module->isMain() ? '' : ( $module->getModulePath() . '+' );
538 $map = [];
539 foreach ( $module->getModuleManager()->getNames( $name ) as $submoduleName ) {
540 $map[$submoduleName] = $prefix . $submoduleName;
541 }
542 $defaultAttrs = [ 'dir' => 'ltr', 'lang' => 'en' ];
543 }
544 ksort( $map );
545
546 $submodules = [];
547 $deprecatedSubmodules = [];
548 foreach ( $map as $v => $m ) {
549 $attrs = $defaultAttrs;
550 $arr = &$submodules;
551 try {
552 $submod = $module->getModuleFromPath( $m );
553 if ( $submod ) {
554 if ( $submod->isDeprecated() ) {
555 $arr = &$deprecatedSubmodules;
556 $attrs['class'] = 'apihelp-deprecated-value';
557 }
558 }
559 } catch ( ApiUsageException $ex ) {
560 // Ignore
561 }
562 if ( $attrs ) {
563 $v = Html::element( 'span', $attrs, $v );
564 }
565 $arr[] = "[[Special:ApiHelp/{$m}|{$v}]]";
566 }
567 $submodules = array_merge( $submodules, $deprecatedSubmodules );
568 $count = count( $submodules );
569 $info[] = $context->msg( 'api-help-param-list' )
570 ->params( $multi ? 2 : 1 )
571 ->params( $context->getLanguage()->commaList( $submodules ) )
572 ->parse();
573 $hintPipeSeparated = false;
574 // No type message necessary, we have a list of values.
575 $type = null;
576 break;
577
578 case 'namespace':
579 $namespaces = MWNamespace::getValidNamespaces();
580 if ( isset( $settings[ApiBase::PARAM_EXTRA_NAMESPACES] ) &&
581 is_array( $settings[ApiBase::PARAM_EXTRA_NAMESPACES] )
582 ) {
583 $namespaces = array_merge(
586 );
587 }
588 sort( $namespaces );
589 $count = count( $namespaces );
590 $info[] = $context->msg( 'api-help-param-list' )
591 ->params( $multi ? 2 : 1 )
592 ->params( $context->getLanguage()->commaList( $namespaces ) )
593 ->parse();
594 $hintPipeSeparated = false;
595 // No type message necessary, we have a list of values.
596 $type = null;
597 break;
598
599 case 'tags':
601 $count = count( $tags );
602 $info[] = $context->msg( 'api-help-param-list' )
603 ->params( $multi ? 2 : 1 )
604 ->params( $context->getLanguage()->commaList( $tags ) )
605 ->parse();
606 $hintPipeSeparated = false;
607 $type = null;
608 break;
609
610 case 'limit':
611 if ( isset( $settings[ApiBase::PARAM_MAX2] ) ) {
612 $info[] = $context->msg( 'api-help-param-limit2' )
613 ->numParams( $settings[ApiBase::PARAM_MAX] )
614 ->numParams( $settings[ApiBase::PARAM_MAX2] )
615 ->parse();
616 } else {
617 $info[] = $context->msg( 'api-help-param-limit' )
618 ->numParams( $settings[ApiBase::PARAM_MAX] )
619 ->parse();
620 }
621 break;
622
623 case 'integer':
624 // Possible messages:
625 // api-help-param-integer-min,
626 // api-help-param-integer-max,
627 // api-help-param-integer-minmax
628 $suffix = '';
629 $min = $max = 0;
630 if ( isset( $settings[ApiBase::PARAM_MIN] ) ) {
631 $suffix .= 'min';
632 $min = $settings[ApiBase::PARAM_MIN];
633 }
634 if ( isset( $settings[ApiBase::PARAM_MAX] ) ) {
635 $suffix .= 'max';
636 $max = $settings[ApiBase::PARAM_MAX];
637 }
638 if ( $suffix !== '' ) {
639 $info[] =
640 $context->msg( "api-help-param-integer-$suffix" )
641 ->params( $multi ? 2 : 1 )
642 ->numParams( $min, $max )
643 ->parse();
644 }
645 break;
646
647 case 'upload':
648 $info[] = $context->msg( 'api-help-param-upload' )
649 ->parse();
650 // No type message necessary, api-help-param-upload should handle it.
651 $type = null;
652 break;
653
654 case 'string':
655 case 'text':
656 // Displaying a type message here would be useless.
657 $type = null;
658 break;
659 }
660 }
661
662 // Add type. Messages for grep: api-help-param-type-limit
663 // api-help-param-type-integer api-help-param-type-boolean
664 // api-help-param-type-timestamp api-help-param-type-user
665 // api-help-param-type-password
666 if ( is_string( $type ) ) {
667 $msg = $context->msg( "api-help-param-type-$type" );
668 if ( !$msg->isDisabled() ) {
669 $info[] = $msg->params( $multi ? 2 : 1 )->parse();
670 }
671 }
672
673 if ( $multi ) {
674 $extra = [];
675 $lowcount = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT1] )
678 $highcount = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT2] )
681
682 if ( $hintPipeSeparated ) {
683 $extra[] = $context->msg( 'api-help-param-multi-separate' )->parse();
684 }
685 if ( $count > $lowcount ) {
686 if ( $lowcount === $highcount ) {
687 $msg = $context->msg( 'api-help-param-multi-max-simple' )
688 ->numParams( $lowcount );
689 } else {
690 $msg = $context->msg( 'api-help-param-multi-max' )
691 ->numParams( $lowcount, $highcount );
692 }
693 $extra[] = $msg->parse();
694 }
695 if ( $extra ) {
696 $info[] = implode( ' ', $extra );
697 }
698
699 $allowAll = isset( $settings[ApiBase::PARAM_ALL] )
700 ? $settings[ApiBase::PARAM_ALL]
701 : false;
702 if ( $allowAll || $settings[ApiBase::PARAM_TYPE] === 'namespace' ) {
703 if ( $settings[ApiBase::PARAM_TYPE] === 'namespace' ) {
704 $allSpecifier = ApiBase::ALL_DEFAULT_STRING;
705 } else {
706 $allSpecifier = ( is_string( $allowAll )
707 ? $allowAll : ApiBase::ALL_DEFAULT_STRING );
708 }
709 $info[] = $context->msg( 'api-help-param-multi-all' )
710 ->params( $allSpecifier )
711 ->parse();
712 }
713 }
714 }
715
716 if ( isset( $settings[self::PARAM_MAX_BYTES] ) ) {
717 $info[] = $context->msg( 'api-help-param-maxbytes' )
718 ->numParams( $settings[self::PARAM_MAX_BYTES] );
719 }
720 if ( isset( $settings[self::PARAM_MAX_CHARS] ) ) {
721 $info[] = $context->msg( 'api-help-param-maxchars' )
722 ->numParams( $settings[self::PARAM_MAX_CHARS] );
723 }
724
725 // Add default
726 $default = isset( $settings[ApiBase::PARAM_DFLT] )
727 ? $settings[ApiBase::PARAM_DFLT]
728 : null;
729 if ( $default === '' ) {
730 $info[] = $context->msg( 'api-help-param-default-empty' )
731 ->parse();
732 } elseif ( $default !== null && $default !== false ) {
733 // We can't know whether this contains LTR or RTL text.
734 $info[] = $context->msg( 'api-help-param-default' )
735 ->params( Html::element( 'span', [ 'dir' => 'auto' ], $default ) )
736 ->parse();
737 }
738
739 if ( !array_filter( $description ) ) {
740 $description = [ self::wrap(
741 $context->msg( 'api-help-param-no-description' ),
742 'apihelp-empty'
743 ) ];
744 }
745
746 // Add "deprecated" flag
747 if ( !empty( $settings[ApiBase::PARAM_DEPRECATED] ) ) {
748 $help['parameters'] .= Html::openElement( 'dd',
749 [ 'class' => 'info' ] );
750 $help['parameters'] .= self::wrap(
751 $context->msg( 'api-help-param-deprecated' ),
752 'apihelp-deprecated', 'strong'
753 );
754 $help['parameters'] .= Html::closeElement( 'dd' );
755 }
756
757 if ( $description ) {
758 $description = implode( '', $description );
759 $description = preg_replace( '!\s*</([oud]l)>\s*<\1>\s*!', "\n", $description );
760 $help['parameters'] .= Html::rawElement( 'dd',
761 [ 'class' => 'description' ], $description );
762 }
763
764 foreach ( $info as $i ) {
765 $help['parameters'] .= Html::rawElement( 'dd', [ 'class' => 'info' ], $i );
766 }
767 }
768
769 if ( $dynamicParams !== null ) {
770 $dynamicParams = ApiBase::makeMessage( $dynamicParams, $context, [
771 $module->getModulePrefix(),
772 $module->getModuleName(),
773 $module->getModulePath()
774 ] );
775 $help['parameters'] .= Html::element( 'dt', null, '*' );
776 $help['parameters'] .= Html::rawElement( 'dd',
777 [ 'class' => 'description' ], $dynamicParams->parse() );
778 }
779
780 $help['parameters'] .= Html::closeElement( 'dl' );
781 $help['parameters'] .= Html::closeElement( 'div' );
782 }
783
784 $examples = $module->getExamplesMessages();
785 if ( $examples ) {
786 $help['examples'] .= Html::openElement( 'div',
787 [ 'class' => 'apihelp-block apihelp-examples' ] );
788 $msg = $context->msg( 'api-help-examples' );
789 if ( !$msg->isDisabled() ) {
790 $help['examples'] .= self::wrap(
791 $msg->numParams( count( $examples ) ), 'apihelp-block-head', 'div'
792 );
793 }
794
795 $help['examples'] .= Html::openElement( 'dl' );
796 foreach ( $examples as $qs => $msg ) {
797 $msg = ApiBase::makeMessage( $msg, $context, [
798 $module->getModulePrefix(),
799 $module->getModuleName(),
800 $module->getModulePath()
801 ] );
802
803 $link = wfAppendQuery( wfScript( 'api' ), $qs );
804 $sandbox = SpecialPage::getTitleFor( 'ApiSandbox' )->getLocalURL() . '#' . $qs;
805 $help['examples'] .= Html::rawElement( 'dt', null, $msg->parse() );
806 $help['examples'] .= Html::rawElement( 'dd', null,
807 Html::element( 'a', [ 'href' => $link, 'dir' => 'ltr' ], "api.php?$qs" ) . ' ' .
808 Html::rawElement( 'a', [ 'href' => $sandbox ],
809 $context->msg( 'api-help-open-in-apisandbox' )->parse() )
810 );
811 }
812 $help['examples'] .= Html::closeElement( 'dl' );
813 $help['examples'] .= Html::closeElement( 'div' );
814 }
815
816 $subtocnumber = $tocnumber;
817 $subtocnumber[$level + 1] = 0;
818 $suboptions = [
819 'submodules' => $options['recursivesubmodules'],
820 'headerlevel' => $level + 1,
821 'tocnumber' => &$subtocnumber,
822 'noheader' => false,
823 ] + $options;
824
825 if ( $options['submodules'] && $module->getModuleManager() ) {
826 $manager = $module->getModuleManager();
827 $submodules = [];
828 foreach ( $groups as $group ) {
829 $names = $manager->getNames( $group );
830 sort( $names );
831 foreach ( $names as $name ) {
832 $submodules[] = $manager->getModule( $name );
833 }
834 }
835 $help['submodules'] .= self::getHelpInternal(
836 $context,
837 $submodules,
838 $suboptions,
839 $haveModules
840 );
841 }
842
843 $module->modifyHelp( $help, $suboptions, $haveModules );
844
845 Hooks::run( 'APIHelpModifyOutput', [ $module, &$help, $suboptions, &$haveModules ] );
846
847 $out .= implode( "\n", $help );
848 }
849
850 return $out;
851 }
852
853 public function shouldCheckMaxlag() {
854 return false;
855 }
856
857 public function isReadMode() {
858 return false;
859 }
860
861 public function getCustomPrinter() {
862 $params = $this->extractRequestParams();
863 if ( $params['wrap'] ) {
864 return null;
865 }
866
867 $main = $this->getMain();
868 $errorPrinter = $main->createPrinterByName( $main->getParameter( 'format' ) );
869 return new ApiFormatRaw( $main, $errorPrinter );
870 }
871
872 public function getAllowedParams() {
873 return [
874 'modules' => [
875 ApiBase::PARAM_DFLT => 'main',
877 ],
878 'submodules' => false,
879 'recursivesubmodules' => false,
880 'wrap' => false,
881 'toc' => false,
882 ];
883 }
884
885 protected function getExamplesMessages() {
886 return [
887 'action=help'
888 => 'apihelp-help-example-main',
889 'action=help&modules=query&submodules=1'
890 => 'apihelp-help-example-submodules',
891 'action=help&recursivesubmodules=1'
892 => 'apihelp-help-example-recursive',
893 'action=help&modules=help'
894 => 'apihelp-help-example-help',
895 'action=help&modules=query+info|query+categorymembers'
896 => 'apihelp-help-example-query',
897 ];
898 }
899
900 public function getHelpUrls() {
901 return [
902 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Main_page',
903 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:FAQ',
904 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Quick_start_guide',
905 ];
906 }
907}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:37
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition ApiBase.php:111
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right,...
Definition ApiBase.php:96
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is 'submodule', map parameter values to submodule paths.
Definition ApiBase.php:165
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition ApiBase.php:105
getModuleFromPath( $path)
Get a module from its module path.
Definition ApiBase.php:603
static makeMessage( $msg, IContextSource $context, array $params=null)
Create a Message from a string or array.
Definition ApiBase.php:1741
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:90
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
Definition ApiBase.php:202
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
Definition ApiBase.php:208
getMain()
Get the main module.
Definition ApiBase.php:537
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:87
const PARAM_HELP_MSG_INFO
(array) Specify additional information tags for the parameter.
Definition ApiBase.php:141
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:48
const PARAM_VALUE_LINKS
(string[]) When PARAM_TYPE is an array, this may be an array mapping those values to page titles whic...
Definition ApiBase.php:148
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:749
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
Definition ApiBase.php:215
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition ApiBase.php:99
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition ApiBase.php:240
getResult()
Get the result object.
Definition ApiBase.php:641
getModulePath()
Get the path to this module.
Definition ApiBase.php:585
const PARAM_EXTRA_NAMESPACES
(int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
Definition ApiBase.php:186
const LIMIT_SML1
Slow query, standard limit.
Definition ApiBase.php:238
const PARAM_ALL
(boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,...
Definition ApiBase.php:180
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When set, the result could take longer to generate, but should be more thoro...
Definition ApiBase.php:247
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:521
const ALL_DEFAULT_STRING
Definition ApiBase.php:231
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:51
Formatter that spits out anything you like with any desired MIME type.
Class to output help for an API module.
Definition ApiHelp.php:32
static wrap(Message $msg, $class, $tag='span')
Wrap a message in HTML with a class.
Definition ApiHelp.php:209
isReadMode()
Indicates whether this module requires read rights.
Definition ApiHelp.php:857
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition ApiHelp.php:33
getExamplesMessages()
Returns usage examples for this module.
Definition ApiHelp.php:885
static fixHelpLinks( $html, $helptitle=null, $localModules=[])
Replace Special:ApiHelp links with links to api.php.
Definition ApiHelp.php:170
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition ApiHelp.php:872
getHelpUrls()
Return links to more detailed help pages about the module.
Definition ApiHelp.php:900
static getHelpInternal(IContextSource $context, array $modules, array $options, &$haveModules)
Recursively-called function to actually construct the help.
Definition ApiHelp.php:224
static getHelp(IContextSource $context, $modules, array $options)
Generate help for the specified modules.
Definition ApiHelp.php:93
shouldCheckMaxlag()
Indicates if this module needs maxlag to be checked.
Definition ApiHelp.php:853
getCustomPrinter()
If the module may only be used with a certain format module, it should override this method to return...
Definition ApiHelp.php:861
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:43
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Definition ApiResult.php:56
static setSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as subelements rather than attributes.
Exception used to abort API execution with an error.
static listExplicitlyDefinedTags()
Lists tags explicitly defined in the valid_tag table of the database.
IContextSource $context
getContext()
Get the base IContextSource object.
An IContextSource implementation which will inherit context from another source but allow individual ...
static generateTOC( $tree, $lang=false)
Generate a table of contents from a section tree.
Definition Linker.php:1604
MediaWikiServices is the service locator for the application scope of MediaWiki.
The Message class provides methods which fulfil two basic services:
Definition Message.php:159
parse()
Fully parse the text from wikitext to HTML.
Definition Message.php:920
This class should be covered by a general architecture document which does not exist as of January 20...
static getExtLicenseFileName( $extDir)
Obtains the full path of an extensions copying or license file if one exists.
static getVersion( $flags='', $lang=null)
Return a string of the MediaWiki version with Git revision if available.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
the array() calling protocol came about after MediaWiki 1.4rc1.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1993
namespace and then decline to actually register it & $namespaces
Definition hooks.txt:934
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2001
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:2005
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:864
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition hooks.txt:2013
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:3021
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Interface for objects which can provide a MediaWiki context on request.
getConfig()
Get the site configuration.
msg( $key)
This is the method for getting translated interface messages.
$cache
Definition mcc.php:33
$help
Definition mcc.php:32
$params