Merge "Select column page_lang in prop=info"
[lhc/web/wiklou.git] / includes / api / ApiHelp.php
1 <?php
2 /**
3 *
4 *
5 * Created on Aug 29, 2014
6 *
7 * Copyright © 2014 Brad Jorsch <bjorsch@wikimedia.org>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * Class to output help for an API module
29 *
30 * @since 1.25 completely rewritten
31 * @ingroup API
32 */
33 class ApiHelp extends ApiBase {
34 public function execute() {
35 global $wgContLang;
36
37 $params = $this->extractRequestParams();
38 $modules = array();
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 $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 = array(
62 'mime' => 'text/html',
63 'help' => $html,
64 );
65 $result->setSubelements( $data, 'help' );
66 $result->addValue( null, $this->getModuleName(), $data );
67 } else {
68 $result->reset();
69 $result->addValue( null, 'text', $html, ApiResult::NO_SIZE_CHECK );
70 $result->addValue( null, 'mime', 'text/html', ApiResult::NO_SIZE_CHECK );
71 }
72 }
73
74 /**
75 * Generate help for the specified modules
76 *
77 * Help is placed into the OutputPage object returned by
78 * $context->getOutput().
79 *
80 * Recognized options include:
81 * - headerlevel: (int) Header tag level
82 * - nolead: (bool) Skip the inclusion of api-help-lead
83 * - noheader: (bool) Skip the inclusion of the top-level section headers
84 * - submodules: (bool) Include help for submodules of the current module
85 * - recursivesubmodules: (bool) Include help for submodules recursively
86 * - helptitle: (string) Title to link for additional modules' help. Should contain $1.
87 *
88 * @param IContextSource $context
89 * @param ApiBase[]|ApiBase $modules
90 * @param array $options Formatting options (described above)
91 * @return string
92 */
93 public static function getHelp( IContextSource $context, $modules, array $options ) {
94 global $wgMemc, $wgContLang;
95
96 if ( !is_array( $modules ) ) {
97 $modules = array( $modules );
98 }
99
100 $out = $context->getOutput();
101 $out->addModules( 'mediawiki.apihelp' );
102 $out->setPageTitle( $context->msg( 'api-help-title' ) );
103
104 $cacheKey = null;
105 if ( count( $modules ) == 1 && $modules[0] instanceof ApiMain &&
106 $options['recursivesubmodules'] && $context->getLanguage() === $wgContLang
107 ) {
108 $cacheHelpTimeout = $context->getConfig()->get( 'APICacheHelpTimeout' );
109 if ( $cacheHelpTimeout > 0 ) {
110 // Get help text from cache if present
111 $cacheKey = wfMemcKey( 'apihelp', $modules[0]->getModulePath(),
112 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
113 $cached = $wgMemc->get( $cacheKey );
114 if ( $cached ) {
115 $out->addHTML( $cached );
116 return;
117 }
118 }
119 }
120 if ( $out->getHTML() !== '' ) {
121 // Don't save to cache, there's someone else's content in the page
122 // already
123 $cacheKey = null;
124 }
125
126 $options['recursivesubmodules'] = !empty( $options['recursivesubmodules'] );
127 $options['submodules'] = $options['recursivesubmodules'] || !empty( $options['submodules'] );
128
129 // Prepend lead
130 if ( empty( $options['nolead'] ) ) {
131 $msg = $context->msg( 'api-help-lead' );
132 if ( !$msg->isDisabled() ) {
133 $out->addHTML( $msg->parseAsBlock() );
134 }
135 }
136
137 $haveModules = array();
138 $out->addHTML( self::getHelpInternal( $context, $modules, $options, $haveModules ) );
139
140 $helptitle = isset( $options['helptitle'] ) ? $options['helptitle'] : null;
141 $html = self::fixHelpLinks( $out->getHTML(), $helptitle, $haveModules );
142 $out->clearHTML();
143 $out->addHTML( $html );
144
145 if ( $cacheKey !== null ) {
146 $wgMemc->set( $cacheKey, $out->getHTML(), $cacheHelpTimeout );
147 }
148 }
149
150 /**
151 * Replace Special:ApiHelp links with links to api.php
152 *
153 * @param string $html
154 * @param string|null $helptitle Title to link to rather than api.php, must contain '$1'
155 * @param array $localModules Modules to link within the current page
156 * @return string
157 */
158 public static function fixHelpLinks( $html, $helptitle = null, $localModules = array() ) {
159 $formatter = new HtmlFormatter( $html );
160 $doc = $formatter->getDoc();
161 $xpath = new DOMXPath( $doc );
162 $nodes = $xpath->query( '//a[@href][not(contains(@class,\'apihelp-linktrail\'))]' );
163 foreach ( $nodes as $node ) {
164 $href = $node->getAttribute( 'href' );
165 do {
166 $old = $href;
167 $href = rawurldecode( $href );
168 } while ( $old !== $href );
169 if ( preg_match( '!Special:ApiHelp/([^&/|]+)!', $href, $m ) ) {
170 if ( isset( $localModules[$m[1]] ) ) {
171 $href = '#' . $m[1];
172 } elseif ( $helptitle !== null ) {
173 $href = Title::newFromText( str_replace( '$1', $m[1], $helptitle ) )
174 ->getFullUrl();
175 } else {
176 $href = wfAppendQuery( wfScript( 'api' ), array(
177 'action' => 'help',
178 'modules' => $m[1],
179 ) );
180 }
181 $node->setAttribute( 'href', $href );
182 $node->removeAttribute( 'title' );
183 }
184 }
185
186 return $formatter->getText();
187 }
188
189 /**
190 * Wrap a message in HTML with a class.
191 *
192 * @param Message $msg
193 * @param string $class
194 * @param string $tag
195 * @return string
196 */
197 private static function wrap( Message $msg, $class, $tag = 'span' ) {
198 return Html::rawElement( $tag, array( 'class' => $class ),
199 $msg->parse()
200 );
201 }
202
203 /**
204 * Recursively-called function to actually construct the help
205 *
206 * @param IContextSource $context
207 * @param ApiBase[] $modules
208 * @param array $options
209 * @param array &$haveModules
210 * @return string
211 */
212 private static function getHelpInternal( IContextSource $context, array $modules,
213 array $options, &$haveModules
214 ) {
215 $out = '';
216
217 $level = min( 6, empty( $options['headerlevel'] ) ? 2 : $options['headerlevel'] );
218 $options['headerlevel'] = $level;
219
220 foreach ( $modules as $module ) {
221 $haveModules[$module->getModulePath()] = true;
222 $module->setContext( $context );
223 $help = array(
224 'header' => '',
225 'flags' => '',
226 'description' => '',
227 'help-urls' => '',
228 'parameters' => '',
229 'examples' => '',
230 'submodules' => '',
231 );
232
233 if ( empty( $options['noheader'] ) ) {
234 $path = $module->getModulePath();
235 if ( $module->isMain() ) {
236 $header = $context->msg( 'api-help-main-header' )->parse();
237 } else {
238 $name = $module->getModuleName();
239 $header = $module->getParent()->getModuleManager()->getModuleGroup( $name ) .
240 "=$name";
241 if ( $module->getModulePrefix() !== '' ) {
242 $header .= ' ' .
243 $context->msg( 'parentheses', $module->getModulePrefix() )->parse();
244 }
245 }
246 $help['header'] .= Html::element( "h$level",
247 array( 'id' => $path, 'class' => 'apihelp-header' ),
248 $header
249 );
250 }
251
252 $links = array();
253 $any = false;
254 for ( $m = $module; $m !== null; $m = $m->getParent() ) {
255 $name = $m->getModuleName();
256 if ( $name === 'main_int' ) {
257 $name = 'main';
258 }
259
260 if ( count( $modules ) === 1 && $m === $modules[0] &&
261 !( !empty( $options['submodules'] ) && $m->getModuleManager() )
262 ) {
263 $link = Html::element( 'b', null, $name );
264 } else {
265 $link = SpecialPage::getTitleFor( 'ApiHelp', $m->getModulePath() )->getLocalURL();
266 $link = Html::element( 'a',
267 array( 'href' => $link, 'class' => 'apihelp-linktrail' ),
268 $name
269 );
270 $any = true;
271 }
272 array_unshift( $links, $link );
273 }
274 if ( $any ) {
275 $help['header'] .= self::wrap(
276 $context->msg( 'parentheses' )
277 ->rawParams( $context->getLanguage()->pipeList( $links ) ),
278 'apihelp-linktrail', 'div'
279 );
280 }
281
282 $flags = $module->getHelpFlags();
283 if ( $flags ) {
284 $help['flags'] .= Html::openElement( 'div',
285 array( 'class' => 'apihelp-block apihelp-flags' ) );
286 $msg = $context->msg( 'api-help-flags' );
287 if ( !$msg->isDisabled() ) {
288 $help['flags'] .= self::wrap(
289 $msg->numParams( count( $flags ) ), 'apihelp-block-head', 'div'
290 );
291 }
292 $help['flags'] .= Html::openElement( 'ul' );
293 foreach ( $flags as $flag ) {
294 $help['flags'] .= Html::rawElement( 'li', null,
295 self::wrap( $context->msg( "api-help-flag-$flag" ), "apihelp-flag-$flag" )
296 );
297 }
298 $help['flags'] .= Html::closeElement( 'ul' );
299 $help['flags'] .= Html::closeElement( 'div' );
300 }
301
302 foreach ( $module->getFinalDescription() as $msg ) {
303 $msg->setContext( $context );
304 $help['description'] .= $msg->parseAsBlock();
305 }
306
307 $urls = $module->getHelpUrls();
308 if ( $urls ) {
309 $help['help-urls'] .= Html::openElement( 'div',
310 array( 'class' => 'apihelp-block apihelp-help-urls' )
311 );
312 $msg = $context->msg( 'api-help-help-urls' );
313 if ( !$msg->isDisabled() ) {
314 $help['help-urls'] .= self::wrap(
315 $msg->numParams( count( $urls ) ), 'apihelp-block-head', 'div'
316 );
317 }
318 if ( !is_array( $urls ) ) {
319 $urls = array( $urls );
320 }
321 $help['help-urls'] .= Html::openElement( 'ul' );
322 foreach ( $urls as $url ) {
323 $help['help-urls'] .= Html::rawElement( 'li', null,
324 Html::element( 'a', array( 'href' => $url ), $url )
325 );
326 }
327 $help['help-urls'] .= Html::closeElement( 'ul' );
328 $help['help-urls'] .= Html::closeElement( 'div' );
329 }
330
331 $params = $module->getFinalParams( ApiBase::GET_VALUES_FOR_HELP );
332 $groups = array();
333 if ( $params ) {
334 $help['parameters'] .= Html::openElement( 'div',
335 array( 'class' => 'apihelp-block apihelp-parameters' )
336 );
337 $msg = $context->msg( 'api-help-parameters' );
338 if ( !$msg->isDisabled() ) {
339 $help['parameters'] .= self::wrap(
340 $msg->numParams( count( $params ) ), 'apihelp-block-head', 'div'
341 );
342 }
343 $help['parameters'] .= Html::openElement( 'dl' );
344
345 $descriptions = $module->getFinalParamDescription();
346
347 foreach ( $params as $name => $settings ) {
348 if ( !is_array( $settings ) ) {
349 $settings = array( ApiBase::PARAM_DFLT => $settings );
350 }
351
352 $help['parameters'] .= Html::element( 'dt', null,
353 $module->encodeParamName( $name ) );
354
355 // Add description
356 $description = array();
357 if ( isset( $descriptions[$name] ) ) {
358 foreach ( $descriptions[$name] as $msg ) {
359 $msg->setContext( $context );
360 $description[] = $msg->parseAsBlock();
361 }
362 }
363
364 // Add usage info
365 $info = array();
366
367 // Required?
368 if ( !empty( $settings[ApiBase::PARAM_REQUIRED] ) ) {
369 $info[] = $context->msg( 'api-help-param-required' )->parse();
370 }
371
372 // Custom info?
373 if ( !empty( $settings[ApiBase::PARAM_HELP_MSG_INFO] ) ) {
374 foreach ( $settings[ApiBase::PARAM_HELP_MSG_INFO] as $i ) {
375 $tag = array_shift( $i );
376 $info[] = $context->msg( "apihelp-{$path}-paraminfo-{$tag}" )
377 ->numParams( count( $i ) )
378 ->params( $context->getLanguage()->commaList( $i ) )
379 ->params( $module->getModulePrefix() )
380 ->parse();
381 }
382 }
383
384 // Type documentation
385 if ( !isset( $settings[ApiBase::PARAM_TYPE] ) ) {
386 $dflt = isset( $settings[ApiBase::PARAM_DFLT] )
387 ? $settings[ApiBase::PARAM_DFLT]
388 : null;
389 if ( is_bool( $dflt ) ) {
390 $settings[ApiBase::PARAM_TYPE] = 'boolean';
391 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
392 $settings[ApiBase::PARAM_TYPE] = 'string';
393 } elseif ( is_int( $dflt ) ) {
394 $settings[ApiBase::PARAM_TYPE] = 'integer';
395 }
396 }
397 if ( isset( $settings[ApiBase::PARAM_TYPE] ) ) {
398 $type = $settings[ApiBase::PARAM_TYPE];
399 $multi = !empty( $settings[ApiBase::PARAM_ISMULTI] );
400 $hintPipeSeparated = true;
401 $count = ApiBase::LIMIT_SML2 + 1;
402
403 if ( is_array( $type ) ) {
404 $count = count( $type );
405 $links = isset( $settings[ApiBase::PARAM_VALUE_LINKS] )
406 ? $settings[ApiBase::PARAM_VALUE_LINKS]
407 : array();
408 $type = array_map( function ( $v ) use ( $links ) {
409 $ret = wfEscapeWikiText( $v );
410 if ( isset( $links[$v] ) ) {
411 $ret = "[[{$links[$v]}|$ret]]";
412 }
413 return $ret;
414 }, $type );
415 $i = array_search( '', $type, true );
416 if ( $i === false ) {
417 $type = $context->getLanguage()->commaList( $type );
418 } else {
419 unset( $type[$i] );
420 $type = $context->msg( 'api-help-param-list-can-be-empty' )
421 ->numParams( count( $type ) )
422 ->params( $context->getLanguage()->commaList( $type ) )
423 ->parse();
424 }
425 $info[] = $context->msg( 'api-help-param-list' )
426 ->params( $multi ? 2 : 1 )
427 ->params( $type )
428 ->parse();
429 $hintPipeSeparated = false;
430 } else {
431 switch ( $type ) {
432 case 'submodule':
433 $groups[] = $name;
434 $submodules = $module->getModuleManager()->getNames( $name );
435 $count = count( $submodules );
436 sort( $submodules );
437 $prefix = $module->isMain()
438 ? '' : ( $module->getModulePath() . '+' );
439 $submodules = array_map( function ( $name ) use ( $prefix ) {
440 return "[[Special:ApiHelp/{$prefix}{$name}|{$name}]]";
441 }, $submodules );
442 $info[] = $context->msg( 'api-help-param-list' )
443 ->params( $multi ? 2 : 1 )
444 ->params( $context->getLanguage()->commaList( $submodules ) )
445 ->parse();
446 $hintPipeSeparated = false;
447 break;
448
449 case 'namespace':
450 $namespaces = MWNamespace::getValidNamespaces();
451 $count = count( $namespaces );
452 $info[] = $context->msg( 'api-help-param-list' )
453 ->params( $multi ? 2 : 1 )
454 ->params( $context->getLanguage()->commaList( $namespaces ) )
455 ->parse();
456 $hintPipeSeparated = false;
457 break;
458
459 case 'limit':
460 if ( isset( $settings[ApiBase::PARAM_MAX2] ) ) {
461 $info[] = $context->msg( 'api-help-param-limit2' )
462 ->numParams( $settings[ApiBase::PARAM_MAX] )
463 ->numParams( $settings[ApiBase::PARAM_MAX2] )
464 ->parse();
465 } else {
466 $info[] = $context->msg( 'api-help-param-limit' )
467 ->numParams( $settings[ApiBase::PARAM_MAX] )
468 ->parse();
469 }
470 break;
471
472 case 'integer':
473 // Possible messages:
474 // api-help-param-integer-min,
475 // api-help-param-integer-max,
476 // api-help-param-integer-minmax
477 $suffix = '';
478 $min = $max = 0;
479 if ( isset( $settings[ApiBase::PARAM_MIN] ) ) {
480 $suffix .= 'min';
481 $min = $settings[ApiBase::PARAM_MIN];
482 }
483 if ( isset( $settings[ApiBase::PARAM_MAX] ) ) {
484 $suffix .= 'max';
485 $max = $settings[ApiBase::PARAM_MAX];
486 }
487 if ( $suffix !== '' ) {
488 $info[] =
489 $context->msg( "api-help-param-integer-$suffix" )
490 ->params( $multi ? 2 : 1 )
491 ->numParams( $min, $max )
492 ->parse();
493 }
494 break;
495
496 case 'upload':
497 $info[] = $context->msg( 'api-help-param-upload' )
498 ->parse();
499 break;
500 }
501 }
502
503 if ( $multi ) {
504 $extra = array();
505 if ( $hintPipeSeparated ) {
506 $extra[] = $context->msg( 'api-help-param-multi-separate' )->parse();
507 }
508 if ( $count > ApiBase::LIMIT_SML1 ) {
509 $extra[] = $context->msg( 'api-help-param-multi-max' )
510 ->numParams( ApiBase::LIMIT_SML1, ApiBase::LIMIT_SML2 )
511 ->parse();
512 }
513 if ( $extra ) {
514 $info[] = join( ' ', $extra );
515 }
516 }
517 }
518
519 // Add default
520 $default = isset( $settings[ApiBase::PARAM_DFLT] )
521 ? $settings[ApiBase::PARAM_DFLT]
522 : null;
523 if ( $default === '' ) {
524 $info[] = $context->msg( 'api-help-param-default-empty' )
525 ->parse();
526 } elseif ( $default !== null && $default !== false ) {
527 $info[] = $context->msg( 'api-help-param-default' )
528 ->params( wfEscapeWikiText( $default ) )
529 ->parse();
530 }
531
532 if ( !array_filter( $description ) ) {
533 $description = array( self::wrap(
534 $context->msg( 'api-help-param-no-description' ),
535 'apihelp-empty'
536 ) );
537 }
538
539 // Add "deprecated" flag
540 if ( !empty( $settings[ApiBase::PARAM_DEPRECATED] ) ) {
541 $help['parameters'] .= Html::openElement( 'dd',
542 array( 'class' => 'info' ) );
543 $help['parameters'] .= self::wrap(
544 $context->msg( 'api-help-param-deprecated' ),
545 'apihelp-deprecated', 'strong'
546 );
547 $help['parameters'] .= Html::closeElement( 'dd' );
548 }
549
550 if ( $description ) {
551 $help['parameters'] .= Html::openElement( 'dd',
552 array( 'class' => 'description' ) );
553 $help['parameters'] .= join( '', $description );
554 $help['parameters'] .= Html::closeElement( 'dd' );
555 }
556
557 foreach ( $info as $i ) {
558 $help['parameters'] .= Html::rawElement( 'dd', array( 'class' => 'info' ), $i );
559 }
560 }
561
562 $help['parameters'] .= Html::closeElement( 'dl' );
563 $help['parameters'] .= Html::closeElement( 'div' );
564 }
565
566 $examples = $module->getExamplesMessages();
567 if ( $examples ) {
568 $help['examples'] .= Html::openElement( 'div',
569 array( 'class' => 'apihelp-block apihelp-examples' ) );
570 $msg = $context->msg( 'api-help-examples' );
571 if ( !$msg->isDisabled() ) {
572 $help['examples'] .= self::wrap(
573 $msg->numParams( count( $examples ) ), 'apihelp-block-head', 'div'
574 );
575 }
576
577 $help['examples'] .= Html::openElement( 'dl' );
578 foreach ( $examples as $qs => $msg ) {
579 $msg = ApiBase::makeMessage( $msg, $context, array(
580 $module->getModulePrefix(),
581 $module->getModuleName(),
582 $module->getModulePath()
583 ) );
584
585 $link = wfAppendQuery( wfScript( 'api' ), $qs );
586 $help['examples'] .= Html::rawElement( 'dt', null, $msg->parse() );
587 $help['examples'] .= Html::rawElement( 'dd', null,
588 Html::element( 'a', array( 'href' => $link ), "api.php?$qs" )
589 );
590 }
591 $help['examples'] .= Html::closeElement( 'dl' );
592 $help['examples'] .= Html::closeElement( 'div' );
593 }
594
595 if ( $options['submodules'] && $module->getModuleManager() ) {
596 $manager = $module->getModuleManager();
597 $submodules = array();
598 foreach ( $groups as $group ) {
599 $names = $manager->getNames( $group );
600 sort( $names );
601 foreach ( $names as $name ) {
602 $submodules[] = $manager->getModule( $name );
603 }
604 }
605 $help['submodules'] .= self::getHelpInternal( $context, $submodules, array(
606 'submodules' => $options['recursivesubmodules'],
607 'headerlevel' => $level + 1,
608 'noheader' => false,
609 ) + $options, $haveModules );
610 }
611
612 $module->modifyHelp( $help, $options );
613
614 wfRunHooks( 'APIHelpModifyOutput', array( $module, &$help, $options ) );
615
616 $out .= join( "\n", $help );
617 }
618
619 return $out;
620 }
621
622 public function shouldCheckMaxlag() {
623 return false;
624 }
625
626 public function isReadMode() {
627 return false;
628 }
629
630 public function getCustomPrinter() {
631 $params = $this->extractRequestParams();
632 if ( $params['wrap'] ) {
633 return null;
634 }
635
636 $main = $this->getMain();
637 $errorPrinter = $main->createPrinterByName( $main->getParameter( 'format' ) );
638 return new ApiFormatRaw( $main, $errorPrinter );
639 }
640
641 public function getAllowedParams() {
642 return array(
643 'modules' => array(
644 ApiBase::PARAM_DFLT => 'main',
645 ApiBase::PARAM_ISMULTI => true,
646 ),
647 'submodules' => false,
648 'recursivesubmodules' => false,
649 'wrap' => false,
650 'toc' => false,
651 );
652 }
653
654 protected function getExamplesMessages() {
655 return array(
656 'action=help'
657 => 'apihelp-help-example-main',
658 'action=help&recursivesubmodules=1'
659 => 'apihelp-help-example-recursive',
660 'action=help&modules=help'
661 => 'apihelp-help-example-help',
662 'action=help&modules=query+info|query+categorymembers'
663 => 'apihelp-help-example-query',
664 );
665 }
666
667 public function getHelpUrls() {
668 return array(
669 'https://www.mediawiki.org/wiki/API:Main_page',
670 'https://www.mediawiki.org/wiki/API:FAQ',
671 'https://www.mediawiki.org/wiki/API:Quick_start_guide',
672 );
673 }
674 }