9dc4d03a39c87d1530b5ab28de192f5daf4f29c8
[lhc/web/wiklou.git] / includes / api / ApiParse.php
1 <?php
2 /**
3 * Created on Dec 01, 2007
4 *
5 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 */
24
25 /**
26 * @ingroup API
27 */
28 class ApiParse extends ApiBase {
29
30 /** @var string $section */
31 private $section = null;
32
33 /** @var Content $content */
34 private $content = null;
35
36 /** @var Content $pstContent */
37 private $pstContent = null;
38
39 public function execute() {
40 // The data is hot but user-dependent, like page views, so we set vary cookies
41 $this->getMain()->setCacheMode( 'anon-public-user-private' );
42
43 // Get parameters
44 $params = $this->extractRequestParams();
45 $text = $params['text'];
46 $title = $params['title'];
47 if ( $title === null ) {
48 $titleProvided = false;
49 // A title is needed for parsing, so arbitrarily choose one
50 $title = 'API';
51 } else {
52 $titleProvided = true;
53 }
54
55 $page = $params['page'];
56 $pageid = $params['pageid'];
57 $oldid = $params['oldid'];
58
59 $model = $params['contentmodel'];
60 $format = $params['contentformat'];
61
62 if ( !is_null( $page ) && ( !is_null( $text ) || $titleProvided ) ) {
63 $this->dieUsage(
64 'The page parameter cannot be used together with the text and title parameters',
65 'params'
66 );
67 }
68
69 $prop = array_flip( $params['prop'] );
70
71 if ( isset( $params['section'] ) ) {
72 $this->section = $params['section'];
73 } else {
74 $this->section = false;
75 }
76
77 // The parser needs $wgTitle to be set, apparently the
78 // $title parameter in Parser::parse isn't enough *sigh*
79 // TODO: Does this still need $wgTitle?
80 global $wgParser, $wgTitle;
81
82 // Currently unnecessary, code to act as a safeguard against any change
83 // in current behavior of uselang
84 $oldLang = null;
85 if ( isset( $params['uselang'] )
86 && $params['uselang'] != $this->getContext()->getLanguage()->getCode()
87 ) {
88 $oldLang = $this->getContext()->getLanguage(); // Backup language
89 $this->getContext()->setLanguage( Language::factory( $params['uselang'] ) );
90 }
91
92 $redirValues = null;
93
94 // Return result
95 $result = $this->getResult();
96
97 if ( !is_null( $oldid ) || !is_null( $pageid ) || !is_null( $page ) ) {
98 if ( !is_null( $oldid ) ) {
99 // Don't use the parser cache
100 $rev = Revision::newFromID( $oldid );
101 if ( !$rev ) {
102 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
103 }
104 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
105 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
106 }
107
108 $titleObj = $rev->getTitle();
109 $wgTitle = $titleObj;
110 $pageObj = WikiPage::factory( $titleObj );
111 $popts = $this->makeParserOptions( $pageObj, $params );
112
113 // If for some reason the "oldid" is actually the current revision, it may be cached
114 if ( $rev->isCurrent() ) {
115 // May get from/save to parser cache
116 $p_result = $this->getParsedContent( $pageObj, $popts,
117 $pageid, isset( $prop['wikitext'] ) );
118 } else { // This is an old revision, so get the text differently
119 $this->content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
120
121 if ( $this->section !== false ) {
122 $this->content = $this->getSectionContent( $this->content, 'r' . $rev->getId() );
123 }
124
125 // Should we save old revision parses to the parser cache?
126 $p_result = $this->content->getParserOutput( $titleObj, $rev->getId(), $popts );
127 }
128 } else { // Not $oldid, but $pageid or $page
129 if ( $params['redirects'] ) {
130 $reqParams = array(
131 'action' => 'query',
132 'redirects' => '',
133 );
134 if ( !is_null( $pageid ) ) {
135 $reqParams['pageids'] = $pageid;
136 } else { // $page
137 $reqParams['titles'] = $page;
138 }
139 $req = new FauxRequest( $reqParams );
140 $main = new ApiMain( $req );
141 $main->execute();
142 $data = $main->getResultData();
143 $redirValues = isset( $data['query']['redirects'] )
144 ? $data['query']['redirects']
145 : array();
146 $to = $page;
147 foreach ( (array)$redirValues as $r ) {
148 $to = $r['to'];
149 }
150 $pageParams = array( 'title' => $to );
151 } elseif ( !is_null( $pageid ) ) {
152 $pageParams = array( 'pageid' => $pageid );
153 } else { // $page
154 $pageParams = array( 'title' => $page );
155 }
156
157 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
158 $titleObj = $pageObj->getTitle();
159 if ( !$titleObj || !$titleObj->exists() ) {
160 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
161 }
162 $wgTitle = $titleObj;
163
164 if ( isset( $prop['revid'] ) ) {
165 $oldid = $pageObj->getLatest();
166 }
167
168 $popts = $this->makeParserOptions( $pageObj, $params );
169
170 // Potentially cached
171 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
172 isset( $prop['wikitext'] ) );
173 }
174 } else { // Not $oldid, $pageid, $page. Hence based on $text
175 $titleObj = Title::newFromText( $title );
176 if ( !$titleObj || $titleObj->isExternal() ) {
177 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
178 }
179 $wgTitle = $titleObj;
180 if ( $titleObj->canExist() ) {
181 $pageObj = WikiPage::factory( $titleObj );
182 } else {
183 // Do like MediaWiki::initializeArticle()
184 $article = Article::newFromTitle( $titleObj, $this->getContext() );
185 $pageObj = $article->getPage();
186 }
187
188 $popts = $this->makeParserOptions( $pageObj, $params );
189 $textProvided = !is_null( $text );
190
191 if ( !$textProvided ) {
192 if ( $titleProvided && ( $prop || $params['generatexml'] ) ) {
193 $this->setWarning(
194 "'title' used without 'text', and parsed page properties were requested " .
195 "(did you mean to use 'page' instead of 'title'?)"
196 );
197 }
198 // Prevent warning from ContentHandler::makeContent()
199 $text = '';
200 }
201
202 // If we are parsing text, do not use the content model of the default
203 // API title, but default to wikitext to keep BC.
204 if ( $textProvided && !$titleProvided && is_null( $model ) ) {
205 $model = CONTENT_MODEL_WIKITEXT;
206 $this->setWarning( "No 'title' or 'contentmodel' was given, assuming $model." );
207 }
208
209 try {
210 $this->content = ContentHandler::makeContent( $text, $titleObj, $model, $format );
211 } catch ( MWContentSerializationException $ex ) {
212 $this->dieUsage( $ex->getMessage(), 'parseerror' );
213 }
214
215 if ( $this->section !== false ) {
216 $this->content = $this->getSectionContent( $this->content, $titleObj->getText() );
217 }
218
219 if ( $params['pst'] || $params['onlypst'] ) {
220 $this->pstContent = $this->content->preSaveTransform( $titleObj, $this->getUser(), $popts );
221 }
222 if ( $params['onlypst'] ) {
223 // Build a result and bail out
224 $result_array = array();
225 $result_array['text'] = array();
226 ApiResult::setContent( $result_array['text'], $this->pstContent->serialize( $format ) );
227 if ( isset( $prop['wikitext'] ) ) {
228 $result_array['wikitext'] = array();
229 ApiResult::setContent( $result_array['wikitext'], $this->content->serialize( $format ) );
230 }
231 $result->addValue( null, $this->getModuleName(), $result_array );
232
233 return;
234 }
235
236 // Not cached (save or load)
237 if ( $params['pst'] ) {
238 $p_result = $this->pstContent->getParserOutput( $titleObj, null, $popts );
239 } else {
240 $p_result = $this->content->getParserOutput( $titleObj, null, $popts );
241 }
242 }
243
244 $result_array = array();
245
246 $result_array['title'] = $titleObj->getPrefixedText();
247
248 if ( !is_null( $oldid ) ) {
249 $result_array['revid'] = intval( $oldid );
250 }
251
252 if ( $params['redirects'] && !is_null( $redirValues ) ) {
253 $result_array['redirects'] = $redirValues;
254 }
255
256 if ( $params['disabletoc'] ) {
257 $p_result->setTOCEnabled( false );
258 }
259
260 if ( isset( $prop['text'] ) ) {
261 $result_array['text'] = array();
262 ApiResult::setContent( $result_array['text'], $p_result->getText() );
263 }
264
265 if ( !is_null( $params['summary'] ) ) {
266 $result_array['parsedsummary'] = array();
267 ApiResult::setContent(
268 $result_array['parsedsummary'],
269 Linker::formatComment( $params['summary'], $titleObj )
270 );
271 }
272
273 if ( isset( $prop['langlinks'] ) || isset( $prop['languageshtml'] ) ) {
274 $langlinks = $p_result->getLanguageLinks();
275
276 if ( $params['effectivelanglinks'] ) {
277 // Link flags are ignored for now, but may in the future be
278 // included in the result.
279 $linkFlags = array();
280 wfRunHooks( 'LanguageLinks', array( $titleObj, &$langlinks, &$linkFlags ) );
281 }
282 } else {
283 $langlinks = false;
284 }
285
286 if ( isset( $prop['langlinks'] ) ) {
287 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
288 }
289 if ( isset( $prop['languageshtml'] ) ) {
290 $languagesHtml = $this->languagesHtml( $langlinks );
291
292 $result_array['languageshtml'] = array();
293 ApiResult::setContent( $result_array['languageshtml'], $languagesHtml );
294 }
295 if ( isset( $prop['categories'] ) ) {
296 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
297 }
298 if ( isset( $prop['categorieshtml'] ) ) {
299 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
300 $result_array['categorieshtml'] = array();
301 ApiResult::setContent( $result_array['categorieshtml'], $categoriesHtml );
302 }
303 if ( isset( $prop['links'] ) ) {
304 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
305 }
306 if ( isset( $prop['templates'] ) ) {
307 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
308 }
309 if ( isset( $prop['images'] ) ) {
310 $result_array['images'] = array_keys( $p_result->getImages() );
311 }
312 if ( isset( $prop['externallinks'] ) ) {
313 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
314 }
315 if ( isset( $prop['sections'] ) ) {
316 $result_array['sections'] = $p_result->getSections();
317 }
318
319 if ( isset( $prop['displaytitle'] ) ) {
320 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
321 $p_result->getDisplayTitle() :
322 $titleObj->getPrefixedText();
323 }
324
325 if ( isset( $prop['headitems'] ) || isset( $prop['headhtml'] ) ) {
326 $context = $this->getContext();
327 $context->setTitle( $titleObj );
328 $context->getOutput()->addParserOutputMetadata( $p_result );
329
330 if ( isset( $prop['headitems'] ) ) {
331 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
332
333 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
334
335 $scripts = array( $context->getOutput()->getHeadScripts() );
336
337 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
338 }
339
340 if ( isset( $prop['headhtml'] ) ) {
341 $result_array['headhtml'] = array();
342 ApiResult::setContent(
343 $result_array['headhtml'],
344 $context->getOutput()->headElement( $context->getSkin() )
345 );
346 }
347 }
348
349 if ( isset( $prop['modules'] ) ) {
350 $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
351 $result_array['modulescripts'] = array_values( array_unique( $p_result->getModuleScripts() ) );
352 $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
353 $result_array['modulemessages'] = array_values( array_unique( $p_result->getModuleMessages() ) );
354 }
355
356 if ( isset( $prop['iwlinks'] ) ) {
357 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
358 }
359
360 if ( isset( $prop['wikitext'] ) ) {
361 $result_array['wikitext'] = array();
362 ApiResult::setContent( $result_array['wikitext'], $this->content->serialize( $format ) );
363 if ( !is_null( $this->pstContent ) ) {
364 $result_array['psttext'] = array();
365 ApiResult::setContent( $result_array['psttext'], $this->pstContent->serialize( $format ) );
366 }
367 }
368 if ( isset( $prop['properties'] ) ) {
369 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
370 }
371
372 if ( isset( $prop['limitreportdata'] ) ) {
373 $result_array['limitreportdata'] =
374 $this->formatLimitReportData( $p_result->getLimitReportData() );
375 }
376 if ( isset( $prop['limitreporthtml'] ) ) {
377 $limitreportHtml = EditPage::getPreviewLimitReport( $p_result );
378 $result_array['limitreporthtml'] = array();
379 ApiResult::setContent( $result_array['limitreporthtml'], $limitreportHtml );
380 }
381
382 if ( $params['generatexml'] ) {
383 if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
384 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
385 }
386
387 $wgParser->startExternalParse( $titleObj, $popts, OT_PREPROCESS );
388 $dom = $wgParser->preprocessToDom( $this->content->getNativeData() );
389 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
390 $xml = $dom->saveXML();
391 } else {
392 $xml = $dom->__toString();
393 }
394 $result_array['parsetree'] = array();
395 ApiResult::setContent( $result_array['parsetree'], $xml );
396 }
397
398 $result_mapping = array(
399 'redirects' => 'r',
400 'langlinks' => 'll',
401 'categories' => 'cl',
402 'links' => 'pl',
403 'templates' => 'tl',
404 'images' => 'img',
405 'externallinks' => 'el',
406 'iwlinks' => 'iw',
407 'sections' => 's',
408 'headitems' => 'hi',
409 'modules' => 'm',
410 'modulescripts' => 'm',
411 'modulestyles' => 'm',
412 'modulemessages' => 'm',
413 'properties' => 'pp',
414 'limitreportdata' => 'lr',
415 );
416 $this->setIndexedTagNames( $result_array, $result_mapping );
417 $result->addValue( null, $this->getModuleName(), $result_array );
418
419 if ( !is_null( $oldLang ) ) {
420 $this->getContext()->setLanguage( $oldLang ); // Reset language to $oldLang
421 }
422 }
423
424 /**
425 * Constructs a ParserOptions object
426 *
427 * @param WikiPage $pageObj
428 * @param array $params
429 *
430 * @return ParserOptions
431 */
432 protected function makeParserOptions( WikiPage $pageObj, array $params ) {
433 wfProfileIn( __METHOD__ );
434
435 $popts = $pageObj->makeParserOptions( $this->getContext() );
436 $popts->enableLimitReport( !$params['disablepp'] );
437 $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
438 $popts->setIsSectionPreview( $params['sectionpreview'] );
439 $popts->setEditSection( !$params['disableeditsection'] );
440
441 wfProfileOut( __METHOD__ );
442
443 return $popts;
444 }
445
446 /**
447 * @param WikiPage $page
448 * @param ParserOptions $popts
449 * @param int $pageId
450 * @param bool $getWikitext
451 * @return ParserOutput
452 */
453 private function getParsedContent( WikiPage $page, $popts, $pageId = null, $getWikitext = false ) {
454 $this->content = $page->getContent( Revision::RAW ); //XXX: really raw?
455
456 if ( $this->section !== false && $this->content !== null ) {
457 $this->content = $this->getSectionContent(
458 $this->content,
459 !is_null( $pageId ) ? 'page id ' . $pageId : $page->getTitle()->getText()
460 );
461
462 // Not cached (save or load)
463 return $this->content->getParserOutput( $page->getTitle(), null, $popts );
464 }
465
466 // Try the parser cache first
467 // getParserOutput will save to Parser cache if able
468 $pout = $page->getParserOutput( $popts );
469 if ( !$pout ) {
470 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
471 }
472 if ( $getWikitext ) {
473 $this->content = $page->getContent( Revision::RAW );
474 }
475
476 return $pout;
477 }
478
479 private function getSectionContent( Content $content, $what ) {
480 // Not cached (save or load)
481 $section = $content->getSection( $this->section );
482 if ( $section === false ) {
483 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
484 }
485 if ( $section === null ) {
486 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
487 $section = false;
488 }
489
490 return $section;
491 }
492
493 private function formatLangLinks( $links ) {
494 $result = array();
495 foreach ( $links as $link ) {
496 $entry = array();
497 $bits = explode( ':', $link, 2 );
498 $title = Title::newFromText( $link );
499
500 $entry['lang'] = $bits[0];
501 if ( $title ) {
502 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
503 // localised language name in user language (maybe set by uselang=)
504 $entry['langname'] = Language::fetchLanguageName(
505 $title->getInterwiki(),
506 $this->getLanguage()->getCode()
507 );
508
509 // native language name
510 $entry['autonym'] = Language::fetchLanguageName( $title->getInterwiki() );
511 }
512 ApiResult::setContent( $entry, $bits[1] );
513 $result[] = $entry;
514 }
515
516 return $result;
517 }
518
519 private function formatCategoryLinks( $links ) {
520 $result = array();
521
522 if ( !$links ) {
523 return $result;
524 }
525
526 // Fetch hiddencat property
527 $lb = new LinkBatch;
528 $lb->setArray( array( NS_CATEGORY => $links ) );
529 $db = $this->getDB();
530 $res = $db->select( array( 'page', 'page_props' ),
531 array( 'page_title', 'pp_propname' ),
532 $lb->constructSet( 'page', $db ),
533 __METHOD__,
534 array(),
535 array( 'page_props' => array(
536 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' )
537 ) )
538 );
539 $hiddencats = array();
540 foreach ( $res as $row ) {
541 $hiddencats[$row->page_title] = isset( $row->pp_propname );
542 }
543
544 foreach ( $links as $link => $sortkey ) {
545 $entry = array();
546 $entry['sortkey'] = $sortkey;
547 ApiResult::setContent( $entry, $link );
548 if ( !isset( $hiddencats[$link] ) ) {
549 $entry['missing'] = '';
550 } elseif ( $hiddencats[$link] ) {
551 $entry['hidden'] = '';
552 }
553 $result[] = $entry;
554 }
555
556 return $result;
557 }
558
559 private function categoriesHtml( $categories ) {
560 $context = $this->getContext();
561 $context->getOutput()->addCategoryLinks( $categories );
562
563 return $context->getSkin()->getCategories();
564 }
565
566 /**
567 * @deprecated since 1.18 No modern skin generates language links this way,
568 * please use language links data to generate your own HTML.
569 * @param array $languages
570 * @return string
571 */
572 private function languagesHtml( $languages ) {
573 wfDeprecated( __METHOD__, '1.18' );
574 $this->setWarning( '"action=parse&prop=languageshtml" is deprecated ' .
575 'and will be removed in MediaWiki 1.24. Use "prop=langlinks" ' .
576 'to generate your own HTML.' );
577
578 global $wgContLang;
579
580 if ( $this->getConfig()->get( 'HideInterlanguageLinks' ) || count( $languages ) == 0 ) {
581 return '';
582 }
583
584 $s = htmlspecialchars( wfMessage( 'otherlanguages' )->text() .
585 wfMessage( 'colon-separator' )->text() );
586
587 $langs = array();
588 foreach ( $languages as $l ) {
589 $nt = Title::newFromText( $l );
590 $text = Language::fetchLanguageName( $nt->getInterwiki() );
591
592 $langs[] = Html::element( 'a',
593 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => 'external' ),
594 $text == '' ? $l : $text );
595 }
596
597 $s .= implode( wfMessage( 'pipe-separator' )->escaped(), $langs );
598
599 if ( $wgContLang->isRTL() ) {
600 $s = Html::rawElement( 'span', array( 'dir' => 'LTR' ), $s );
601 }
602
603 return $s;
604 }
605
606 private function formatLinks( $links ) {
607 $result = array();
608 foreach ( $links as $ns => $nslinks ) {
609 foreach ( $nslinks as $title => $id ) {
610 $entry = array();
611 $entry['ns'] = $ns;
612 ApiResult::setContent( $entry, Title::makeTitle( $ns, $title )->getFullText() );
613 if ( $id != 0 ) {
614 $entry['exists'] = '';
615 }
616 $result[] = $entry;
617 }
618 }
619
620 return $result;
621 }
622
623 private function formatIWLinks( $iw ) {
624 $result = array();
625 foreach ( $iw as $prefix => $titles ) {
626 foreach ( array_keys( $titles ) as $title ) {
627 $entry = array();
628 $entry['prefix'] = $prefix;
629
630 $title = Title::newFromText( "{$prefix}:{$title}" );
631 if ( $title ) {
632 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
633 }
634
635 ApiResult::setContent( $entry, $title->getFullText() );
636 $result[] = $entry;
637 }
638 }
639
640 return $result;
641 }
642
643 private function formatHeadItems( $headItems ) {
644 $result = array();
645 foreach ( $headItems as $tag => $content ) {
646 $entry = array();
647 $entry['tag'] = $tag;
648 ApiResult::setContent( $entry, $content );
649 $result[] = $entry;
650 }
651
652 return $result;
653 }
654
655 private function formatProperties( $properties ) {
656 $result = array();
657 foreach ( $properties as $name => $value ) {
658 $entry = array();
659 $entry['name'] = $name;
660 ApiResult::setContent( $entry, $value );
661 $result[] = $entry;
662 }
663
664 return $result;
665 }
666
667 private function formatCss( $css ) {
668 $result = array();
669 foreach ( $css as $file => $link ) {
670 $entry = array();
671 $entry['file'] = $file;
672 ApiResult::setContent( $entry, $link );
673 $result[] = $entry;
674 }
675
676 return $result;
677 }
678
679 private function formatLimitReportData( $limitReportData ) {
680 $result = array();
681 $apiResult = $this->getResult();
682
683 foreach ( $limitReportData as $name => $value ) {
684 $entry = array();
685 $entry['name'] = $name;
686 if ( !is_array( $value ) ) {
687 $value = array( $value );
688 }
689 $apiResult->setIndexedTagName( $value, 'param' );
690 $apiResult->setIndexedTagName_recursive( $value, 'param' );
691 $entry = array_merge( $entry, $value );
692 $result[] = $entry;
693 }
694
695 return $result;
696 }
697
698 private function setIndexedTagNames( &$array, $mapping ) {
699 foreach ( $mapping as $key => $name ) {
700 if ( isset( $array[$key] ) ) {
701 $this->getResult()->setIndexedTagName( $array[$key], $name );
702 }
703 }
704 }
705
706 public function getAllowedParams() {
707 return array(
708 'title' => null,
709 'text' => null,
710 'summary' => null,
711 'page' => null,
712 'pageid' => array(
713 ApiBase::PARAM_TYPE => 'integer',
714 ),
715 'redirects' => false,
716 'oldid' => array(
717 ApiBase::PARAM_TYPE => 'integer',
718 ),
719 'prop' => array(
720 ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|' .
721 'images|externallinks|sections|revid|displaytitle|iwlinks|properties',
722 ApiBase::PARAM_ISMULTI => true,
723 ApiBase::PARAM_TYPE => array(
724 'text',
725 'langlinks',
726 'languageshtml',
727 'categories',
728 'categorieshtml',
729 'links',
730 'templates',
731 'images',
732 'externallinks',
733 'sections',
734 'revid',
735 'displaytitle',
736 'headitems',
737 'headhtml',
738 'modules',
739 'iwlinks',
740 'wikitext',
741 'properties',
742 'limitreportdata',
743 'limitreporthtml',
744 )
745 ),
746 'pst' => false,
747 'onlypst' => false,
748 'effectivelanglinks' => false,
749 'uselang' => null,
750 'section' => null,
751 'disablepp' => false,
752 'disableeditsection' => false,
753 'generatexml' => false,
754 'preview' => false,
755 'sectionpreview' => false,
756 'disabletoc' => false,
757 'contentformat' => array(
758 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
759 ),
760 'contentmodel' => array(
761 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
762 )
763 );
764 }
765
766 public function getParamDescription() {
767 $p = $this->getModulePrefix();
768 $wikitext = CONTENT_MODEL_WIKITEXT;
769
770 return array(
771 'text' => "Text to parse. Use {$p}title or {$p}contentmodel to control the content model",
772 'summary' => 'Summary to parse',
773 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
774 'title' => "Title of page the text belongs to. " .
775 "If omitted, {$p}contentmodel must be specified, and \"API\" will be used as the title",
776 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
777 'pageid' => "Parse the content of this page. Overrides {$p}page",
778 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
779 'prop' => array(
780 'Which pieces of information to get',
781 ' text - Gives the parsed text of the wikitext',
782 ' langlinks - Gives the language links in the parsed wikitext',
783 ' categories - Gives the categories in the parsed wikitext',
784 ' categorieshtml - Gives the HTML version of the categories',
785 ' languageshtml - DEPRECATED. Will be removed in MediaWiki 1.24.',
786 ' Gives the HTML version of the language links',
787 ' links - Gives the internal links in the parsed wikitext',
788 ' templates - Gives the templates in the parsed wikitext',
789 ' images - Gives the images in the parsed wikitext',
790 ' externallinks - Gives the external links in the parsed wikitext',
791 ' sections - Gives the sections in the parsed wikitext',
792 ' revid - Adds the revision ID of the parsed page',
793 ' displaytitle - Adds the title of the parsed wikitext',
794 ' headitems - Gives items to put in the <head> of the page',
795 ' headhtml - Gives parsed <head> of the page',
796 ' modules - Gives the ResourceLoader modules used on the page',
797 ' iwlinks - Gives interwiki links in the parsed wikitext',
798 ' wikitext - Gives the original wikitext that was parsed',
799 ' properties - Gives various properties defined in the parsed wikitext',
800 ' limitreportdata - Gives the limit report in a structured way.',
801 " Gives no data, when {$p}disablepp is set.",
802 ' limitreporthtml - Gives the HTML version of the limit report.',
803 " Gives no data, when {$p}disablepp is set.",
804 ),
805 'effectivelanglinks' => array(
806 'Includes language links supplied by extensions',
807 '(for use with prop=langlinks|languageshtml)',
808 ),
809 'pst' => array(
810 'Do a pre-save transform on the input before parsing it',
811 "Only valid when used with {$p}text",
812 ),
813 'onlypst' => array(
814 'Do a pre-save transform (PST) on the input, but don\'t parse it',
815 'Returns the same wikitext, after a PST has been applied.',
816 "Only valid when used with {$p}text",
817 ),
818 'uselang' => 'Which language to parse the request in',
819 'section' => 'Only retrieve the content of this section number',
820 'disablepp' => 'Disable the PP Report from the parser output',
821 'disableeditsection' => 'Disable edit section links from the parser output',
822 'generatexml' => "Generate XML parse tree (requires contentmodel=$wikitext)",
823 'preview' => 'Parse in preview mode',
824 'sectionpreview' => 'Parse in section preview mode (enables preview mode too)',
825 'disabletoc' => 'Disable table of contents in output',
826 'contentformat' => array(
827 'Content serialization format used for the input text',
828 "Only valid when used with {$p}text",
829 ),
830 'contentmodel' => array(
831 "Content model of the input text. If omitted, ${p}title must be specified, " .
832 "and default will be the model of the specified ${p}title",
833 "Only valid when used with {$p}text",
834 ),
835 );
836 }
837
838 public function getDescription() {
839 $p = $this->getModulePrefix();
840
841 return array(
842 'Parses content and returns parser output.',
843 'See the various prop-Modules of action=query to get information from the current' .
844 'version of a page.',
845 'There are several ways to specify the text to parse:',
846 "1) Specify a page or revision, using {$p}page, {$p}pageid, or {$p}oldid.",
847 "2) Specify content explicitly, using {$p}text, {$p}title, and {$p}contentmodel.",
848 "3) Specify only a summary to parse. {$p}prop should be given an empty value.",
849 );
850 }
851
852 public function getPossibleErrors() {
853 return array_merge( parent::getPossibleErrors(), array(
854 array(
855 'code' => 'params',
856 'info' => 'The page parameter cannot be used together with the text and title parameters'
857 ),
858 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
859 array(
860 'code' => 'permissiondenied',
861 'info' => 'You don\'t have permission to view deleted revisions'
862 ),
863 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
864 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
865 array( 'nosuchpageid' ),
866 array( 'invalidtitle', 'title' ),
867 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
868 array(
869 'code' => 'notwikitext',
870 'info' => 'The requested operation is only supported on wikitext content.'
871 ),
872 ) );
873 }
874
875 public function getExamples() {
876 return array(
877 'api.php?action=parse&page=Project:Sandbox' => 'Parse a page',
878 'api.php?action=parse&text={{Project:Sandbox}}&contentmodel=wikitext' => 'Parse wikitext',
879 'api.php?action=parse&text={{PAGENAME}}&title=Test'
880 => 'Parse wikitext, specifying the page title',
881 'api.php?action=parse&summary=Some+[[link]]&prop=' => 'Parse a summary',
882 );
883 }
884
885 public function getHelpUrls() {
886 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
887 }
888 }