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