ApiHelp.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. <?php
  2. /**
  3. * Copyright © 2014 Wikimedia Foundation and contributors
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use HtmlFormatter\HtmlFormatter;
  23. use MediaWiki\MediaWikiServices;
  24. /**
  25. * Class to output help for an API module
  26. *
  27. * @since 1.25 completely rewritten
  28. * @ingroup API
  29. */
  30. class ApiHelp extends ApiBase {
  31. public function execute() {
  32. $params = $this->extractRequestParams();
  33. $modules = [];
  34. foreach ( $params['modules'] as $path ) {
  35. $modules[] = $this->getModuleFromPath( $path );
  36. }
  37. // Get the help
  38. $context = new DerivativeContext( $this->getMain()->getContext() );
  39. $skinFactory = MediaWikiServices::getInstance()->getSkinFactory();
  40. $context->setSkin( $skinFactory->makeSkin( 'apioutput' ) );
  41. $context->setLanguage( $this->getMain()->getLanguage() );
  42. $context->setTitle( SpecialPage::getTitleFor( 'ApiHelp' ) );
  43. $out = new OutputPage( $context );
  44. $out->setRobotPolicy( 'noindex,nofollow' );
  45. $out->setCopyrightUrl( 'https://www.mediawiki.org/wiki/Special:MyLanguage/Copyright' );
  46. $context->setOutput( $out );
  47. self::getHelp( $context, $modules, $params );
  48. // Grab the output from the skin
  49. ob_start();
  50. $context->getOutput()->output();
  51. $html = ob_get_clean();
  52. $result = $this->getResult();
  53. if ( $params['wrap'] ) {
  54. $data = [
  55. 'mime' => 'text/html',
  56. 'filename' => 'api-help.html',
  57. 'help' => $html,
  58. ];
  59. ApiResult::setSubelementsList( $data, 'help' );
  60. $result->addValue( null, $this->getModuleName(), $data );
  61. } else {
  62. // Show any errors at the top of the HTML
  63. $transform = [
  64. 'Types' => [ 'AssocAsObject' => true ],
  65. 'Strip' => 'all',
  66. ];
  67. $errors = array_filter( [
  68. 'errors' => $this->getResult()->getResultData( [ 'errors' ], $transform ),
  69. 'warnings' => $this->getResult()->getResultData( [ 'warnings' ], $transform ),
  70. ] );
  71. if ( $errors ) {
  72. $json = FormatJson::encode( $errors, true, FormatJson::UTF8_OK );
  73. // Escape any "--", some parsers might interpret that as end-of-comment.
  74. // The above already escaped any "<" and ">".
  75. $json = str_replace( '--', '-\u002D', $json );
  76. $html = "<!-- API warnings and errors:\n$json\n-->\n$html";
  77. }
  78. $result->reset();
  79. $result->addValue( null, 'text', $html, ApiResult::NO_SIZE_CHECK );
  80. $result->addValue( null, 'mime', 'text/html', ApiResult::NO_SIZE_CHECK );
  81. $result->addValue( null, 'filename', 'api-help.html', ApiResult::NO_SIZE_CHECK );
  82. }
  83. }
  84. /**
  85. * Generate help for the specified modules
  86. *
  87. * Help is placed into the OutputPage object returned by
  88. * $context->getOutput().
  89. *
  90. * Recognized options include:
  91. * - headerlevel: (int) Header tag level
  92. * - nolead: (bool) Skip the inclusion of api-help-lead
  93. * - noheader: (bool) Skip the inclusion of the top-level section headers
  94. * - submodules: (bool) Include help for submodules of the current module
  95. * - recursivesubmodules: (bool) Include help for submodules recursively
  96. * - helptitle: (string) Title to link for additional modules' help. Should contain $1.
  97. * - toc: (bool) Include a table of contents
  98. *
  99. * @param IContextSource $context
  100. * @param ApiBase[]|ApiBase $modules
  101. * @param array $options Formatting options (described above)
  102. */
  103. public static function getHelp( IContextSource $context, $modules, array $options ) {
  104. if ( !is_array( $modules ) ) {
  105. $modules = [ $modules ];
  106. }
  107. $out = $context->getOutput();
  108. $out->addModuleStyles( [
  109. 'mediawiki.hlist',
  110. 'mediawiki.apipretty',
  111. ] );
  112. if ( !empty( $options['toc'] ) ) {
  113. $out->addModuleStyles( 'mediawiki.toc.styles' );
  114. }
  115. $out->setPageTitle( $context->msg( 'api-help-title' ) );
  116. $services = MediaWikiServices::getInstance();
  117. $cache = $services->getMainWANObjectCache();
  118. $cacheKey = null;
  119. if ( count( $modules ) == 1 && $modules[0] instanceof ApiMain &&
  120. $options['recursivesubmodules'] &&
  121. $context->getLanguage()->equals( $services->getContentLanguage() )
  122. ) {
  123. $cacheHelpTimeout = $context->getConfig()->get( 'APICacheHelpTimeout' );
  124. if ( $cacheHelpTimeout > 0 ) {
  125. // Get help text from cache if present
  126. $cacheKey = $cache->makeKey( 'apihelp', $modules[0]->getModulePath(),
  127. (int)!empty( $options['toc'] ),
  128. str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
  129. $cached = $cache->get( $cacheKey );
  130. if ( $cached ) {
  131. $out->addHTML( $cached );
  132. return;
  133. }
  134. }
  135. }
  136. if ( $out->getHTML() !== '' ) {
  137. // Don't save to cache, there's someone else's content in the page
  138. // already
  139. $cacheKey = null;
  140. }
  141. $options['recursivesubmodules'] = !empty( $options['recursivesubmodules'] );
  142. $options['submodules'] = $options['recursivesubmodules'] || !empty( $options['submodules'] );
  143. // Prepend lead
  144. if ( empty( $options['nolead'] ) ) {
  145. $msg = $context->msg( 'api-help-lead' );
  146. if ( !$msg->isDisabled() ) {
  147. $out->addHTML( $msg->parseAsBlock() );
  148. }
  149. }
  150. $haveModules = [];
  151. $html = self::getHelpInternal( $context, $modules, $options, $haveModules );
  152. if ( !empty( $options['toc'] ) && $haveModules ) {
  153. $out->addHTML( Linker::generateTOC( $haveModules, $context->getLanguage() ) );
  154. }
  155. $out->addHTML( $html );
  156. $helptitle = $options['helptitle'] ?? null;
  157. $html = self::fixHelpLinks( $out->getHTML(), $helptitle, $haveModules );
  158. $out->clearHTML();
  159. $out->addHTML( $html );
  160. if ( $cacheKey !== null ) {
  161. $cache->set( $cacheKey, $out->getHTML(), $cacheHelpTimeout );
  162. }
  163. }
  164. /**
  165. * Replace Special:ApiHelp links with links to api.php
  166. *
  167. * @param string $html
  168. * @param string|null $helptitle Title to link to rather than api.php, must contain '$1'
  169. * @param array $localModules Keys are modules to link within the current page, values are ignored
  170. * @return string
  171. */
  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. return $formatter->getText();
  200. }
  201. /**
  202. * Wrap a message in HTML with a class.
  203. *
  204. * @param Message $msg
  205. * @param string $class
  206. * @param string $tag
  207. * @return string
  208. */
  209. private static function wrap( Message $msg, $class, $tag = 'span' ) {
  210. return Html::rawElement( $tag, [ 'class' => $class ],
  211. $msg->parse()
  212. );
  213. }
  214. /**
  215. * Recursively-called function to actually construct the help
  216. *
  217. * @param IContextSource $context
  218. * @param ApiBase[] $modules
  219. * @param array $options
  220. * @param array &$haveModules
  221. * @return string
  222. */
  223. private static function getHelpInternal( IContextSource $context, array $modules,
  224. array $options, &$haveModules
  225. ) {
  226. $out = '';
  227. $level = empty( $options['headerlevel'] ) ? 2 : $options['headerlevel'];
  228. if ( empty( $options['tocnumber'] ) ) {
  229. $tocnumber = [ 2 => 0 ];
  230. } else {
  231. $tocnumber = &$options['tocnumber'];
  232. }
  233. foreach ( $modules as $module ) {
  234. $tocnumber[$level]++;
  235. $path = $module->getModulePath();
  236. $module->setContext( $context );
  237. $help = [
  238. 'header' => '',
  239. 'flags' => '',
  240. 'description' => '',
  241. 'help-urls' => '',
  242. 'parameters' => '',
  243. 'examples' => '',
  244. 'submodules' => '',
  245. ];
  246. if ( empty( $options['noheader'] ) || !empty( $options['toc'] ) ) {
  247. $anchor = $path;
  248. $i = 1;
  249. while ( isset( $haveModules[$anchor] ) ) {
  250. $anchor = $path . '|' . ++$i;
  251. }
  252. if ( $module->isMain() ) {
  253. $headerContent = $context->msg( 'api-help-main-header' )->parse();
  254. $headerAttr = [
  255. 'class' => 'apihelp-header',
  256. ];
  257. } else {
  258. $name = $module->getModuleName();
  259. $headerContent = $module->getParent()->getModuleManager()->getModuleGroup( $name ) .
  260. "=$name";
  261. if ( $module->getModulePrefix() !== '' ) {
  262. $headerContent .= ' ' .
  263. $context->msg( 'parentheses', $module->getModulePrefix() )->parse();
  264. }
  265. // Module names are always in English and not localized,
  266. // so English language and direction must be set explicitly,
  267. // otherwise parentheses will get broken in RTL wikis
  268. $headerAttr = [
  269. 'class' => 'apihelp-header apihelp-module-name',
  270. 'dir' => 'ltr',
  271. 'lang' => 'en',
  272. ];
  273. }
  274. $headerAttr['id'] = $anchor;
  275. $haveModules[$anchor] = [
  276. 'toclevel' => count( $tocnumber ),
  277. 'level' => $level,
  278. 'anchor' => $anchor,
  279. 'line' => $headerContent,
  280. 'number' => implode( '.', $tocnumber ),
  281. 'index' => false,
  282. ];
  283. if ( empty( $options['noheader'] ) ) {
  284. $help['header'] .= Html::element(
  285. 'h' . min( 6, $level ),
  286. $headerAttr,
  287. $headerContent
  288. );
  289. }
  290. } else {
  291. $haveModules[$path] = true;
  292. }
  293. $links = [];
  294. $any = false;
  295. for ( $m = $module; $m !== null; $m = $m->getParent() ) {
  296. $name = $m->getModuleName();
  297. if ( $name === 'main_int' ) {
  298. $name = 'main';
  299. }
  300. if ( count( $modules ) === 1 && $m === $modules[0] &&
  301. !( !empty( $options['submodules'] ) && $m->getModuleManager() )
  302. ) {
  303. $link = Html::element( 'b', [ 'dir' => 'ltr', 'lang' => 'en' ], $name );
  304. } else {
  305. $link = SpecialPage::getTitleFor( 'ApiHelp', $m->getModulePath() )->getLocalURL();
  306. $link = Html::element( 'a',
  307. [ 'href' => $link, 'class' => 'apihelp-linktrail', 'dir' => 'ltr', 'lang' => 'en' ],
  308. $name
  309. );
  310. $any = true;
  311. }
  312. array_unshift( $links, $link );
  313. }
  314. if ( $any ) {
  315. $help['header'] .= self::wrap(
  316. $context->msg( 'parentheses' )
  317. ->rawParams( $context->getLanguage()->pipeList( $links ) ),
  318. 'apihelp-linktrail', 'div'
  319. );
  320. }
  321. $flags = $module->getHelpFlags();
  322. $help['flags'] .= Html::openElement( 'div',
  323. [ 'class' => 'apihelp-block apihelp-flags' ] );
  324. $msg = $context->msg( 'api-help-flags' );
  325. if ( !$msg->isDisabled() ) {
  326. $help['flags'] .= self::wrap(
  327. $msg->numParams( count( $flags ) ), 'apihelp-block-head', 'div'
  328. );
  329. }
  330. $help['flags'] .= Html::openElement( 'ul' );
  331. foreach ( $flags as $flag ) {
  332. $help['flags'] .= Html::rawElement( 'li', null,
  333. self::wrap( $context->msg( "api-help-flag-$flag" ), "apihelp-flag-$flag" )
  334. );
  335. }
  336. $sourceInfo = $module->getModuleSourceInfo();
  337. if ( $sourceInfo ) {
  338. if ( isset( $sourceInfo['namemsg'] ) ) {
  339. $extname = $context->msg( $sourceInfo['namemsg'] )->text();
  340. } else {
  341. // Probably English, so wrap it.
  342. $extname = Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $sourceInfo['name'] );
  343. }
  344. $help['flags'] .= Html::rawElement( 'li', null,
  345. self::wrap(
  346. $context->msg( 'api-help-source', $extname, $sourceInfo['name'] ),
  347. 'apihelp-source'
  348. )
  349. );
  350. $link = SpecialPage::getTitleFor( 'Version', 'License/' . $sourceInfo['name'] );
  351. if ( isset( $sourceInfo['license-name'] ) ) {
  352. $msg = $context->msg( 'api-help-license', $link,
  353. Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $sourceInfo['license-name'] )
  354. );
  355. } elseif ( SpecialVersion::getExtLicenseFileName( dirname( $sourceInfo['path'] ) ) ) {
  356. $msg = $context->msg( 'api-help-license-noname', $link );
  357. } else {
  358. $msg = $context->msg( 'api-help-license-unknown' );
  359. }
  360. $help['flags'] .= Html::rawElement( 'li', null,
  361. self::wrap( $msg, 'apihelp-license' )
  362. );
  363. } else {
  364. $help['flags'] .= Html::rawElement( 'li', null,
  365. self::wrap( $context->msg( 'api-help-source-unknown' ), 'apihelp-source' )
  366. );
  367. $help['flags'] .= Html::rawElement( 'li', null,
  368. self::wrap( $context->msg( 'api-help-license-unknown' ), 'apihelp-license' )
  369. );
  370. }
  371. $help['flags'] .= Html::closeElement( 'ul' );
  372. $help['flags'] .= Html::closeElement( 'div' );
  373. foreach ( $module->getFinalDescription() as $msg ) {
  374. $msg->setContext( $context );
  375. $help['description'] .= $msg->parseAsBlock();
  376. }
  377. $urls = $module->getHelpUrls();
  378. if ( $urls ) {
  379. $help['help-urls'] .= Html::openElement( 'div',
  380. [ 'class' => 'apihelp-block apihelp-help-urls' ]
  381. );
  382. $msg = $context->msg( 'api-help-help-urls' );
  383. if ( !$msg->isDisabled() ) {
  384. $help['help-urls'] .= self::wrap(
  385. $msg->numParams( count( $urls ) ), 'apihelp-block-head', 'div'
  386. );
  387. }
  388. if ( !is_array( $urls ) ) {
  389. $urls = [ $urls ];
  390. }
  391. $help['help-urls'] .= Html::openElement( 'ul' );
  392. foreach ( $urls as $url ) {
  393. $help['help-urls'] .= Html::rawElement( 'li', null,
  394. Html::element( 'a', [ 'href' => $url, 'dir' => 'ltr' ], $url )
  395. );
  396. }
  397. $help['help-urls'] .= Html::closeElement( 'ul' );
  398. $help['help-urls'] .= Html::closeElement( 'div' );
  399. }
  400. $params = $module->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
  401. $dynamicParams = $module->dynamicParameterDocumentation();
  402. $groups = [];
  403. if ( $params || $dynamicParams !== null ) {
  404. $help['parameters'] .= Html::openElement( 'div',
  405. [ 'class' => 'apihelp-block apihelp-parameters' ]
  406. );
  407. $msg = $context->msg( 'api-help-parameters' );
  408. if ( !$msg->isDisabled() ) {
  409. $help['parameters'] .= self::wrap(
  410. $msg->numParams( count( $params ) ), 'apihelp-block-head', 'div'
  411. );
  412. }
  413. $help['parameters'] .= Html::openElement( 'dl' );
  414. $descriptions = $module->getFinalParamDescription();
  415. foreach ( $params as $name => $settings ) {
  416. if ( !is_array( $settings ) ) {
  417. $settings = [ ApiBase::PARAM_DFLT => $settings ];
  418. }
  419. $help['parameters'] .= Html::rawElement( 'dt', null,
  420. Html::element( 'span', [ 'dir' => 'ltr', 'lang' => 'en' ], $module->encodeParamName( $name ) )
  421. );
  422. // Add description
  423. $description = [];
  424. if ( isset( $descriptions[$name] ) ) {
  425. foreach ( $descriptions[$name] as $msg ) {
  426. $msg->setContext( $context );
  427. $description[] = $msg->parseAsBlock();
  428. }
  429. }
  430. // Add usage info
  431. $info = [];
  432. // Required?
  433. if ( !empty( $settings[ApiBase::PARAM_REQUIRED] ) ) {
  434. $info[] = $context->msg( 'api-help-param-required' )->parse();
  435. }
  436. // Custom info?
  437. if ( !empty( $settings[ApiBase::PARAM_HELP_MSG_INFO] ) ) {
  438. foreach ( $settings[ApiBase::PARAM_HELP_MSG_INFO] as $i ) {
  439. $tag = array_shift( $i );
  440. $info[] = $context->msg( "apihelp-{$path}-paraminfo-{$tag}" )
  441. ->numParams( count( $i ) )
  442. ->params( $context->getLanguage()->commaList( $i ) )
  443. ->params( $module->getModulePrefix() )
  444. ->parse();
  445. }
  446. }
  447. // Templated?
  448. if ( !empty( $settings[ApiBase::PARAM_TEMPLATE_VARS] ) ) {
  449. $vars = [];
  450. $msg = 'api-help-param-templated-var-first';
  451. foreach ( $settings[ApiBase::PARAM_TEMPLATE_VARS] as $k => $v ) {
  452. $vars[] = $context->msg( $msg, $k, $module->encodeParamName( $v ) );
  453. $msg = 'api-help-param-templated-var';
  454. }
  455. $info[] = $context->msg( 'api-help-param-templated' )
  456. ->numParams( count( $vars ) )
  457. ->params( Message::listParam( $vars ) )
  458. ->parse();
  459. }
  460. // Type documentation
  461. if ( !isset( $settings[ApiBase::PARAM_TYPE] ) ) {
  462. $dflt = $settings[ApiBase::PARAM_DFLT] ?? null;
  463. if ( is_bool( $dflt ) ) {
  464. $settings[ApiBase::PARAM_TYPE] = 'boolean';
  465. } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
  466. $settings[ApiBase::PARAM_TYPE] = 'string';
  467. } elseif ( is_int( $dflt ) ) {
  468. $settings[ApiBase::PARAM_TYPE] = 'integer';
  469. }
  470. }
  471. if ( isset( $settings[ApiBase::PARAM_TYPE] ) ) {
  472. $type = $settings[ApiBase::PARAM_TYPE];
  473. $multi = !empty( $settings[ApiBase::PARAM_ISMULTI] );
  474. $hintPipeSeparated = true;
  475. $count = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT2] )
  476. ? $settings[ApiBase::PARAM_ISMULTI_LIMIT2] + 1
  477. : ApiBase::LIMIT_SML2 + 1;
  478. if ( is_array( $type ) ) {
  479. $count = count( $type );
  480. $deprecatedValues = $settings[ApiBase::PARAM_DEPRECATED_VALUES] ?? [];
  481. $links = $settings[ApiBase::PARAM_VALUE_LINKS] ?? [];
  482. $values = array_map( function ( $v ) use ( $links, $deprecatedValues ) {
  483. $attr = [];
  484. if ( $v !== '' ) {
  485. // We can't know whether this contains LTR or RTL text.
  486. $attr['dir'] = 'auto';
  487. }
  488. if ( isset( $deprecatedValues[$v] ) ) {
  489. $attr['class'] = 'apihelp-deprecated-value';
  490. }
  491. $ret = $attr ? Html::element( 'span', $attr, $v ) : $v;
  492. if ( isset( $links[$v] ) ) {
  493. $ret = "[[{$links[$v]}|$ret]]";
  494. }
  495. return $ret;
  496. }, $type );
  497. $i = array_search( '', $type, true );
  498. if ( $i === false ) {
  499. $values = $context->getLanguage()->commaList( $values );
  500. } else {
  501. unset( $values[$i] );
  502. $values = $context->msg( 'api-help-param-list-can-be-empty' )
  503. ->numParams( count( $values ) )
  504. ->params( $context->getLanguage()->commaList( $values ) )
  505. ->parse();
  506. }
  507. $info[] = $context->msg( 'api-help-param-list' )
  508. ->params( $multi ? 2 : 1 )
  509. ->params( $values )
  510. ->parse();
  511. $hintPipeSeparated = false;
  512. } else {
  513. switch ( $type ) {
  514. case 'submodule':
  515. $groups[] = $name;
  516. if ( isset( $settings[ApiBase::PARAM_SUBMODULE_MAP] ) ) {
  517. $map = $settings[ApiBase::PARAM_SUBMODULE_MAP];
  518. $defaultAttrs = [];
  519. } else {
  520. $prefix = $module->isMain() ? '' : ( $module->getModulePath() . '+' );
  521. $map = [];
  522. foreach ( $module->getModuleManager()->getNames( $name ) as $submoduleName ) {
  523. $map[$submoduleName] = $prefix . $submoduleName;
  524. }
  525. $defaultAttrs = [ 'dir' => 'ltr', 'lang' => 'en' ];
  526. }
  527. ksort( $map );
  528. $submodules = [];
  529. $deprecatedSubmodules = [];
  530. foreach ( $map as $v => $m ) {
  531. $attrs = $defaultAttrs;
  532. $arr = &$submodules;
  533. try {
  534. $submod = $module->getModuleFromPath( $m );
  535. if ( $submod && $submod->isDeprecated() ) {
  536. $arr = &$deprecatedSubmodules;
  537. $attrs['class'] = 'apihelp-deprecated-value';
  538. }
  539. } catch ( ApiUsageException $ex ) {
  540. // Ignore
  541. }
  542. if ( $attrs ) {
  543. $v = Html::element( 'span', $attrs, $v );
  544. }
  545. $arr[] = "[[Special:ApiHelp/{$m}|{$v}]]";
  546. }
  547. $submodules = array_merge( $submodules, $deprecatedSubmodules );
  548. $count = count( $submodules );
  549. $info[] = $context->msg( 'api-help-param-list' )
  550. ->params( $multi ? 2 : 1 )
  551. ->params( $context->getLanguage()->commaList( $submodules ) )
  552. ->parse();
  553. $hintPipeSeparated = false;
  554. // No type message necessary, we have a list of values.
  555. $type = null;
  556. break;
  557. case 'namespace':
  558. $namespaces = MediaWikiServices::getInstance()->
  559. getNamespaceInfo()->getValidNamespaces();
  560. if ( isset( $settings[ApiBase::PARAM_EXTRA_NAMESPACES] ) &&
  561. is_array( $settings[ApiBase::PARAM_EXTRA_NAMESPACES] )
  562. ) {
  563. $namespaces = array_merge( $namespaces, $settings[ApiBase::PARAM_EXTRA_NAMESPACES] );
  564. }
  565. sort( $namespaces );
  566. $count = count( $namespaces );
  567. $info[] = $context->msg( 'api-help-param-list' )
  568. ->params( $multi ? 2 : 1 )
  569. ->params( $context->getLanguage()->commaList( $namespaces ) )
  570. ->parse();
  571. $hintPipeSeparated = false;
  572. // No type message necessary, we have a list of values.
  573. $type = null;
  574. break;
  575. case 'tags':
  576. $tags = ChangeTags::listExplicitlyDefinedTags();
  577. $count = count( $tags );
  578. $info[] = $context->msg( 'api-help-param-list' )
  579. ->params( $multi ? 2 : 1 )
  580. ->params( $context->getLanguage()->commaList( $tags ) )
  581. ->parse();
  582. $hintPipeSeparated = false;
  583. $type = null;
  584. break;
  585. case 'limit':
  586. if ( isset( $settings[ApiBase::PARAM_MAX2] ) ) {
  587. $info[] = $context->msg( 'api-help-param-limit2' )
  588. ->numParams( $settings[ApiBase::PARAM_MAX] )
  589. ->numParams( $settings[ApiBase::PARAM_MAX2] )
  590. ->parse();
  591. } else {
  592. $info[] = $context->msg( 'api-help-param-limit' )
  593. ->numParams( $settings[ApiBase::PARAM_MAX] )
  594. ->parse();
  595. }
  596. break;
  597. case 'integer':
  598. // Possible messages:
  599. // api-help-param-integer-min,
  600. // api-help-param-integer-max,
  601. // api-help-param-integer-minmax
  602. $suffix = '';
  603. $min = $max = 0;
  604. if ( isset( $settings[ApiBase::PARAM_MIN] ) ) {
  605. $suffix .= 'min';
  606. $min = $settings[ApiBase::PARAM_MIN];
  607. }
  608. if ( isset( $settings[ApiBase::PARAM_MAX] ) ) {
  609. $suffix .= 'max';
  610. $max = $settings[ApiBase::PARAM_MAX];
  611. }
  612. if ( $suffix !== '' ) {
  613. $info[] =
  614. $context->msg( "api-help-param-integer-$suffix" )
  615. ->params( $multi ? 2 : 1 )
  616. ->numParams( $min, $max )
  617. ->parse();
  618. }
  619. break;
  620. case 'upload':
  621. $info[] = $context->msg( 'api-help-param-upload' )
  622. ->parse();
  623. // No type message necessary, api-help-param-upload should handle it.
  624. $type = null;
  625. break;
  626. case 'string':
  627. case 'text':
  628. // Displaying a type message here would be useless.
  629. $type = null;
  630. break;
  631. }
  632. }
  633. // Add type. Messages for grep: api-help-param-type-limit
  634. // api-help-param-type-integer api-help-param-type-boolean
  635. // api-help-param-type-timestamp api-help-param-type-user
  636. // api-help-param-type-password
  637. if ( is_string( $type ) ) {
  638. $msg = $context->msg( "api-help-param-type-$type" );
  639. if ( !$msg->isDisabled() ) {
  640. $info[] = $msg->params( $multi ? 2 : 1 )->parse();
  641. }
  642. }
  643. if ( $multi ) {
  644. $extra = [];
  645. $lowcount = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT1] )
  646. ? $settings[ApiBase::PARAM_ISMULTI_LIMIT1]
  647. : ApiBase::LIMIT_SML1;
  648. $highcount = !empty( $settings[ApiBase::PARAM_ISMULTI_LIMIT2] )
  649. ? $settings[ApiBase::PARAM_ISMULTI_LIMIT2]
  650. : ApiBase::LIMIT_SML2;
  651. if ( $hintPipeSeparated ) {
  652. $extra[] = $context->msg( 'api-help-param-multi-separate' )->parse();
  653. }
  654. if ( $count > $lowcount ) {
  655. if ( $lowcount === $highcount ) {
  656. $msg = $context->msg( 'api-help-param-multi-max-simple' )
  657. ->numParams( $lowcount );
  658. } else {
  659. $msg = $context->msg( 'api-help-param-multi-max' )
  660. ->numParams( $lowcount, $highcount );
  661. }
  662. $extra[] = $msg->parse();
  663. }
  664. if ( $extra ) {
  665. $info[] = implode( ' ', $extra );
  666. }
  667. $allowAll = $settings[ApiBase::PARAM_ALL] ?? false;
  668. if ( $allowAll || $settings[ApiBase::PARAM_TYPE] === 'namespace' ) {
  669. if ( $settings[ApiBase::PARAM_TYPE] === 'namespace' ) {
  670. $allSpecifier = ApiBase::ALL_DEFAULT_STRING;
  671. } else {
  672. $allSpecifier = ( is_string( $allowAll ) ? $allowAll : ApiBase::ALL_DEFAULT_STRING );
  673. }
  674. $info[] = $context->msg( 'api-help-param-multi-all' )
  675. ->params( $allSpecifier )
  676. ->parse();
  677. }
  678. }
  679. }
  680. if ( isset( $settings[self::PARAM_MAX_BYTES] ) ) {
  681. $info[] = $context->msg( 'api-help-param-maxbytes' )
  682. ->numParams( $settings[self::PARAM_MAX_BYTES] );
  683. }
  684. if ( isset( $settings[self::PARAM_MAX_CHARS] ) ) {
  685. $info[] = $context->msg( 'api-help-param-maxchars' )
  686. ->numParams( $settings[self::PARAM_MAX_CHARS] );
  687. }
  688. // Add default
  689. $default = $settings[ApiBase::PARAM_DFLT] ?? null;
  690. if ( $default === '' ) {
  691. $info[] = $context->msg( 'api-help-param-default-empty' )
  692. ->parse();
  693. } elseif ( $default !== null && $default !== false ) {
  694. // We can't know whether this contains LTR or RTL text.
  695. $info[] = $context->msg( 'api-help-param-default' )
  696. ->params( Html::element( 'span', [ 'dir' => 'auto' ], $default ) )
  697. ->parse();
  698. }
  699. if ( !array_filter( $description ) ) {
  700. $description = [ self::wrap(
  701. $context->msg( 'api-help-param-no-description' ),
  702. 'apihelp-empty'
  703. ) ];
  704. }
  705. // Add "deprecated" flag
  706. if ( !empty( $settings[ApiBase::PARAM_DEPRECATED] ) ) {
  707. $help['parameters'] .= Html::openElement( 'dd',
  708. [ 'class' => 'info' ] );
  709. $help['parameters'] .= self::wrap(
  710. $context->msg( 'api-help-param-deprecated' ),
  711. 'apihelp-deprecated', 'strong'
  712. );
  713. $help['parameters'] .= Html::closeElement( 'dd' );
  714. }
  715. if ( $description ) {
  716. $description = implode( '', $description );
  717. $description = preg_replace( '!\s*</([oud]l)>\s*<\1>\s*!', "\n", $description );
  718. $help['parameters'] .= Html::rawElement( 'dd',
  719. [ 'class' => 'description' ], $description );
  720. }
  721. foreach ( $info as $i ) {
  722. $help['parameters'] .= Html::rawElement( 'dd', [ 'class' => 'info' ], $i );
  723. }
  724. }
  725. if ( $dynamicParams !== null ) {
  726. $dynamicParams = ApiBase::makeMessage( $dynamicParams, $context, [
  727. $module->getModulePrefix(),
  728. $module->getModuleName(),
  729. $module->getModulePath()
  730. ] );
  731. $help['parameters'] .= Html::element( 'dt', null, '*' );
  732. $help['parameters'] .= Html::rawElement( 'dd',
  733. [ 'class' => 'description' ], $dynamicParams->parse() );
  734. }
  735. $help['parameters'] .= Html::closeElement( 'dl' );
  736. $help['parameters'] .= Html::closeElement( 'div' );
  737. }
  738. $examples = $module->getExamplesMessages();
  739. if ( $examples ) {
  740. $help['examples'] .= Html::openElement( 'div',
  741. [ 'class' => 'apihelp-block apihelp-examples' ] );
  742. $msg = $context->msg( 'api-help-examples' );
  743. if ( !$msg->isDisabled() ) {
  744. $help['examples'] .= self::wrap(
  745. $msg->numParams( count( $examples ) ), 'apihelp-block-head', 'div'
  746. );
  747. }
  748. $help['examples'] .= Html::openElement( 'dl' );
  749. foreach ( $examples as $qs => $msg ) {
  750. $msg = ApiBase::makeMessage( $msg, $context, [
  751. $module->getModulePrefix(),
  752. $module->getModuleName(),
  753. $module->getModulePath()
  754. ] );
  755. $link = wfAppendQuery( wfScript( 'api' ), $qs );
  756. $sandbox = SpecialPage::getTitleFor( 'ApiSandbox' )->getLocalURL() . '#' . $qs;
  757. $help['examples'] .= Html::rawElement( 'dt', null, $msg->parse() );
  758. $help['examples'] .= Html::rawElement( 'dd', null,
  759. Html::element( 'a', [ 'href' => $link, 'dir' => 'ltr' ], "api.php?$qs" ) . ' ' .
  760. Html::rawElement( 'a', [ 'href' => $sandbox ],
  761. $context->msg( 'api-help-open-in-apisandbox' )->parse() )
  762. );
  763. }
  764. $help['examples'] .= Html::closeElement( 'dl' );
  765. $help['examples'] .= Html::closeElement( 'div' );
  766. }
  767. $subtocnumber = $tocnumber;
  768. $subtocnumber[$level + 1] = 0;
  769. $suboptions = [
  770. 'submodules' => $options['recursivesubmodules'],
  771. 'headerlevel' => $level + 1,
  772. 'tocnumber' => &$subtocnumber,
  773. 'noheader' => false,
  774. ] + $options;
  775. if ( $options['submodules'] && $module->getModuleManager() ) {
  776. $manager = $module->getModuleManager();
  777. $submodules = [];
  778. foreach ( $groups as $group ) {
  779. $names = $manager->getNames( $group );
  780. sort( $names );
  781. foreach ( $names as $name ) {
  782. $submodules[] = $manager->getModule( $name );
  783. }
  784. }
  785. $help['submodules'] .= self::getHelpInternal(
  786. $context,
  787. $submodules,
  788. $suboptions,
  789. $haveModules
  790. );
  791. }
  792. $module->modifyHelp( $help, $suboptions, $haveModules );
  793. Hooks::run( 'APIHelpModifyOutput', [ $module, &$help, $suboptions, &$haveModules ] );
  794. $out .= implode( "\n", $help );
  795. }
  796. return $out;
  797. }
  798. public function shouldCheckMaxlag() {
  799. return false;
  800. }
  801. public function isReadMode() {
  802. return false;
  803. }
  804. public function getCustomPrinter() {
  805. $params = $this->extractRequestParams();
  806. if ( $params['wrap'] ) {
  807. return null;
  808. }
  809. $main = $this->getMain();
  810. $errorPrinter = $main->createPrinterByName( $main->getParameter( 'format' ) );
  811. return new ApiFormatRaw( $main, $errorPrinter );
  812. }
  813. public function getAllowedParams() {
  814. return [
  815. 'modules' => [
  816. ApiBase::PARAM_DFLT => 'main',
  817. ApiBase::PARAM_ISMULTI => true,
  818. ],
  819. 'submodules' => false,
  820. 'recursivesubmodules' => false,
  821. 'wrap' => false,
  822. 'toc' => false,
  823. ];
  824. }
  825. protected function getExamplesMessages() {
  826. return [
  827. 'action=help'
  828. => 'apihelp-help-example-main',
  829. 'action=help&modules=query&submodules=1'
  830. => 'apihelp-help-example-submodules',
  831. 'action=help&recursivesubmodules=1'
  832. => 'apihelp-help-example-recursive',
  833. 'action=help&modules=help'
  834. => 'apihelp-help-example-help',
  835. 'action=help&modules=query+info|query+categorymembers'
  836. => 'apihelp-help-example-query',
  837. ];
  838. }
  839. public function getHelpUrls() {
  840. return [
  841. 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Main_page',
  842. 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:FAQ',
  843. 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Quick_start_guide',
  844. ];
  845. }
  846. }