Merge "Remove unused variable in ProfilerMwprof"
[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' => $help,
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 ->parse();
380 }
381 }
382
383 // Type documentation
384 if ( !isset( $settings[ApiBase::PARAM_TYPE] ) ) {
385 $dflt = isset( $settings[ApiBase::PARAM_DFLT] )
386 ? $settings[ApiBase::PARAM_DFLT]
387 : null;
388 if ( is_bool( $dflt ) ) {
389 $settings[ApiBase::PARAM_TYPE] = 'boolean';
390 } elseif ( is_string( $dflt ) || is_null( $dflt ) ) {
391 $settings[ApiBase::PARAM_TYPE] = 'string';
392 } elseif ( is_int( $dflt ) ) {
393 $settings[ApiBase::PARAM_TYPE] = 'integer';
394 }
395 }
396 if ( isset( $settings[ApiBase::PARAM_TYPE] ) ) {
397 $type = $settings[ApiBase::PARAM_TYPE];
398 $multi = !empty( $settings[ApiBase::PARAM_ISMULTI] );
399 $hintPipeSeparated = true;
400 $count = ApiBase::LIMIT_SML2 + 1;
401
402 if ( is_array( $type ) ) {
403 $count = count( $type );
404 $links = isset( $settings[ApiBase::PARAM_VALUE_LINKS] )
405 ? $settings[ApiBase::PARAM_VALUE_LINKS]
406 : array();
407 $type = array_map( function ( $v ) use ( $links ) {
408 $ret = wfEscapeWikiText( $v );
409 if ( isset( $links[$v] ) ) {
410 $ret = "[[{$links[$v]}|$ret]]";
411 }
412 return $ret;
413 }, $type );
414 $i = array_search( '', $type, true );
415 if ( $i === false ) {
416 $type = $context->getLanguage()->commaList( $type );
417 } else {
418 unset( $type[$i] );
419 $type = $context->msg( 'api-help-param-list-can-be-empty' )
420 ->numParams( count( $type ) )
421 ->params( $context->getLanguage()->commaList( $type ) )
422 ->parse();
423 }
424 $info[] = $context->msg( 'api-help-param-list' )
425 ->params( $multi ? 2 : 1 )
426 ->params( $type )
427 ->parse();
428 $hintPipeSeparated = false;
429 } else {
430 switch ( $type ) {
431 case 'submodule':
432 $groups[] = $name;
433 $submodules = $module->getModuleManager()->getNames( $name );
434 $count = count( $submodules );
435 sort( $submodules );
436 $prefix = $module->isMain()
437 ? '' : ( $module->getModulePath() . '+' );
438 $submodules = array_map( function ( $name ) use ( $prefix ) {
439 return "[[Special:ApiHelp/{$prefix}{$name}|{$name}]]";
440 }, $submodules );
441 $info[] = $context->msg( 'api-help-param-list' )
442 ->params( $multi ? 2 : 1 )
443 ->params( $context->getLanguage()->commaList( $submodules ) )
444 ->parse();
445 $hintPipeSeparated = false;
446 break;
447
448 case 'namespace':
449 $namespaces = MWNamespace::getValidNamespaces();
450 $count = count( $namespaces );
451 $info[] = $context->msg( 'api-help-param-list' )
452 ->params( $multi ? 2 : 1 )
453 ->params( $context->getLanguage()->commaList( $namespaces ) )
454 ->parse();
455 $hintPipeSeparated = false;
456 break;
457
458 case 'limit':
459 if ( isset( $settings[ApiBase::PARAM_MAX2] ) ) {
460 $info[] = $context->msg( 'api-help-param-limit2' )
461 ->numParams( $settings[ApiBase::PARAM_MAX] )
462 ->numParams( $settings[ApiBase::PARAM_MAX2] )
463 ->parse();
464 } else {
465 $info[] = $context->msg( 'api-help-param-limit' )
466 ->numParams( $settings[ApiBase::PARAM_MAX] )
467 ->parse();
468 }
469 break;
470
471 case 'integer':
472 // Possible messages:
473 // api-help-param-integer-min,
474 // api-help-param-integer-max,
475 // api-help-param-integer-minmax
476 $suffix = '';
477 $min = $max = 0;
478 if ( isset( $settings[ApiBase::PARAM_MIN] ) ) {
479 $suffix .= 'min';
480 $min = $settings[ApiBase::PARAM_MIN];
481 }
482 if ( isset( $settings[ApiBase::PARAM_MAX] ) ) {
483 $suffix .= 'max';
484 $max = $settings[ApiBase::PARAM_MAX];
485 }
486 if ( $suffix !== '' ) {
487 $info[] =
488 $context->msg( "api-help-param-integer-$suffix" )
489 ->params( $multi ? 2 : 1 )
490 ->numParams( $min, $max )
491 ->parse();
492 }
493 break;
494
495 case 'upload':
496 $info[] = $context->msg( 'api-help-param-upload' )
497 ->parse();
498 break;
499 }
500 }
501
502 if ( $multi ) {
503 $extra = array();
504 if ( $hintPipeSeparated ) {
505 $extra[] = $context->msg( 'api-help-param-multi-separate' )->parse();
506 }
507 if ( $count > ApiBase::LIMIT_SML1 ) {
508 $extra[] = $context->msg( 'api-help-param-multi-max' )
509 ->numParams( ApiBase::LIMIT_SML1, ApiBase::LIMIT_SML2 )
510 ->parse();
511 }
512 if ( $extra ) {
513 $info[] = join( ' ', $extra );
514 }
515 }
516 }
517
518 // Add default
519 $default = isset( $settings[ApiBase::PARAM_DFLT] )
520 ? $settings[ApiBase::PARAM_DFLT]
521 : null;
522 if ( $default === '' ) {
523 $info[] = $context->msg( 'api-help-param-default-empty' )
524 ->parse();
525 } elseif ( $default !== null && $default !== false ) {
526 $info[] = $context->msg( 'api-help-param-default' )
527 ->params( wfEscapeWikiText( $default ) )
528 ->parse();
529 }
530
531 if ( !$description && !$info ) {
532 $description[] = self::wrap(
533 $context->msg( 'api-help-param-no-description' ),
534 'apihelp-empty'
535 );
536 }
537
538 // Add "deprecated" flag
539 if ( !empty( $settings[ApiBase::PARAM_DEPRECATED] ) ) {
540 $help['parameters'] .= Html::openElement( 'dd',
541 array( 'class' => 'info' ) );
542 $help['parameters'] .= self::wrap(
543 $context->msg( 'api-help-param-deprecated' ),
544 'apihelp-deprecated', 'strong'
545 );
546 $help['parameters'] .= Html::closeElement( 'dd' );
547 }
548
549 if ( $description ) {
550 $help['parameters'] .= Html::openElement( 'dd',
551 array( 'class' => 'description' ) );
552 $help['parameters'] .= join( '', $description );
553 $help['parameters'] .= Html::closeElement( 'dd' );
554 }
555
556 foreach ( $info as $i ) {
557 $help['parameters'] .= Html::rawElement( 'dd', array( 'class' => 'info' ), $i );
558 }
559 }
560
561 $help['parameters'] .= Html::closeElement( 'dl' );
562 $help['parameters'] .= Html::closeElement( 'div' );
563 }
564
565 $examples = $module->getExamplesMessages();
566 if ( $examples ) {
567 $help['examples'] .= Html::openElement( 'div',
568 array( 'class' => 'apihelp-block apihelp-examples' ) );
569 $msg = $context->msg( 'api-help-examples' );
570 if ( !$msg->isDisabled() ) {
571 $help['examples'] .= self::wrap(
572 $msg->numParams( count( $examples ) ), 'apihelp-block-head', 'div'
573 );
574 }
575
576 $help['examples'] .= Html::openElement( 'dl' );
577 foreach ( $examples as $qs => $msg ) {
578 $msg = ApiBase::makeMessage( $msg, $context, array(
579 $module->getModulePrefix(),
580 $module->getModuleName(),
581 $module->getModulePath()
582 ) );
583
584 $link = wfAppendQuery( wfScript( 'api' ), $qs );
585 $help['examples'] .= Html::rawElement( 'dt', null, $msg->parse() );
586 $help['examples'] .= Html::rawElement( 'dd', null,
587 Html::element( 'a', array( 'href' => $link ), "api.php?$qs" )
588 );
589 }
590 $help['examples'] .= Html::closeElement( 'dl' );
591 $help['examples'] .= Html::closeElement( 'div' );
592 }
593
594 if ( $options['submodules'] && $module->getModuleManager() ) {
595 $manager = $module->getModuleManager();
596 $submodules = array();
597 foreach ( $groups as $group ) {
598 $names = $manager->getNames( $group );
599 sort( $names );
600 foreach ( $names as $name ) {
601 $submodules[] = $manager->getModule( $name );
602 }
603 }
604 $help['submodules'] .= self::getHelpInternal( $context, $submodules, array(
605 'submodules' => $options['recursivesubmodules'],
606 'headerlevel' => $level + 1,
607 'noheader' => false,
608 ) + $options, $haveModules );
609 }
610
611 $module->modifyHelp( $help, $options );
612
613 wfRunHooks( 'APIHelpModifyOutput', array( $module, &$help, $options ) );
614
615 $out .= join( "\n", $help );
616 }
617
618 return $out;
619 }
620
621 public function shouldCheckMaxlag() {
622 return false;
623 }
624
625 public function isReadMode() {
626 return false;
627 }
628
629 public function getCustomPrinter() {
630 $params = $this->extractRequestParams();
631 if ( $params['wrap'] ) {
632 return null;
633 }
634
635 $main = $this->getMain();
636 $errorPrinter = $main->createPrinterByName( $main->getParameter( 'format' ) );
637 return new ApiFormatRaw( $main, $errorPrinter );
638 }
639
640 public function getAllowedParams() {
641 return array(
642 'modules' => array(
643 ApiBase::PARAM_DFLT => 'main',
644 ApiBase::PARAM_ISMULTI => true,
645 ),
646 'submodules' => false,
647 'recursivesubmodules' => false,
648 'wrap' => false,
649 'toc' => false,
650 );
651 }
652
653 public function getExamplesMessages() {
654 return array(
655 'action=help'
656 => 'apihelp-help-example-main',
657 'action=help&recursivesubmodules=1'
658 => 'apihelp-help-example-recursive',
659 'action=help&modules=help'
660 => 'apihelp-help-example-help',
661 'action=help&modules=query+info|query+categorymembers'
662 => 'apihelp-help-example-query',
663 );
664 }
665
666 public function getHelpUrls() {
667 return array(
668 'https://www.mediawiki.org/wiki/API:Main_page',
669 'https://www.mediawiki.org/wiki/API:FAQ',
670 'https://www.mediawiki.org/wiki/API:Quick_start_guide',
671 );
672 }
673 }