MediaWiki  1.28.3
ApiHelp.php
Go to the documentation of this file.
1 <?php
28 
35 class ApiHelp extends ApiBase {
36  public function execute() {
37  $params = $this->extractRequestParams();
38  $modules = [];
39 
40  foreach ( $params['modules'] as $path ) {
41  $modules[] = $this->getModuleFromPath( $path );
42  }
43 
44  // Get the help
45  $context = new DerivativeContext( $this->getMain()->getContext() );
46  $context->setSkin( SkinFactory::getDefaultInstance()->makeSkin( 'apioutput' ) );
47  $context->setLanguage( $this->getMain()->getLanguage() );
48  $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
49  $out = new OutputPage( $context );
50  $out->setCopyrightUrl( 'https://www.mediawiki.org/wiki/Special:MyLanguage/Copyright' );
51  $context->setOutput( $out );
52 
53  self::getHelp( $context, $modules, $params );
54 
55  // Grab the output from the skin
56  ob_start();
57  $context->getOutput()->output();
58  $html = ob_get_clean();
59 
60  $result = $this->getResult();
61  if ( $params['wrap'] ) {
62  $data = [
63  'mime' => 'text/html',
64  'filename' => 'api-help.html',
65  'help' => $html,
66  ];
67  ApiResult::setSubelementsList( $data, 'help' );
68  $result->addValue( null, $this->getModuleName(), $data );
69  } else {
70  $result->reset();
71  $result->addValue( null, 'text', $html, ApiResult::NO_SIZE_CHECK );
72  $result->addValue( null, 'mime', 'text/html', ApiResult::NO_SIZE_CHECK );
73  $result->addValue( null, 'filename', 'api-help.html', ApiResult::NO_SIZE_CHECK );
74  }
75  }
76 
97  public static function getHelp( IContextSource $context, $modules, array $options ) {
99 
100  if ( !is_array( $modules ) ) {
101  $modules = [ $modules ];
102  }
103 
104  $out = $context->getOutput();
105  $out->addModuleStyles( [
106  'mediawiki.hlist',
107  'mediawiki.apihelp',
108  ] );
109  if ( !empty( $options['toc'] ) ) {
110  $out->addModules( 'mediawiki.toc' );
111  }
112  $out->setPageTitle( $context->msg( 'api-help-title' ) );
113 
115  $cacheKey = null;
116  if ( count( $modules ) == 1 && $modules[0] instanceof ApiMain &&
117  $options['recursivesubmodules'] && $context->getLanguage() === $wgContLang
118  ) {
119  $cacheHelpTimeout = $context->getConfig()->get( 'APICacheHelpTimeout' );
120  if ( $cacheHelpTimeout > 0 ) {
121  // Get help text from cache if present
122  $cacheKey = wfMemcKey( 'apihelp', $modules[0]->getModulePath(),
123  (int)!empty( $options['toc'] ),
124  str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
125  $cached = $cache->get( $cacheKey );
126  if ( $cached ) {
127  $out->addHTML( $cached );
128  return;
129  }
130  }
131  }
132  if ( $out->getHTML() !== '' ) {
133  // Don't save to cache, there's someone else's content in the page
134  // already
135  $cacheKey = null;
136  }
137 
138  $options['recursivesubmodules'] = !empty( $options['recursivesubmodules'] );
139  $options['submodules'] = $options['recursivesubmodules'] || !empty( $options['submodules'] );
140 
141  // Prepend lead
142  if ( empty( $options['nolead'] ) ) {
143  $msg = $context->msg( 'api-help-lead' );
144  if ( !$msg->isDisabled() ) {
145  $out->addHTML( $msg->parseAsBlock() );
146  }
147  }
148 
149  $haveModules = [];
150  $html = self::getHelpInternal( $context, $modules, $options, $haveModules );
151  if ( !empty( $options['toc'] ) && $haveModules ) {
152  $out->addHTML( Linker::generateTOC( $haveModules, $context->getLanguage() ) );
153  }
154  $out->addHTML( $html );
155 
156  $helptitle = isset( $options['helptitle'] ) ? $options['helptitle'] : null;
157  $html = self::fixHelpLinks( $out->getHTML(), $helptitle, $haveModules );
158  $out->clearHTML();
159  $out->addHTML( $html );
160 
161  if ( $cacheKey !== null ) {
162  $cache->set( $cacheKey, $out->getHTML(), $cacheHelpTimeout );
163  }
164  }
165 
174  public static function fixHelpLinks( $html, $helptitle = null, $localModules = [] ) {
175  $formatter = new HtmlFormatter( $html );
176  $doc = $formatter->getDoc();
177  $xpath = new DOMXPath( $doc );
178  $nodes = $xpath->query( '//a[@href][not(contains(@class,\'apihelp-linktrail\'))]' );
179  foreach ( $nodes as $node ) {
180  $href = $node->getAttribute( 'href' );
181  do {
182  $old = $href;
183  $href = rawurldecode( $href );
184  } while ( $old !== $href );
185  if ( preg_match( '!Special:ApiHelp/([^&/|#]+)((?:#.*)?)!', $href, $m ) ) {
186  if ( isset( $localModules[$m[1]] ) ) {
187  $href = $m[2] === '' ? '#' . $m[1] : $m[2];
188  } elseif ( $helptitle !== null ) {
189  $href = Title::newFromText( str_replace( '$1', $m[1], $helptitle ) . $m[2] )
190  ->getFullURL();
191  } else {
192  $href = wfAppendQuery( wfScript( 'api' ), [
193  'action' => 'help',
194  'modules' => $m[1],
195  ] ) . $m[2];
196  }
197  $node->setAttribute( 'href', $href );
198  $node->removeAttribute( 'title' );
199  }
200  }
201 
202  return $formatter->getText();
203  }
204 
213  private static function wrap( Message $msg, $class, $tag = 'span' ) {
214  return Html::rawElement( $tag, [ 'class' => $class ],
215  $msg->parse()
216  );
217  }
218 
229  array $options, &$haveModules
230  ) {
231  $out = '';
232 
233  $level = empty( $options['headerlevel'] ) ? 2 : $options['headerlevel'];
234  if ( empty( $options['tocnumber'] ) ) {
235  $tocnumber = [ 2 => 0 ];
236  } else {
237  $tocnumber = &$options['tocnumber'];
238  }
239 
240  foreach ( $modules as $module ) {
241  $tocnumber[$level]++;
242  $path = $module->getModulePath();
243  $module->setContext( $context );
244  $help = [
245  'header' => '',
246  'flags' => '',
247  'description' => '',
248  'help-urls' => '',
249  'parameters' => '',
250  'examples' => '',
251  'submodules' => '',
252  ];
253 
254  if ( empty( $options['noheader'] ) || !empty( $options['toc'] ) ) {
255  $anchor = $path;
256  $i = 1;
257  while ( isset( $haveModules[$anchor] ) ) {
258  $anchor = $path . '|' . ++$i;
259  }
260 
261  if ( $module->isMain() ) {
262  $headerContent = $context->msg( 'api-help-main-header' )->parse();
263  $headerAttr = [
264  'class' => 'apihelp-header',
265  ];
266  } else {
267  $name = $module->getModuleName();
268  $headerContent = $module->getParent()->getModuleManager()->getModuleGroup( $name ) .
269  "=$name";
270  if ( $module->getModulePrefix() !== '' ) {
271  $headerContent .= ' ' .
272  $context->msg( 'parentheses', $module->getModulePrefix() )->parse();
273  }
274  // Module names are always in English and not localized,
275  // so English language and direction must be set explicitly,
276  // otherwise parentheses will get broken in RTL wikis
277  $headerAttr = [
278  'class' => 'apihelp-header apihelp-module-name',
279  'dir' => 'ltr',
280  'lang' => 'en',
281  ];
282  }
283 
284  $headerAttr['id'] = $anchor;
285 
286  $haveModules[$anchor] = [
287  'toclevel' => count( $tocnumber ),
288  'level' => $level,
289  'anchor' => $anchor,
290  'line' => $headerContent,
291  'number' => implode( '.', $tocnumber ),
292  'index' => false,
293  ];
294  if ( empty( $options['noheader'] ) ) {
295  $help['header'] .= Html::element(
296  'h' . min( 6, $level ),
297  $headerAttr,
298  $headerContent
299  );
300  }
301  } else {
302  $haveModules[$path] = true;
303  }
304 
305  $links = [];
306  $any = false;
307  for ( $m = $module; $m !== null; $m = $m->getParent() ) {
308  $name = $m->getModuleName();
309  if ( $name === 'main_int' ) {
310  $name = 'main';
311  }
312 
313  if ( count( $modules ) === 1 && $m === $modules[0] &&
314  !( !empty( $options['submodules'] ) && $m->getModuleManager() )
315  ) {
316  $link = Html::element( 'b', [ 'dir' => 'ltr', 'lang' => 'en' ], $name );
317  } else {
318  $link = SpecialPage::getTitleFor( 'ApiHelp', $m->getModulePath() )->getLocalURL();
319  $link = Html::element( 'a',
320  [ 'href' => $link, 'class' => 'apihelp-linktrail', 'dir' => 'ltr', 'lang' => 'en' ],
321  $name
322  );
323  $any = true;
324  }
325  array_unshift( $links, $link );
326  }
327  if ( $any ) {
328  $help['header'] .= self::wrap(
329  $context->msg( 'parentheses' )
330  ->rawParams( $context->getLanguage()->pipeList( $links ) ),
331  'apihelp-linktrail', 'div'
332  );
333  }
334 
335  $flags = $module->getHelpFlags();
336  $help['flags'] .= Html::openElement( 'div',
337  [ 'class' => 'apihelp-block apihelp-flags' ] );
338  $msg = $context->msg( 'api-help-flags' );
339  if ( !$msg->isDisabled() ) {
340  $help['flags'] .= self::wrap(
341  $msg->numParams( count( $flags ) ), 'apihelp-block-head', 'div'
342  );
343  }
344  $help['flags'] .= Html::openElement( 'ul' );
345  foreach ( $flags as $flag ) {
346  $help['flags'] .= Html::rawElement( 'li', null,
347  self::wrap( $context->msg( "api-help-flag-$flag" ), "apihelp-flag-$flag" )
348  );
349  }
350  $sourceInfo = $module->getModuleSourceInfo();
351  if ( $sourceInfo ) {
352  if ( isset( $sourceInfo['namemsg'] ) ) {
353  $extname = $context->msg( $sourceInfo['namemsg'] )->text();
354  } else {
355  // Probably English, so wrap it.
356  $extname = Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $sourceInfo['name'] );
357  }
358  $help['flags'] .= Html::rawElement( 'li', null,
359  self::wrap(
360  $context->msg( 'api-help-source', $extname, $sourceInfo['name'] ),
361  'apihelp-source'
362  )
363  );
364 
365  $link = SpecialPage::getTitleFor( 'Version', 'License/' . $sourceInfo['name'] );
366  if ( isset( $sourceInfo['license-name'] ) ) {
367  $msg = $context->msg( 'api-help-license', $link,
368  Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $sourceInfo['license-name'] )
369  );
370  } elseif ( SpecialVersion::getExtLicenseFileName( dirname( $sourceInfo['path'] ) ) ) {
371  $msg = $context->msg( 'api-help-license-noname', $link );
372  } else {
373  $msg = $context->msg( 'api-help-license-unknown' );
374  }
375  $help['flags'] .= Html::rawElement( 'li', null,
376  self::wrap( $msg, 'apihelp-license' )
377  );
378  } else {
379  $help['flags'] .= Html::rawElement( 'li', null,
380  self::wrap( $context->msg( 'api-help-source-unknown' ), 'apihelp-source' )
381  );
382  $help['flags'] .= Html::rawElement( 'li', null,
383  self::wrap( $context->msg( 'api-help-license-unknown' ), 'apihelp-license' )
384  );
385  }
386  $help['flags'] .= Html::closeElement( 'ul' );
387  $help['flags'] .= Html::closeElement( 'div' );
388 
389  foreach ( $module->getFinalDescription() as $msg ) {
390  $msg->setContext( $context );
391  $help['description'] .= $msg->parseAsBlock();
392  }
393 
394  $urls = $module->getHelpUrls();
395  if ( $urls ) {
396  $help['help-urls'] .= Html::openElement( 'div',
397  [ 'class' => 'apihelp-block apihelp-help-urls' ]
398  );
399  $msg = $context->msg( 'api-help-help-urls' );
400  if ( !$msg->isDisabled() ) {
401  $help['help-urls'] .= self::wrap(
402  $msg->numParams( count( $urls ) ), 'apihelp-block-head', 'div'
403  );
404  }
405  if ( !is_array( $urls ) ) {
406  $urls = [ $urls ];
407  }
408  $help['help-urls'] .= Html::openElement( 'ul' );
409  foreach ( $urls as $url ) {
410  $help['help-urls'] .= Html::rawElement( 'li', null,
411  Html::element( 'a', [ 'href' => $url, 'dir' => 'ltr' ], $url )
412  );
413  }
414  $help['help-urls'] .= Html::closeElement( 'ul' );
415  $help['help-urls'] .= Html::closeElement( 'div' );
416  }
417 
418  $params = $module->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
419  $dynamicParams = $module->dynamicParameterDocumentation();
420  $groups = [];
421  if ( $params || $dynamicParams !== null ) {
422  $help['parameters'] .= Html::openElement( 'div',
423  [ 'class' => 'apihelp-block apihelp-parameters' ]
424  );
425  $msg = $context->msg( 'api-help-parameters' );
426  if ( !$msg->isDisabled() ) {
427  $help['parameters'] .= self::wrap(
428  $msg->numParams( count( $params ) ), 'apihelp-block-head', 'div'
429  );
430  }
431  $help['parameters'] .= Html::openElement( 'dl' );
432 
433  $descriptions = $module->getFinalParamDescription();
434 
435  foreach ( $params as $name => $settings ) {
436  if ( !is_array( $settings ) ) {
437  $settings = [ ApiBase::PARAM_DFLT => $settings ];
438  }
439 
440  $help['parameters'] .= Html::rawElement( 'dt', null,
441  Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $module->encodeParamName( $name ) )
442  );
443 
444  // Add description
445  $description = [];
446  if ( isset( $descriptions[$name] ) ) {
447  foreach ( $descriptions[$name] as $msg ) {
448  $msg->setContext( $context );
449  $description[] = $msg->parseAsBlock();
450  }
451  }
452 
453  // Add usage info
454  $info = [];
455 
456  // Required?
457  if ( !empty( $settings[ApiBase::PARAM_REQUIRED] ) ) {
458  $info[] = $context->msg( 'api-help-param-required' )->parse();
459  }
460 
461  // Custom info?
462  if ( !empty( $settings[ApiBase::PARAM_HELP_MSG_INFO] ) ) {
463  foreach ( $settings[ApiBase::PARAM_HELP_MSG_INFO] as $i ) {
464  $tag = array_shift( $i );
465  $info[] = $context->msg( "apihelp-{$path}-paraminfo-{$tag}" )
466  ->numParams( count( $i ) )
467  ->params( $context->getLanguage()->commaList( $i ) )
468  ->params( $module->getModulePrefix() )
469  ->parse();
470  }
471  }
472 
473  // Type documentation
474  if ( !isset( $settings[ApiBase::PARAM_TYPE] ) ) {
475  $dflt = isset( $settings[ApiBase::PARAM_DFLT] )
476  ? $settings[ApiBase::PARAM_DFLT]
477  : null;
478  if ( is_bool( $dflt ) ) {
479  $settings[ApiBase::PARAM_TYPE] = 'boolean';
480  } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
481  $settings[ApiBase::PARAM_TYPE] = 'string';
482  } elseif ( is_int( $dflt ) ) {
483  $settings[ApiBase::PARAM_TYPE] = 'integer';
484  }
485  }
486  if ( isset( $settings[ApiBase::PARAM_TYPE] ) ) {
487  $type = $settings[ApiBase::PARAM_TYPE];
488  $multi = !empty( $settings[ApiBase::PARAM_ISMULTI] );
489  $hintPipeSeparated = true;
491 
492  if ( is_array( $type ) ) {
493  $count = count( $type );
494  $links = isset( $settings[ApiBase::PARAM_VALUE_LINKS] )
495  ? $settings[ApiBase::PARAM_VALUE_LINKS]
496  : [];
497  $values = array_map( function ( $v ) use ( $links ) {
498  // We can't know whether this contains LTR or RTL text.
499  $ret = $v === '' ? $v : Html::element( 'span', [ 'dir' => 'auto' ], $v );
500  if ( isset( $links[$v] ) ) {
501  $ret = "[[{$links[$v]}|$ret]]";
502  }
503  return $ret;
504  }, $type );
505  $i = array_search( '', $type, true );
506  if ( $i === false ) {
507  $values = $context->getLanguage()->commaList( $values );
508  } else {
509  unset( $values[$i] );
510  $values = $context->msg( 'api-help-param-list-can-be-empty' )
511  ->numParams( count( $values ) )
512  ->params( $context->getLanguage()->commaList( $values ) )
513  ->parse();
514  }
515  $info[] = $context->msg( 'api-help-param-list' )
516  ->params( $multi ? 2 : 1 )
517  ->params( $values )
518  ->parse();
519  $hintPipeSeparated = false;
520  } else {
521  switch ( $type ) {
522  case 'submodule':
523  $groups[] = $name;
524  if ( isset( $settings[ApiBase::PARAM_SUBMODULE_MAP] ) ) {
525  $map = $settings[ApiBase::PARAM_SUBMODULE_MAP];
526  ksort( $map );
527  $submodules = [];
528  foreach ( $map as $v => $m ) {
529  $submodules[] = "[[Special:ApiHelp/{$m}|{$v}]]";
530  }
531  } else {
532  $submodules = $module->getModuleManager()->getNames( $name );
533  sort( $submodules );
534  $prefix = $module->isMain()
535  ? '' : ( $module->getModulePath() . '+' );
536  $submodules = array_map( function ( $name ) use ( $prefix ) {
537  $text = Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $name );
538  return "[[Special:ApiHelp/{$prefix}{$name}|{$text}]]";
539  }, $submodules );
540  }
541  $count = count( $submodules );
542  $info[] = $context->msg( 'api-help-param-list' )
543  ->params( $multi ? 2 : 1 )
544  ->params( $context->getLanguage()->commaList( $submodules ) )
545  ->parse();
546  $hintPipeSeparated = false;
547  // No type message necessary, we have a list of values.
548  $type = null;
549  break;
550 
551  case 'namespace':
553  $count = count( $namespaces );
554  $info[] = $context->msg( 'api-help-param-list' )
555  ->params( $multi ? 2 : 1 )
556  ->params( $context->getLanguage()->commaList( $namespaces ) )
557  ->parse();
558  $hintPipeSeparated = false;
559  // No type message necessary, we have a list of values.
560  $type = null;
561  break;
562 
563  case 'tags':
565  $count = count( $tags );
566  $info[] = $context->msg( 'api-help-param-list' )
567  ->params( $multi ? 2 : 1 )
568  ->params( $context->getLanguage()->commaList( $tags ) )
569  ->parse();
570  $hintPipeSeparated = false;
571  $type = null;
572  break;
573 
574  case 'limit':
575  if ( isset( $settings[ApiBase::PARAM_MAX2] ) ) {
576  $info[] = $context->msg( 'api-help-param-limit2' )
577  ->numParams( $settings[ApiBase::PARAM_MAX] )
578  ->numParams( $settings[ApiBase::PARAM_MAX2] )
579  ->parse();
580  } else {
581  $info[] = $context->msg( 'api-help-param-limit' )
582  ->numParams( $settings[ApiBase::PARAM_MAX] )
583  ->parse();
584  }
585  break;
586 
587  case 'integer':
588  // Possible messages:
589  // api-help-param-integer-min,
590  // api-help-param-integer-max,
591  // api-help-param-integer-minmax
592  $suffix = '';
593  $min = $max = 0;
594  if ( isset( $settings[ApiBase::PARAM_MIN] ) ) {
595  $suffix .= 'min';
596  $min = $settings[ApiBase::PARAM_MIN];
597  }
598  if ( isset( $settings[ApiBase::PARAM_MAX] ) ) {
599  $suffix .= 'max';
600  $max = $settings[ApiBase::PARAM_MAX];
601  }
602  if ( $suffix !== '' ) {
603  $info[] =
604  $context->msg( "api-help-param-integer-$suffix" )
605  ->params( $multi ? 2 : 1 )
606  ->numParams( $min, $max )
607  ->parse();
608  }
609  break;
610 
611  case 'upload':
612  $info[] = $context->msg( 'api-help-param-upload' )
613  ->parse();
614  // No type message necessary, api-help-param-upload should handle it.
615  $type = null;
616  break;
617 
618  case 'string':
619  case 'text':
620  // Displaying a type message here would be useless.
621  $type = null;
622  break;
623  }
624  }
625 
626  // Add type. Messages for grep: api-help-param-type-limit
627  // api-help-param-type-integer api-help-param-type-boolean
628  // api-help-param-type-timestamp api-help-param-type-user
629  // api-help-param-type-password
630  if ( is_string( $type ) ) {
631  $msg = $context->msg( "api-help-param-type-$type" );
632  if ( !$msg->isDisabled() ) {
633  $info[] = $msg->params( $multi ? 2 : 1 )->parse();
634  }
635  }
636 
637  if ( $multi ) {
638  $extra = [];
639  if ( $hintPipeSeparated ) {
640  $extra[] = $context->msg( 'api-help-param-multi-separate' )->parse();
641  }
642  if ( $count > ApiBase::LIMIT_SML1 ) {
643  $extra[] = $context->msg( 'api-help-param-multi-max' )
645  ->parse();
646  }
647  if ( $extra ) {
648  $info[] = implode( ' ', $extra );
649  }
650  }
651  }
652 
653  // Add default
654  $default = isset( $settings[ApiBase::PARAM_DFLT] )
655  ? $settings[ApiBase::PARAM_DFLT]
656  : null;
657  if ( $default === '' ) {
658  $info[] = $context->msg( 'api-help-param-default-empty' )
659  ->parse();
660  } elseif ( $default !== null && $default !== false ) {
661  // We can't know whether this contains LTR or RTL text.
662  $info[] = $context->msg( 'api-help-param-default' )
663  ->params( Html::element( 'span', [ 'dir' => 'auto' ], $default ) )
664  ->parse();
665  }
666 
667  if ( !array_filter( $description ) ) {
668  $description = [ self::wrap(
669  $context->msg( 'api-help-param-no-description' ),
670  'apihelp-empty'
671  ) ];
672  }
673 
674  // Add "deprecated" flag
675  if ( !empty( $settings[ApiBase::PARAM_DEPRECATED] ) ) {
676  $help['parameters'] .= Html::openElement( 'dd',
677  [ 'class' => 'info' ] );
678  $help['parameters'] .= self::wrap(
679  $context->msg( 'api-help-param-deprecated' ),
680  'apihelp-deprecated', 'strong'
681  );
682  $help['parameters'] .= Html::closeElement( 'dd' );
683  }
684 
685  if ( $description ) {
686  $description = implode( '', $description );
687  $description = preg_replace( '!\s*</([oud]l)>\s*<\1>\s*!', "\n", $description );
688  $help['parameters'] .= Html::rawElement( 'dd',
689  [ 'class' => 'description' ], $description );
690  }
691 
692  foreach ( $info as $i ) {
693  $help['parameters'] .= Html::rawElement( 'dd', [ 'class' => 'info' ], $i );
694  }
695  }
696 
697  if ( $dynamicParams !== null ) {
698  $dynamicParams = ApiBase::makeMessage( $dynamicParams, $context, [
699  $module->getModulePrefix(),
700  $module->getModuleName(),
701  $module->getModulePath()
702  ] );
703  $help['parameters'] .= Html::element( 'dt', null, '*' );
704  $help['parameters'] .= Html::rawElement( 'dd',
705  [ 'class' => 'description' ], $dynamicParams->parse() );
706  }
707 
708  $help['parameters'] .= Html::closeElement( 'dl' );
709  $help['parameters'] .= Html::closeElement( 'div' );
710  }
711 
712  $examples = $module->getExamplesMessages();
713  if ( $examples ) {
714  $help['examples'] .= Html::openElement( 'div',
715  [ 'class' => 'apihelp-block apihelp-examples' ] );
716  $msg = $context->msg( 'api-help-examples' );
717  if ( !$msg->isDisabled() ) {
718  $help['examples'] .= self::wrap(
719  $msg->numParams( count( $examples ) ), 'apihelp-block-head', 'div'
720  );
721  }
722 
723  $help['examples'] .= Html::openElement( 'dl' );
724  foreach ( $examples as $qs => $msg ) {
725  $msg = ApiBase::makeMessage( $msg, $context, [
726  $module->getModulePrefix(),
727  $module->getModuleName(),
728  $module->getModulePath()
729  ] );
730 
731  $link = wfAppendQuery( wfScript( 'api' ), $qs );
732  $sandbox = SpecialPage::getTitleFor( 'ApiSandbox' )->getLocalURL() . '#' . $qs;
733  $help['examples'] .= Html::rawElement( 'dt', null, $msg->parse() );
734  $help['examples'] .= Html::rawElement( 'dd', null,
735  Html::element( 'a', [ 'href' => $link, 'dir' => 'ltr' ], "api.php?$qs" ) . ' ' .
736  Html::rawElement( 'a', [ 'href' => $sandbox ],
737  $context->msg( 'api-help-open-in-apisandbox' )->parse() )
738  );
739  }
740  $help['examples'] .= Html::closeElement( 'dl' );
741  $help['examples'] .= Html::closeElement( 'div' );
742  }
743 
744  $subtocnumber = $tocnumber;
745  $subtocnumber[$level + 1] = 0;
746  $suboptions = [
747  'submodules' => $options['recursivesubmodules'],
748  'headerlevel' => $level + 1,
749  'tocnumber' => &$subtocnumber,
750  'noheader' => false,
751  ] + $options;
752 
753  if ( $options['submodules'] && $module->getModuleManager() ) {
754  $manager = $module->getModuleManager();
755  $submodules = [];
756  foreach ( $groups as $group ) {
757  $names = $manager->getNames( $group );
758  sort( $names );
759  foreach ( $names as $name ) {
760  $submodules[] = $manager->getModule( $name );
761  }
762  }
763  $help['submodules'] .= self::getHelpInternal(
764  $context,
765  $submodules,
766  $suboptions,
767  $haveModules
768  );
769  }
770 
771  $module->modifyHelp( $help, $suboptions, $haveModules );
772 
773  Hooks::run( 'APIHelpModifyOutput', [ $module, &$help, $suboptions, &$haveModules ] );
774 
775  $out .= implode( "\n", $help );
776  }
777 
778  return $out;
779  }
780 
781  public function shouldCheckMaxlag() {
782  return false;
783  }
784 
785  public function isReadMode() {
786  return false;
787  }
788 
789  public function getCustomPrinter() {
790  $params = $this->extractRequestParams();
791  if ( $params['wrap'] ) {
792  return null;
793  }
794 
795  $main = $this->getMain();
796  $errorPrinter = $main->createPrinterByName( $main->getParameter( 'format' ) );
797  return new ApiFormatRaw( $main, $errorPrinter );
798  }
799 
800  public function getAllowedParams() {
801  return [
802  'modules' => [
803  ApiBase::PARAM_DFLT => 'main',
804  ApiBase::PARAM_ISMULTI => true,
805  ],
806  'submodules' => false,
807  'recursivesubmodules' => false,
808  'wrap' => false,
809  'toc' => false,
810  ];
811  }
812 
813  protected function getExamplesMessages() {
814  return [
815  'action=help'
816  => 'apihelp-help-example-main',
817  'action=help&modules=query&submodules=1'
818  => 'apihelp-help-example-submodules',
819  'action=help&recursivesubmodules=1'
820  => 'apihelp-help-example-recursive',
821  'action=help&modules=help'
822  => 'apihelp-help-example-help',
823  'action=help&modules=query+info|query+categorymembers'
824  => 'apihelp-help-example-query',
825  ];
826  }
827 
828  public function getHelpUrls() {
829  return [
830  'https://www.mediawiki.org/wiki/API:Main_page',
831  'https://www.mediawiki.org/wiki/API:FAQ',
832  'https://www.mediawiki.org/wiki/API:Quick_start_guide',
833  ];
834  }
835 }
static generateTOC($tree, $lang=false)
Generate a table of contents from a section tree.
Definition: Linker.php:1663
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:149
static closeElement($element)
Returns "".
Definition: Html.php:305
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
static getMainWANInstance()
Get the main WAN cache object.
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:1940
Interface for objects which can provide a MediaWiki context on request.
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:806
the array() calling protocol came about after MediaWiki 1.4rc1.
getResult()
Get the result object.
Definition: ApiBase.php:584
getLanguage()
Get the Language object.
wfScript($script= 'index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
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:1940
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getTitleFor($name, $subpage=false, $fragment= '')
Get a localised Title object for a specified special page name If you don't need a full Title object...
Definition: SpecialPage.php:82
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
getMain()
Get the main module.
Definition: ApiBase.php:480
msg()
Get a Message object with context set.
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When set, the result could take longer to generate, but should be more thoro...
Definition: ApiBase.php:197
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 'integer' and 'limit'.
Definition: ApiBase.php:91
An IContextSource implementation which will inherit context from another source but allow individual ...
const PARAM_REQUIRED
(boolean) Is the parameter required?
Definition: ApiBase.php:112
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:142
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
static makeMessage($msg, IContextSource $context, array $params=null)
Create a Message from a string or array.
Definition: ApiBase.php:1522
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2707
static fixHelpLinks($html, $helptitle=null, $localModules=[])
Replace Special:ApiHelp links with links to api.php.
Definition: ApiHelp.php:174
static listExplicitlyDefinedTags()
Lists tags explicitly defined in the valid_tag table of the database.
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:262
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
getHelpUrls()
Definition: ApiHelp.php:828
IContextSource $context
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. '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 '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:Associative array mapping language codes to prefixed links of the form"language:title".&$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:1938
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:2893
getConfig()
Get the site configuration.
static openElement($element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:247
$modules
wfAppendQuery($url, $query)
Append a query string to an existing URL, which may or may not already have query string parameters a...
getExamplesMessages()
Definition: ApiHelp.php:813
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1050
getModulePath()
Get the path to this module.
Definition: ApiBase.php:528
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:190
isReadMode()
Definition: ApiHelp.php:785
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is 'submodule', map parameter values to submodule paths.
Definition: ApiBase.php:165
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:43
static getExtLicenseFileName($extDir)
Obtains the full path of an extensions copying or license file if one exists.
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
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:464
static getHelp(IContextSource $context, $modules, array $options)
Generate help for the specified modules.
Definition: ApiHelp.php:97
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:1011
$help
Definition: mcc.php:32
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right, for PARAM_TYPE 'limit'.
Definition: ApiBase.php:97
getLanguage()
Get the Language object.
namespace and then decline to actually register it & $namespaces
Definition: hooks.txt:957
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
This class should be covered by a general architecture document which does not exist as of January 20...
Definition: OutputPage.php:43
parse()
Fully parse the text from wikitext to HTML.
Definition: Message.php:888
static wrap(Message $msg, $class, $tag= 'span')
Wrap a message in HTML with a class.
Definition: ApiHelp.php:213
getAllowedParams()
Definition: ApiHelp.php:800
static setSubelementsList(array &$arr, $names)
Causes the elements with the specified names to be output as subelements rather than attributes...
Definition: ApiResult.php:567
const LIMIT_SML1
Slow query, standard limit.
Definition: ApiBase.php:188
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:781
getCustomPrinter()
Definition: ApiHelp.php:789
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
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:56
execute()
Definition: ApiHelp.php:36
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
$count
wfMemcKey()
Make a cache key for the local wiki.
getOutput()
Get the OutputPage object.
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
Definition: ApiBase.php:100
Class to output help for an API module.
Definition: ApiHelp.php:35
static getVersion($flags= '', $lang=null)
Return a string of the MediaWiki version with Git revision if available.
static getValidNamespaces()
Returns an array of the namespaces (by integer id) that exist on the wiki.
static getDefaultInstance()
Definition: SkinFactory.php:50
static element($element, $attribs=[], $contents= '')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:229
static getHelpInternal(IContextSource $context, array $modules, array $options, &$haveModules)
Recursively-called function to actually construct the help.
Definition: ApiHelp.php:228
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2495
getModuleFromPath($path)
Get a module from its module path.
Definition: ApiBase.php:546
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304