MediaWiki  master
ApiHelp.php
Go to the documentation of this file.
1 <?php
25 
32 class ApiHelp extends ApiBase {
33  public function execute() {
34  $params = $this->extractRequestParams();
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  $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
44  $context->setSkin( $skinFactory->makeSkin( 'apioutput' ) );
45  $context->setLanguage( $this->getMain()->getLanguage() );
46  $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
47  $out = new OutputPage( $context );
48  $out->setRobotPolicy( 'noindex,nofollow' );
49  $out->setCopyrightUrl( 'https://www.mediawiki.org/wiki/Special:MyLanguage/Copyright' );
50  $context->setOutput( $out );
51 
52  self::getHelp( $context, $modules, $params );
53 
54  // Grab the output from the skin
55  ob_start();
56  $context->getOutput()->output();
57  $html = ob_get_clean();
58 
59  $result = $this->getResult();
60  if ( $params['wrap'] ) {
61  $data = [
62  'mime' => 'text/html',
63  'filename' => 'api-help.html',
64  'help' => $html,
65  ];
66  ApiResult::setSubelementsList( $data, 'help' );
67  $result->addValue( null, $this->getModuleName(), $data );
68  } else {
69  $result->reset();
70  $result->addValue( null, 'text', $html, ApiResult::NO_SIZE_CHECK );
71  $result->addValue( null, 'mime', 'text/html', ApiResult::NO_SIZE_CHECK );
72  $result->addValue( null, 'filename', 'api-help.html', ApiResult::NO_SIZE_CHECK );
73  }
74  }
75 
95  public static function getHelp( IContextSource $context, $modules, array $options ) {
96  if ( !is_array( $modules ) ) {
97  $modules = [ $modules ];
98  }
99 
100  $out = $context->getOutput();
101  $out->addModuleStyles( [
102  'mediawiki.hlist',
103  'mediawiki.apipretty',
104  ] );
105  if ( !empty( $options['toc'] ) ) {
106  $out->addModuleStyles( 'mediawiki.toc.styles' );
107  }
108  $out->setPageTitle( $context->msg( 'api-help-title' ) );
109 
110  $services = MediaWikiServices::getInstance();
111  $cache = $services->getMainWANObjectCache();
112  $cacheKey = null;
113  if ( count( $modules ) == 1 && $modules[0] instanceof ApiMain &&
114  $options['recursivesubmodules'] &&
115  $context->getLanguage()->equals( $services->getContentLanguage() )
116  ) {
117  $cacheHelpTimeout = $context->getConfig()->get( 'APICacheHelpTimeout' );
118  if ( $cacheHelpTimeout > 0 ) {
119  // Get help text from cache if present
120  $cacheKey = $cache->makeKey( 'apihelp', $modules[0]->getModulePath(),
121  (int)!empty( $options['toc'] ),
122  str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
123  $cached = $cache->get( $cacheKey );
124  if ( $cached ) {
125  $out->addHTML( $cached );
126  return;
127  }
128  }
129  }
130  if ( $out->getHTML() !== '' ) {
131  // Don't save to cache, there's someone else's content in the page
132  // already
133  $cacheKey = null;
134  }
135 
136  $options['recursivesubmodules'] = !empty( $options['recursivesubmodules'] );
137  $options['submodules'] = $options['recursivesubmodules'] || !empty( $options['submodules'] );
138 
139  // Prepend lead
140  if ( empty( $options['nolead'] ) ) {
141  $msg = $context->msg( 'api-help-lead' );
142  if ( !$msg->isDisabled() ) {
143  $out->addHTML( $msg->parseAsBlock() );
144  }
145  }
146 
147  $haveModules = [];
148  $html = self::getHelpInternal( $context, $modules, $options, $haveModules );
149  if ( !empty( $options['toc'] ) && $haveModules ) {
150  $out->addHTML( Linker::generateTOC( $haveModules, $context->getLanguage() ) );
151  }
152  $out->addHTML( $html );
153 
154  $helptitle = $options['helptitle'] ?? null;
155  $html = self::fixHelpLinks( $out->getHTML(), $helptitle, $haveModules );
156  $out->clearHTML();
157  $out->addHTML( $html );
158 
159  if ( $cacheKey !== null ) {
160  $cache->set( $cacheKey, $out->getHTML(), $cacheHelpTimeout );
161  }
162  }
163 
172  public static function fixHelpLinks( $html, $helptitle = null, $localModules = [] ) {
173  $formatter = new HtmlFormatter( $html );
174  $doc = $formatter->getDoc();
175  $xpath = new DOMXPath( $doc );
176  $nodes = $xpath->query( '//a[@href][not(contains(@class,\'apihelp-linktrail\'))]' );
177  foreach ( $nodes as $node ) {
178  $href = $node->getAttribute( 'href' );
179  do {
180  $old = $href;
181  $href = rawurldecode( $href );
182  } while ( $old !== $href );
183  if ( preg_match( '!Special:ApiHelp/([^&/|#]+)((?:#.*)?)!', $href, $m ) ) {
184  if ( isset( $localModules[$m[1]] ) ) {
185  $href = $m[2] === '' ? '#' . $m[1] : $m[2];
186  } elseif ( $helptitle !== null ) {
187  $href = Title::newFromText( str_replace( '$1', $m[1], $helptitle ) . $m[2] )
188  ->getFullURL();
189  } else {
190  $href = wfAppendQuery( wfScript( 'api' ), [
191  'action' => 'help',
192  'modules' => $m[1],
193  ] ) . $m[2];
194  }
195  $node->setAttribute( 'href', $href );
196  $node->removeAttribute( 'title' );
197  }
198  }
199 
200  return $formatter->getText();
201  }
202 
211  private static function wrap( Message $msg, $class, $tag = 'span' ) {
212  return Html::rawElement( $tag, [ 'class' => $class ],
213  $msg->parse()
214  );
215  }
216 
226  private static function getHelpInternal( IContextSource $context, array $modules,
227  array $options, &$haveModules
228  ) {
229  $out = '';
230 
231  $level = empty( $options['headerlevel'] ) ? 2 : $options['headerlevel'];
232  if ( empty( $options['tocnumber'] ) ) {
233  $tocnumber = [ 2 => 0 ];
234  } else {
235  $tocnumber = &$options['tocnumber'];
236  }
237 
238  foreach ( $modules as $module ) {
239  $tocnumber[$level]++;
240  $path = $module->getModulePath();
241  $module->setContext( $context );
242  $help = [
243  'header' => '',
244  'flags' => '',
245  'description' => '',
246  'help-urls' => '',
247  'parameters' => '',
248  'examples' => '',
249  'submodules' => '',
250  ];
251 
252  if ( empty( $options['noheader'] ) || !empty( $options['toc'] ) ) {
253  $anchor = $path;
254  $i = 1;
255  while ( isset( $haveModules[$anchor] ) ) {
256  $anchor = $path . '|' . ++$i;
257  }
258 
259  if ( $module->isMain() ) {
260  $headerContent = $context->msg( 'api-help-main-header' )->parse();
261  $headerAttr = [
262  'class' => 'apihelp-header',
263  ];
264  } else {
265  $name = $module->getModuleName();
266  $headerContent = $module->getParent()->getModuleManager()->getModuleGroup( $name ) .
267  "=$name";
268  if ( $module->getModulePrefix() !== '' ) {
269  $headerContent .= ' ' .
270  $context->msg( 'parentheses', $module->getModulePrefix() )->parse();
271  }
272  // Module names are always in English and not localized,
273  // so English language and direction must be set explicitly,
274  // otherwise parentheses will get broken in RTL wikis
275  $headerAttr = [
276  'class' => 'apihelp-header apihelp-module-name',
277  'dir' => 'ltr',
278  'lang' => 'en',
279  ];
280  }
281 
282  $headerAttr['id'] = $anchor;
283 
284  $haveModules[$anchor] = [
285  'toclevel' => count( $tocnumber ),
286  'level' => $level,
287  'anchor' => $anchor,
288  'line' => $headerContent,
289  'number' => implode( '.', $tocnumber ),
290  'index' => false,
291  ];
292  if ( empty( $options['noheader'] ) ) {
293  $help['header'] .= Html::element(
294  'h' . min( 6, $level ),
295  $headerAttr,
296  $headerContent
297  );
298  }
299  } else {
300  $haveModules[$path] = true;
301  }
302 
303  $links = [];
304  $any = false;
305  for ( $m = $module; $m !== null; $m = $m->getParent() ) {
306  $name = $m->getModuleName();
307  if ( $name === 'main_int' ) {
308  $name = 'main';
309  }
310 
311  if ( count( $modules ) === 1 && $m === $modules[0] &&
312  !( !empty( $options['submodules'] ) && $m->getModuleManager() )
313  ) {
314  $link = Html::element( 'b', [ 'dir' => 'ltr', 'lang' => 'en' ], $name );
315  } else {
316  $link = SpecialPage::getTitleFor( 'ApiHelp', $m->getModulePath() )->getLocalURL();
317  $link = Html::element( 'a',
318  [ 'href' => $link, 'class' => 'apihelp-linktrail', 'dir' => 'ltr', 'lang' => 'en' ],
319  $name
320  );
321  $any = true;
322  }
323  array_unshift( $links, $link );
324  }
325  if ( $any ) {
326  $help['header'] .= self::wrap(
327  $context->msg( 'parentheses' )
328  ->rawParams( $context->getLanguage()->pipeList( $links ) ),
329  'apihelp-linktrail', 'div'
330  );
331  }
332 
333  $flags = $module->getHelpFlags();
334  $help['flags'] .= Html::openElement( 'div',
335  [ 'class' => 'apihelp-block apihelp-flags' ] );
336  $msg = $context->msg( 'api-help-flags' );
337  if ( !$msg->isDisabled() ) {
338  $help['flags'] .= self::wrap(
339  $msg->numParams( count( $flags ) ), 'apihelp-block-head', 'div'
340  );
341  }
342  $help['flags'] .= Html::openElement( 'ul' );
343  foreach ( $flags as $flag ) {
344  $help['flags'] .= Html::rawElement( 'li', null,
345  self::wrap( $context->msg( "api-help-flag-$flag" ), "apihelp-flag-$flag" )
346  );
347  }
348  $sourceInfo = $module->getModuleSourceInfo();
349  if ( $sourceInfo ) {
350  if ( isset( $sourceInfo['namemsg'] ) ) {
351  $extname = $context->msg( $sourceInfo['namemsg'] )->text();
352  } else {
353  // Probably English, so wrap it.
354  $extname = Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $sourceInfo['name'] );
355  }
356  $help['flags'] .= Html::rawElement( 'li', null,
357  self::wrap(
358  $context->msg( 'api-help-source', $extname, $sourceInfo['name'] ),
359  'apihelp-source'
360  )
361  );
362 
363  $link = SpecialPage::getTitleFor( 'Version', 'License/' . $sourceInfo['name'] );
364  if ( isset( $sourceInfo['license-name'] ) ) {
365  $msg = $context->msg( 'api-help-license', $link,
366  Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $sourceInfo['license-name'] )
367  );
368  } elseif ( SpecialVersion::getExtLicenseFileName( dirname( $sourceInfo['path'] ) ) ) {
369  $msg = $context->msg( 'api-help-license-noname', $link );
370  } else {
371  $msg = $context->msg( 'api-help-license-unknown' );
372  }
373  $help['flags'] .= Html::rawElement( 'li', null,
374  self::wrap( $msg, 'apihelp-license' )
375  );
376  } else {
377  $help['flags'] .= Html::rawElement( 'li', null,
378  self::wrap( $context->msg( 'api-help-source-unknown' ), 'apihelp-source' )
379  );
380  $help['flags'] .= Html::rawElement( 'li', null,
381  self::wrap( $context->msg( 'api-help-license-unknown' ), 'apihelp-license' )
382  );
383  }
384  $help['flags'] .= Html::closeElement( 'ul' );
385  $help['flags'] .= Html::closeElement( 'div' );
386 
387  foreach ( $module->getFinalDescription() as $msg ) {
388  $msg->setContext( $context );
389  $help['description'] .= $msg->parseAsBlock();
390  }
391 
392  $urls = $module->getHelpUrls();
393  if ( $urls ) {
394  $help['help-urls'] .= Html::openElement( 'div',
395  [ 'class' => 'apihelp-block apihelp-help-urls' ]
396  );
397  $msg = $context->msg( 'api-help-help-urls' );
398  if ( !$msg->isDisabled() ) {
399  $help['help-urls'] .= self::wrap(
400  $msg->numParams( count( $urls ) ), 'apihelp-block-head', 'div'
401  );
402  }
403  if ( !is_array( $urls ) ) {
404  $urls = [ $urls ];
405  }
406  $help['help-urls'] .= Html::openElement( 'ul' );
407  foreach ( $urls as $url ) {
408  $help['help-urls'] .= Html::rawElement( 'li', null,
409  Html::element( 'a', [ 'href' => $url, 'dir' => 'ltr' ], $url )
410  );
411  }
412  $help['help-urls'] .= Html::closeElement( 'ul' );
413  $help['help-urls'] .= Html::closeElement( 'div' );
414  }
415 
416  $params = $module->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
417  $dynamicParams = $module->dynamicParameterDocumentation();
418  $groups = [];
419  if ( $params || $dynamicParams !== null ) {
420  $help['parameters'] .= Html::openElement( 'div',
421  [ 'class' => 'apihelp-block apihelp-parameters' ]
422  );
423  $msg = $context->msg( 'api-help-parameters' );
424  if ( !$msg->isDisabled() ) {
425  $help['parameters'] .= self::wrap(
426  $msg->numParams( count( $params ) ), 'apihelp-block-head', 'div'
427  );
428  }
429  $help['parameters'] .= Html::openElement( 'dl' );
430 
431  $descriptions = $module->getFinalParamDescription();
432 
433  foreach ( $params as $name => $settings ) {
434  if ( !is_array( $settings ) ) {
435  $settings = [ ApiBase::PARAM_DFLT => $settings ];
436  }
437 
438  $help['parameters'] .= Html::rawElement( 'dt', null,
439  Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $module->encodeParamName( $name ) )
440  );
441 
442  // Add description
443  $description = [];
444  if ( isset( $descriptions[$name] ) ) {
445  foreach ( $descriptions[$name] as $msg ) {
446  $msg->setContext( $context );
447  $description[] = $msg->parseAsBlock();
448  }
449  }
450 
451  // Add usage info
452  $info = [];
453 
454  // Required?
455  if ( !empty( $settings[ApiBase::PARAM_REQUIRED] ) ) {
456  $info[] = $context->msg( 'api-help-param-required' )->parse();
457  }
458 
459  // Custom info?
460  if ( !empty( $settings[ApiBase::PARAM_HELP_MSG_INFO] ) ) {
461  foreach ( $settings[ApiBase::PARAM_HELP_MSG_INFO] as $i ) {
462  $tag = array_shift( $i );
463  $info[] = $context->msg( "apihelp-{$path}-paraminfo-{$tag}" )
464  ->numParams( count( $i ) )
465  ->params( $context->getLanguage()->commaList( $i ) )
466  ->params( $module->getModulePrefix() )
467  ->parse();
468  }
469  }
470 
471  // Templated?
472  if ( !empty( $settings[ApiBase::PARAM_TEMPLATE_VARS] ) ) {
473  $vars = [];
474  $msg = 'api-help-param-templated-var-first';
475  foreach ( $settings[ApiBase::PARAM_TEMPLATE_VARS] as $k => $v ) {
476  $vars[] = $context->msg( $msg, $k, $module->encodeParamName( $v ) );
477  $msg = 'api-help-param-templated-var';
478  }
479  $info[] = $context->msg( 'api-help-param-templated' )
480  ->numParams( count( $vars ) )
481  ->params( Message::listParam( $vars ) )
482  ->parse();
483  }
484 
485  // Type documentation
486  if ( !isset( $settings[ApiBase::PARAM_TYPE] ) ) {
487  $dflt = $settings[ApiBase::PARAM_DFLT] ?? null;
488  if ( is_bool( $dflt ) ) {
489  $settings[ApiBase::PARAM_TYPE] = 'boolean';
490  } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
491  $settings[ApiBase::PARAM_TYPE] = 'string';
492  } elseif ( is_int( $dflt ) ) {
493  $settings[ApiBase::PARAM_TYPE] = 'integer';
494  }
495  }
496  if ( isset( $settings[ApiBase::PARAM_TYPE] ) ) {
497  $type = $settings[ApiBase::PARAM_TYPE];
498  $multi = !empty( $settings[ApiBase::PARAM_ISMULTI] );
499  $hintPipeSeparated = true;
500  $count = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT2] )
501  ? $settings[ApiBase::PARAM_ISMULTI_LIMIT2] + 1
502  : ApiBase::LIMIT_SML2 + 1;
503 
504  if ( is_array( $type ) ) {
505  $count = count( $type );
506  $deprecatedValues = $settings[ApiBase::PARAM_DEPRECATED_VALUES] ?? [];
507  $links = $settings[ApiBase::PARAM_VALUE_LINKS] ?? [];
508  $values = array_map( function ( $v ) use ( $links, $deprecatedValues ) {
509  $attr = [];
510  if ( $v !== '' ) {
511  // We can't know whether this contains LTR or RTL text.
512  $attr['dir'] = 'auto';
513  }
514  if ( isset( $deprecatedValues[$v] ) ) {
515  $attr['class'] = 'apihelp-deprecated-value';
516  }
517  $ret = $attr ? Html::element( 'span', $attr, $v ) : $v;
518  if ( isset( $links[$v] ) ) {
519  $ret = "[[{$links[$v]}|$ret]]";
520  }
521  return $ret;
522  }, $type );
523  $i = array_search( '', $type, true );
524  if ( $i === false ) {
525  $values = $context->getLanguage()->commaList( $values );
526  } else {
527  unset( $values[$i] );
528  $values = $context->msg( 'api-help-param-list-can-be-empty' )
529  ->numParams( count( $values ) )
530  ->params( $context->getLanguage()->commaList( $values ) )
531  ->parse();
532  }
533  $info[] = $context->msg( 'api-help-param-list' )
534  ->params( $multi ? 2 : 1 )
535  ->params( $values )
536  ->parse();
537  $hintPipeSeparated = false;
538  } else {
539  switch ( $type ) {
540  case 'submodule':
541  $groups[] = $name;
542 
543  if ( isset( $settings[ApiBase::PARAM_SUBMODULE_MAP] ) ) {
544  $map = $settings[ApiBase::PARAM_SUBMODULE_MAP];
545  $defaultAttrs = [];
546  } else {
547  $prefix = $module->isMain() ? '' : ( $module->getModulePath() . '+' );
548  $map = [];
549  foreach ( $module->getModuleManager()->getNames( $name ) as $submoduleName ) {
550  $map[$submoduleName] = $prefix . $submoduleName;
551  }
552  $defaultAttrs = [ 'dir' => 'ltr', 'lang' => 'en' ];
553  }
554  ksort( $map );
555 
556  $submodules = [];
557  $deprecatedSubmodules = [];
558  foreach ( $map as $v => $m ) {
559  $attrs = $defaultAttrs;
560  $arr = &$submodules;
561  try {
562  $submod = $module->getModuleFromPath( $m );
563  if ( $submod && $submod->isDeprecated() ) {
564  $arr = &$deprecatedSubmodules;
565  $attrs['class'] = 'apihelp-deprecated-value';
566  }
567  } catch ( ApiUsageException $ex ) {
568  // Ignore
569  }
570  if ( $attrs ) {
571  $v = Html::element( 'span', $attrs, $v );
572  }
573  $arr[] = "[[Special:ApiHelp/{$m}|{$v}]]";
574  }
575  $submodules = array_merge( $submodules, $deprecatedSubmodules );
576  $count = count( $submodules );
577  $info[] = $context->msg( 'api-help-param-list' )
578  ->params( $multi ? 2 : 1 )
579  ->params( $context->getLanguage()->commaList( $submodules ) )
580  ->parse();
581  $hintPipeSeparated = false;
582  // No type message necessary, we have a list of values.
583  $type = null;
584  break;
585 
586  case 'namespace':
587  $namespaces = MediaWikiServices::getInstance()->
588  getNamespaceInfo()->getValidNamespaces();
589  if ( isset( $settings[ApiBase::PARAM_EXTRA_NAMESPACES] ) &&
590  is_array( $settings[ApiBase::PARAM_EXTRA_NAMESPACES] )
591  ) {
592  $namespaces = array_merge( $namespaces, $settings[ApiBase::PARAM_EXTRA_NAMESPACES] );
593  }
594  sort( $namespaces );
595  $count = count( $namespaces );
596  $info[] = $context->msg( 'api-help-param-list' )
597  ->params( $multi ? 2 : 1 )
598  ->params( $context->getLanguage()->commaList( $namespaces ) )
599  ->parse();
600  $hintPipeSeparated = false;
601  // No type message necessary, we have a list of values.
602  $type = null;
603  break;
604 
605  case 'tags':
607  $count = count( $tags );
608  $info[] = $context->msg( 'api-help-param-list' )
609  ->params( $multi ? 2 : 1 )
610  ->params( $context->getLanguage()->commaList( $tags ) )
611  ->parse();
612  $hintPipeSeparated = false;
613  $type = null;
614  break;
615 
616  case 'limit':
617  if ( isset( $settings[ApiBase::PARAM_MAX2] ) ) {
618  $info[] = $context->msg( 'api-help-param-limit2' )
619  ->numParams( $settings[ApiBase::PARAM_MAX] )
620  ->numParams( $settings[ApiBase::PARAM_MAX2] )
621  ->parse();
622  } else {
623  $info[] = $context->msg( 'api-help-param-limit' )
624  ->numParams( $settings[ApiBase::PARAM_MAX] )
625  ->parse();
626  }
627  break;
628 
629  case 'integer':
630  // Possible messages:
631  // api-help-param-integer-min,
632  // api-help-param-integer-max,
633  // api-help-param-integer-minmax
634  $suffix = '';
635  $min = $max = 0;
636  if ( isset( $settings[ApiBase::PARAM_MIN] ) ) {
637  $suffix .= 'min';
638  $min = $settings[ApiBase::PARAM_MIN];
639  }
640  if ( isset( $settings[ApiBase::PARAM_MAX] ) ) {
641  $suffix .= 'max';
642  $max = $settings[ApiBase::PARAM_MAX];
643  }
644  if ( $suffix !== '' ) {
645  $info[] =
646  $context->msg( "api-help-param-integer-$suffix" )
647  ->params( $multi ? 2 : 1 )
648  ->numParams( $min, $max )
649  ->parse();
650  }
651  break;
652 
653  case 'upload':
654  $info[] = $context->msg( 'api-help-param-upload' )
655  ->parse();
656  // No type message necessary, api-help-param-upload should handle it.
657  $type = null;
658  break;
659 
660  case 'string':
661  case 'text':
662  // Displaying a type message here would be useless.
663  $type = null;
664  break;
665  }
666  }
667 
668  // Add type. Messages for grep: api-help-param-type-limit
669  // api-help-param-type-integer api-help-param-type-boolean
670  // api-help-param-type-timestamp api-help-param-type-user
671  // api-help-param-type-password
672  if ( is_string( $type ) ) {
673  $msg = $context->msg( "api-help-param-type-$type" );
674  if ( !$msg->isDisabled() ) {
675  $info[] = $msg->params( $multi ? 2 : 1 )->parse();
676  }
677  }
678 
679  if ( $multi ) {
680  $extra = [];
681  $lowcount = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT1] )
682  ? $settings[ApiBase::PARAM_ISMULTI_LIMIT1]
684  $highcount = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT2] )
685  ? $settings[ApiBase::PARAM_ISMULTI_LIMIT2]
687 
688  if ( $hintPipeSeparated ) {
689  $extra[] = $context->msg( 'api-help-param-multi-separate' )->parse();
690  }
691  if ( $count > $lowcount ) {
692  if ( $lowcount === $highcount ) {
693  $msg = $context->msg( 'api-help-param-multi-max-simple' )
694  ->numParams( $lowcount );
695  } else {
696  $msg = $context->msg( 'api-help-param-multi-max' )
697  ->numParams( $lowcount, $highcount );
698  }
699  $extra[] = $msg->parse();
700  }
701  if ( $extra ) {
702  $info[] = implode( ' ', $extra );
703  }
704 
705  $allowAll = $settings[ApiBase::PARAM_ALL] ?? false;
706  if ( $allowAll || $settings[ApiBase::PARAM_TYPE] === 'namespace' ) {
707  if ( $settings[ApiBase::PARAM_TYPE] === 'namespace' ) {
708  $allSpecifier = ApiBase::ALL_DEFAULT_STRING;
709  } else {
710  $allSpecifier = ( is_string( $allowAll ) ? $allowAll : ApiBase::ALL_DEFAULT_STRING );
711  }
712  $info[] = $context->msg( 'api-help-param-multi-all' )
713  ->params( $allSpecifier )
714  ->parse();
715  }
716  }
717  }
718 
719  if ( isset( $settings[self::PARAM_MAX_BYTES] ) ) {
720  $info[] = $context->msg( 'api-help-param-maxbytes' )
721  ->numParams( $settings[self::PARAM_MAX_BYTES] );
722  }
723  if ( isset( $settings[self::PARAM_MAX_CHARS] ) ) {
724  $info[] = $context->msg( 'api-help-param-maxchars' )
725  ->numParams( $settings[self::PARAM_MAX_CHARS] );
726  }
727 
728  // Add default
729  $default = $settings[ApiBase::PARAM_DFLT] ?? null;
730  if ( $default === '' ) {
731  $info[] = $context->msg( 'api-help-param-default-empty' )
732  ->parse();
733  } elseif ( $default !== null && $default !== false ) {
734  // We can't know whether this contains LTR or RTL text.
735  $info[] = $context->msg( 'api-help-param-default' )
736  ->params( Html::element( 'span', [ 'dir' => 'auto' ], $default ) )
737  ->parse();
738  }
739 
740  if ( !array_filter( $description ) ) {
741  $description = [ self::wrap(
742  $context->msg( 'api-help-param-no-description' ),
743  'apihelp-empty'
744  ) ];
745  }
746 
747  // Add "deprecated" flag
748  if ( !empty( $settings[ApiBase::PARAM_DEPRECATED] ) ) {
749  $help['parameters'] .= Html::openElement( 'dd',
750  [ 'class' => 'info' ] );
751  $help['parameters'] .= self::wrap(
752  $context->msg( 'api-help-param-deprecated' ),
753  'apihelp-deprecated', 'strong'
754  );
755  $help['parameters'] .= Html::closeElement( 'dd' );
756  }
757 
758  if ( $description ) {
759  $description = implode( '', $description );
760  $description = preg_replace( '!\s*</([oud]l)>\s*<\1>\s*!', "\n", $description );
761  $help['parameters'] .= Html::rawElement( 'dd',
762  [ 'class' => 'description' ], $description );
763  }
764 
765  foreach ( $info as $i ) {
766  $help['parameters'] .= Html::rawElement( 'dd', [ 'class' => 'info' ], $i );
767  }
768  }
769 
770  if ( $dynamicParams !== null ) {
771  $dynamicParams = ApiBase::makeMessage( $dynamicParams, $context, [
772  $module->getModulePrefix(),
773  $module->getModuleName(),
774  $module->getModulePath()
775  ] );
776  $help['parameters'] .= Html::element( 'dt', null, '*' );
777  $help['parameters'] .= Html::rawElement( 'dd',
778  [ 'class' => 'description' ], $dynamicParams->parse() );
779  }
780 
781  $help['parameters'] .= Html::closeElement( 'dl' );
782  $help['parameters'] .= Html::closeElement( 'div' );
783  }
784 
785  $examples = $module->getExamplesMessages();
786  if ( $examples ) {
787  $help['examples'] .= Html::openElement( 'div',
788  [ 'class' => 'apihelp-block apihelp-examples' ] );
789  $msg = $context->msg( 'api-help-examples' );
790  if ( !$msg->isDisabled() ) {
791  $help['examples'] .= self::wrap(
792  $msg->numParams( count( $examples ) ), 'apihelp-block-head', 'div'
793  );
794  }
795 
796  $help['examples'] .= Html::openElement( 'dl' );
797  foreach ( $examples as $qs => $msg ) {
798  $msg = ApiBase::makeMessage( $msg, $context, [
799  $module->getModulePrefix(),
800  $module->getModuleName(),
801  $module->getModulePath()
802  ] );
803 
804  $link = wfAppendQuery( wfScript( 'api' ), $qs );
805  $sandbox = SpecialPage::getTitleFor( 'ApiSandbox' )->getLocalURL() . '#' . $qs;
806  $help['examples'] .= Html::rawElement( 'dt', null, $msg->parse() );
807  $help['examples'] .= Html::rawElement( 'dd', null,
808  Html::element( 'a', [ 'href' => $link, 'dir' => 'ltr' ], "api.php?$qs" ) . ' ' .
809  Html::rawElement( 'a', [ 'href' => $sandbox ],
810  $context->msg( 'api-help-open-in-apisandbox' )->parse() )
811  );
812  }
813  $help['examples'] .= Html::closeElement( 'dl' );
814  $help['examples'] .= Html::closeElement( 'div' );
815  }
816 
817  $subtocnumber = $tocnumber;
818  $subtocnumber[$level + 1] = 0;
819  $suboptions = [
820  'submodules' => $options['recursivesubmodules'],
821  'headerlevel' => $level + 1,
822  'tocnumber' => &$subtocnumber,
823  'noheader' => false,
824  ] + $options;
825 
826  if ( $options['submodules'] && $module->getModuleManager() ) {
827  $manager = $module->getModuleManager();
828  $submodules = [];
829  foreach ( $groups as $group ) {
830  $names = $manager->getNames( $group );
831  sort( $names );
832  foreach ( $names as $name ) {
833  $submodules[] = $manager->getModule( $name );
834  }
835  }
836  $help['submodules'] .= self::getHelpInternal(
837  $context,
838  $submodules,
839  $suboptions,
840  $haveModules
841  );
842  }
843 
844  $module->modifyHelp( $help, $suboptions, $haveModules );
845 
846  Hooks::run( 'APIHelpModifyOutput', [ $module, &$help, $suboptions, &$haveModules ] );
847 
848  $out .= implode( "\n", $help );
849  }
850 
851  return $out;
852  }
853 
854  public function shouldCheckMaxlag() {
855  return false;
856  }
857 
858  public function isReadMode() {
859  return false;
860  }
861 
862  public function getCustomPrinter() {
863  $params = $this->extractRequestParams();
864  if ( $params['wrap'] ) {
865  return null;
866  }
867 
868  $main = $this->getMain();
869  $errorPrinter = $main->createPrinterByName( $main->getParameter( 'format' ) );
870  return new ApiFormatRaw( $main, $errorPrinter );
871  }
872 
873  public function getAllowedParams() {
874  return [
875  'modules' => [
876  ApiBase::PARAM_DFLT => 'main',
877  ApiBase::PARAM_ISMULTI => true,
878  ],
879  'submodules' => false,
880  'recursivesubmodules' => false,
881  'wrap' => false,
882  'toc' => false,
883  ];
884  }
885 
886  protected function getExamplesMessages() {
887  return [
888  'action=help'
889  => 'apihelp-help-example-main',
890  'action=help&modules=query&submodules=1'
891  => 'apihelp-help-example-submodules',
892  'action=help&recursivesubmodules=1'
893  => 'apihelp-help-example-recursive',
894  'action=help&modules=help'
895  => 'apihelp-help-example-help',
896  'action=help&modules=query+info|query+categorymembers'
897  => 'apihelp-help-example-query',
898  ];
899  }
900 
901  public function getHelpUrls() {
902  return [
903  'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Main_page',
904  'https://www.mediawiki.org/wiki/Special:MyLanguage/API:FAQ',
905  'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Quick_start_guide',
906  ];
907  }
908 }
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:155
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:94
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:1972
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
getResult()
Get the result object.
Definition: ApiBase.php:640
static generateTOC( $tree, Language $lang=null)
Generate a table of contents from a section tree.
Definition: Linker.php:1711
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:1972
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:55
getMain()
Get the main module.
Definition: ApiBase.php:536
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When set, the result could take longer to generate, but should be more thoro...
Definition: ApiBase.php:272
Exception used to abort API execution with an error.
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing &#39;/&#39;...
Definition: Html.php:251
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:97
An IContextSource implementation which will inherit context from another source but allow individual ...
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:118
Formatter that spits out anything you like with any desired MIME type.
const PARAM_HELP_MSG_INFO
(array) Specify additional information tags for the parameter.
Definition: ApiBase.php:148
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:761
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 MediaWikiServices
Definition: injection.txt:23
static listExplicitlyDefinedTags()
Lists tags explicitly defined in the change_tag_def table of the database.
const PARAM_ALL
(boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true...
Definition: ApiBase.php:187
getHelpUrls()
Definition: ApiHelp.php:901
IContextSource $context
static fixHelpLinks( $html, $helptitle=null, $localModules=[])
Replace Special:ApiHelp links with links to api.php.
Definition: ApiHelp.php:172
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
Definition: ApiBase.php:215
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=(\*-\*)") 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. '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 '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 since 1.28! 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:1970
static makeMessage( $msg, IContextSource $context, array $params=null)
Create a Message from a string or array.
Definition: ApiBase.php:1795
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3039
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:767
wfAppendQuery( $url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
getConfig()
Get the site configuration.
$modules
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
Definition: ApiBase.php:222
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2205
getExamplesMessages()
Definition: ApiHelp.php:886
static getVersion( $flags='', $lang=null)
Return a string of the MediaWiki version with Git revision if available.
getModulePath()
Get the path to this module.
Definition: ApiBase.php:584
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:265
isReadMode()
Definition: ApiHelp.php:858
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is &#39;submodule&#39;, map parameter values to submodule paths.
Definition: ApiBase.php:172
getContext()
Get the base IContextSource object.
$cache
Definition: mcc.php:33
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
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:1972
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:315
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don&#39;t use this unless yo...
Definition: ApiResult.php:58
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:520
static getHelp(IContextSource $context, $modules, array $options)
Generate help for the specified modules.
Definition: ApiHelp.php:95
static getExtLicenseFileName( $extDir)
Obtains the full path of an extensions copying or license file if one exists.
$help
Definition: mcc.php:32
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE &#39;limit&#39;.
Definition: ApiBase.php:103
getModuleFromPath( $path)
Get a module from its module path.
Definition: ApiBase.php:602
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:83
namespace and then decline to actually register it & $namespaces
Definition: hooks.txt:912
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
Definition: distributors.txt:9
parse()
Fully parse the text from wikitext to HTML.
Definition: Message.php:943
getAllowedParams()
Definition: ApiHelp.php:873
static setSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as subelements rather than attributes...
Definition: ApiResult.php:565
const LIMIT_SML1
Slow query, standard limit.
Definition: ApiBase.php:263
const PARAM_TEMPLATE_VARS
(array) Indicate that this is a templated parameter, and specify replacements.
Definition: ApiBase.php:252
msg( $key)
This is the method for getting translated interface messages.
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:35
shouldCheckMaxlag()
Definition: ApiHelp.php:854
getCustomPrinter()
Definition: ApiHelp.php:862
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
Definition: ApiBase.php:209
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:58
execute()
Definition: ApiHelp.php:33
const ALL_DEFAULT_STRING
Definition: ApiBase.php:256
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:42
const PARAM_EXTRA_NAMESPACES
(int[]) When PARAM_TYPE is &#39;namespace&#39;, include these as additional possible values.
Definition: ApiBase.php:193
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:112
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE &#39;integer&#39; and &#39;limit&#39;.
Definition: ApiBase.php:106
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:211
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
Definition: hooks.txt:2205
static getHelpInternal(IContextSource $context, array $modules, array $options, &$haveModules)
Recursively-called function to actually construct the help.
Definition: ApiHelp.php:226
static listParam(array $list, $type='text')
Definition: Message.php:1128
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:322