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