Merge "API: Add show=unread to ApiQueryWatchlist"
[mediawiki.git] / includes / api / ApiParse.php
blobfcba5b5f74d32c597336dbb10f44239ebd90d0fe
1 <?php
2 /**
3 * Created on Dec 01, 2007
5 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
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.
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.
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
22 * @file
25 /**
26 * @ingroup API
28 class ApiParse extends ApiBase {
30 /** @var string $section */
31 private $section = null;
33 /** @var Content $content */
34 private $content = null;
36 /** @var Content $pstContent */
37 private $pstContent = null;
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' );
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;
55 $page = $params['page'];
56 $pageid = $params['pageid'];
57 $oldid = $params['oldid'];
59 $model = $params['contentmodel'];
60 $format = $params['contentformat'];
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'
69 $prop = array_flip( $params['prop'] );
71 if ( isset( $params['section'] ) ) {
72 $this->section = $params['section'];
73 } else {
74 $this->section = false;
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;
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'] ) );
92 $redirValues = null;
94 // Return result
95 $result = $this->getResult();
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' );
104 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
105 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
108 $titleObj = $rev->getTitle();
109 $wgTitle = $titleObj;
110 $pageObj = WikiPage::factory( $titleObj );
111 $popts = $this->makeParserOptions( $pageObj, $params );
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() );
121 if ( $this->section !== false ) {
122 $this->content = $this->getSectionContent( $this->content, 'r' . $rev->getId() );
125 // Should we save old revision parses to the parser cache?
126 $p_result = $this->content->getParserOutput( $titleObj, $rev->getId(), $popts );
128 } else { // Not $oldid, but $pageid or $page
129 if ( $params['redirects'] ) {
130 $reqParams = array(
131 'action' => 'query',
132 'redirects' => '',
134 if ( !is_null( $pageid ) ) {
135 $reqParams['pageids'] = $pageid;
136 } else { // $page
137 $reqParams['titles'] = $page;
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'];
150 $pageParams = array( 'title' => $to );
151 } elseif ( !is_null( $pageid ) ) {
152 $pageParams = array( 'pageid' => $pageid );
153 } else { // $page
154 $pageParams = array( 'title' => $page );
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' );
162 $wgTitle = $titleObj;
164 if ( isset( $prop['revid'] ) ) {
165 $oldid = $pageObj->getLatest();
168 $popts = $this->makeParserOptions( $pageObj, $params );
170 // Potentially cached
171 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
172 isset( $prop['wikitext'] ) );
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 ) );
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();
188 $popts = $this->makeParserOptions( $pageObj, $params );
189 $textProvided = !is_null( $text );
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'?)"
198 // Prevent warning from ContentHandler::makeContent()
199 $text = '';
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." );
209 try {
210 $this->content = ContentHandler::makeContent( $text, $titleObj, $model, $format );
211 } catch ( MWContentSerializationException $ex ) {
212 $this->dieUsage( $ex->getMessage(), 'parseerror' );
215 if ( $this->section !== false ) {
216 $this->content = $this->getSectionContent( $this->content, $titleObj->getText() );
219 if ( $params['pst'] || $params['onlypst'] ) {
220 $this->pstContent = $this->content->preSaveTransform( $titleObj, $this->getUser(), $popts );
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 ) );
231 $result->addValue( null, $this->getModuleName(), $result_array );
233 return;
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 );
244 $result_array = array();
246 $result_array['title'] = $titleObj->getPrefixedText();
248 if ( !is_null( $oldid ) ) {
249 $result_array['revid'] = intval( $oldid );
252 if ( $params['redirects'] && !is_null( $redirValues ) ) {
253 $result_array['redirects'] = $redirValues;
256 if ( $params['disabletoc'] ) {
257 $p_result->setTOCEnabled( false );
260 if ( isset( $prop['text'] ) ) {
261 $result_array['text'] = array();
262 ApiResult::setContent( $result_array['text'], $p_result->getText() );
265 if ( !is_null( $params['summary'] ) ) {
266 $result_array['parsedsummary'] = array();
267 ApiResult::setContent(
268 $result_array['parsedsummary'],
269 Linker::formatComment( $params['summary'], $titleObj )
273 if ( isset( $prop['langlinks'] ) || isset( $prop['languageshtml'] ) ) {
274 $langlinks = $p_result->getLanguageLinks();
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 ) );
282 } else {
283 $langlinks = false;
286 if ( isset( $prop['langlinks'] ) ) {
287 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
289 if ( isset( $prop['languageshtml'] ) ) {
290 $languagesHtml = $this->languagesHtml( $langlinks );
292 $result_array['languageshtml'] = array();
293 ApiResult::setContent( $result_array['languageshtml'], $languagesHtml );
295 if ( isset( $prop['categories'] ) ) {
296 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
298 if ( isset( $prop['categorieshtml'] ) ) {
299 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
300 $result_array['categorieshtml'] = array();
301 ApiResult::setContent( $result_array['categorieshtml'], $categoriesHtml );
303 if ( isset( $prop['links'] ) ) {
304 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
306 if ( isset( $prop['templates'] ) ) {
307 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
309 if ( isset( $prop['images'] ) ) {
310 $result_array['images'] = array_keys( $p_result->getImages() );
312 if ( isset( $prop['externallinks'] ) ) {
313 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
315 if ( isset( $prop['sections'] ) ) {
316 $result_array['sections'] = $p_result->getSections();
319 if ( isset( $prop['displaytitle'] ) ) {
320 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
321 $p_result->getDisplayTitle() :
322 $titleObj->getPrefixedText();
325 if ( isset( $prop['headitems'] ) || isset( $prop['headhtml'] ) ) {
326 $context = $this->getContext();
327 $context->setTitle( $titleObj );
328 $context->getOutput()->addParserOutputNoText( $p_result );
330 if ( isset( $prop['headitems'] ) ) {
331 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
333 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
335 $scripts = array( $context->getOutput()->getHeadScripts() );
337 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
340 if ( isset( $prop['headhtml'] ) ) {
341 $result_array['headhtml'] = array();
342 ApiResult::setContent(
343 $result_array['headhtml'],
344 $context->getOutput()->headElement( $context->getSkin() )
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() ) );
356 if ( isset( $prop['iwlinks'] ) ) {
357 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
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 ) );
368 if ( isset( $prop['properties'] ) ) {
369 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
372 if ( isset( $prop['limitreportdata'] ) ) {
373 $result_array['limitreportdata'] =
374 $this->formatLimitReportData( $p_result->getLimitReportData() );
376 if ( isset( $prop['limitreporthtml'] ) ) {
377 $limitreportHtml = EditPage::getPreviewLimitReport( $p_result );
378 $result_array['limitreporthtml'] = array();
379 ApiResult::setContent( $result_array['limitreporthtml'], $limitreportHtml );
382 if ( $params['generatexml'] ) {
383 if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
384 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
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();
394 $result_array['parsetree'] = array();
395 ApiResult::setContent( $result_array['parsetree'], $xml );
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',
416 $this->setIndexedTagNames( $result_array, $result_mapping );
417 $result->addValue( null, $this->getModuleName(), $result_array );
419 if ( !is_null( $oldLang ) ) {
420 $this->getContext()->setLanguage( $oldLang ); // Reset language to $oldLang
425 * Constructs a ParserOptions object
427 * @param WikiPage $pageObj
428 * @param array $params
430 * @return ParserOptions
432 protected function makeParserOptions( WikiPage $pageObj, array $params ) {
433 wfProfileIn( __METHOD__ );
435 $popts = $pageObj->makeParserOptions( $this->getContext() );
436 $popts->enableLimitReport( !$params['disablepp'] );
437 $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
438 $popts->setIsSectionPreview( $params['sectionpreview'] );
440 wfProfileOut( __METHOD__ );
442 return $popts;
446 * @param WikiPage $page
447 * @param ParserOptions $popts
448 * @param int $pageId
449 * @param bool $getWikitext
450 * @return ParserOutput
452 private function getParsedContent( WikiPage $page, $popts, $pageId = null, $getWikitext = false ) {
453 $this->content = $page->getContent( Revision::RAW ); //XXX: really raw?
455 if ( $this->section !== false && $this->content !== null ) {
456 $this->content = $this->getSectionContent(
457 $this->content,
458 !is_null( $pageId ) ? 'page id ' . $pageId : $page->getTitle()->getText()
461 // Not cached (save or load)
462 return $this->content->getParserOutput( $page->getTitle(), null, $popts );
465 // Try the parser cache first
466 // getParserOutput will save to Parser cache if able
467 $pout = $page->getParserOutput( $popts );
468 if ( !$pout ) {
469 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
471 if ( $getWikitext ) {
472 $this->content = $page->getContent( Revision::RAW );
475 return $pout;
478 private function getSectionContent( Content $content, $what ) {
479 // Not cached (save or load)
480 $section = $content->getSection( $this->section );
481 if ( $section === false ) {
482 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
484 if ( $section === null ) {
485 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
486 $section = false;
489 return $section;
492 private function formatLangLinks( $links ) {
493 $result = array();
494 foreach ( $links as $link ) {
495 $entry = array();
496 $bits = explode( ':', $link, 2 );
497 $title = Title::newFromText( $link );
499 $entry['lang'] = $bits[0];
500 if ( $title ) {
501 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
502 // localised language name in user language (maybe set by uselang=)
503 $entry['langname'] = Language::fetchLanguageName(
504 $title->getInterwiki(),
505 $this->getLanguage()->getCode()
508 // native language name
509 $entry['autonym'] = Language::fetchLanguageName( $title->getInterwiki() );
511 ApiResult::setContent( $entry, $bits[1] );
512 $result[] = $entry;
515 return $result;
518 private function formatCategoryLinks( $links ) {
519 $result = array();
521 if ( !$links ) {
522 return $result;
525 // Fetch hiddencat property
526 $lb = new LinkBatch;
527 $lb->setArray( array( NS_CATEGORY => $links ) );
528 $db = $this->getDB();
529 $res = $db->select( array( 'page', 'page_props' ),
530 array( 'page_title', 'pp_propname' ),
531 $lb->constructSet( 'page', $db ),
532 __METHOD__,
533 array(),
534 array( 'page_props' => array(
535 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' )
538 $hiddencats = array();
539 foreach ( $res as $row ) {
540 $hiddencats[$row->page_title] = isset( $row->pp_propname );
543 foreach ( $links as $link => $sortkey ) {
544 $entry = array();
545 $entry['sortkey'] = $sortkey;
546 ApiResult::setContent( $entry, $link );
547 if ( !isset( $hiddencats[$link] ) ) {
548 $entry['missing'] = '';
549 } elseif ( $hiddencats[$link] ) {
550 $entry['hidden'] = '';
552 $result[] = $entry;
555 return $result;
558 private function categoriesHtml( $categories ) {
559 $context = $this->getContext();
560 $context->getOutput()->addCategoryLinks( $categories );
562 return $context->getSkin()->getCategories();
566 * @deprecated since 1.18 No modern skin generates language links this way,
567 * please use language links data to generate your own HTML.
568 * @param array $languages
569 * @return string
571 private function languagesHtml( $languages ) {
572 wfDeprecated( __METHOD__, '1.18' );
573 $this->setWarning( '"action=parse&prop=languageshtml" is deprecated ' .
574 'and will be removed in MediaWiki 1.24. Use "prop=langlinks" ' .
575 'to generate your own HTML.' );
577 global $wgContLang, $wgHideInterlanguageLinks;
579 if ( $wgHideInterlanguageLinks || count( $languages ) == 0 ) {
580 return '';
583 $s = htmlspecialchars( wfMessage( 'otherlanguages' )->text() .
584 wfMessage( 'colon-separator' )->text() );
586 $langs = array();
587 foreach ( $languages as $l ) {
588 $nt = Title::newFromText( $l );
589 $text = Language::fetchLanguageName( $nt->getInterwiki() );
591 $langs[] = Html::element( 'a',
592 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => 'external' ),
593 $text == '' ? $l : $text );
596 $s .= implode( wfMessage( 'pipe-separator' )->escaped(), $langs );
598 if ( $wgContLang->isRTL() ) {
599 $s = Html::rawElement( 'span', array( 'dir' => 'LTR' ), $s );
602 return $s;
605 private function formatLinks( $links ) {
606 $result = array();
607 foreach ( $links as $ns => $nslinks ) {
608 foreach ( $nslinks as $title => $id ) {
609 $entry = array();
610 $entry['ns'] = $ns;
611 ApiResult::setContent( $entry, Title::makeTitle( $ns, $title )->getFullText() );
612 if ( $id != 0 ) {
613 $entry['exists'] = '';
615 $result[] = $entry;
619 return $result;
622 private function formatIWLinks( $iw ) {
623 $result = array();
624 foreach ( $iw as $prefix => $titles ) {
625 foreach ( array_keys( $titles ) as $title ) {
626 $entry = array();
627 $entry['prefix'] = $prefix;
629 $title = Title::newFromText( "{$prefix}:{$title}" );
630 if ( $title ) {
631 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
634 ApiResult::setContent( $entry, $title->getFullText() );
635 $result[] = $entry;
639 return $result;
642 private function formatHeadItems( $headItems ) {
643 $result = array();
644 foreach ( $headItems as $tag => $content ) {
645 $entry = array();
646 $entry['tag'] = $tag;
647 ApiResult::setContent( $entry, $content );
648 $result[] = $entry;
651 return $result;
654 private function formatProperties( $properties ) {
655 $result = array();
656 foreach ( $properties as $name => $value ) {
657 $entry = array();
658 $entry['name'] = $name;
659 ApiResult::setContent( $entry, $value );
660 $result[] = $entry;
663 return $result;
666 private function formatCss( $css ) {
667 $result = array();
668 foreach ( $css as $file => $link ) {
669 $entry = array();
670 $entry['file'] = $file;
671 ApiResult::setContent( $entry, $link );
672 $result[] = $entry;
675 return $result;
678 private function formatLimitReportData( $limitReportData ) {
679 $result = array();
680 $apiResult = $this->getResult();
682 foreach ( $limitReportData as $name => $value ) {
683 $entry = array();
684 $entry['name'] = $name;
685 if ( !is_array( $value ) ) {
686 $value = array( $value );
688 $apiResult->setIndexedTagName( $value, 'param' );
689 $apiResult->setIndexedTagName_recursive( $value, 'param' );
690 $entry = array_merge( $entry, $value );
691 $result[] = $entry;
694 return $result;
697 private function setIndexedTagNames( &$array, $mapping ) {
698 foreach ( $mapping as $key => $name ) {
699 if ( isset( $array[$key] ) ) {
700 $this->getResult()->setIndexedTagName( $array[$key], $name );
705 public function getAllowedParams() {
706 return array(
707 'title' => null,
708 'text' => null,
709 'summary' => null,
710 'page' => null,
711 'pageid' => array(
712 ApiBase::PARAM_TYPE => 'integer',
714 'redirects' => false,
715 'oldid' => array(
716 ApiBase::PARAM_TYPE => 'integer',
718 'prop' => array(
719 ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|' .
720 'images|externallinks|sections|revid|displaytitle|iwlinks|properties',
721 ApiBase::PARAM_ISMULTI => true,
722 ApiBase::PARAM_TYPE => array(
723 'text',
724 'langlinks',
725 'languageshtml',
726 'categories',
727 'categorieshtml',
728 'links',
729 'templates',
730 'images',
731 'externallinks',
732 'sections',
733 'revid',
734 'displaytitle',
735 'headitems',
736 'headhtml',
737 'modules',
738 'iwlinks',
739 'wikitext',
740 'properties',
741 'limitreportdata',
742 'limitreporthtml',
745 'pst' => false,
746 'onlypst' => false,
747 'effectivelanglinks' => false,
748 'uselang' => null,
749 'section' => null,
750 'disablepp' => false,
751 'generatexml' => false,
752 'preview' => false,
753 'sectionpreview' => false,
754 'disabletoc' => false,
755 'contentformat' => array(
756 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
758 'contentmodel' => array(
759 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
764 public function getParamDescription() {
765 $p = $this->getModulePrefix();
766 $wikitext = CONTENT_MODEL_WIKITEXT;
768 return array(
769 'text' => "Text to parse. Use {$p}title or {$p}contentmodel to control the content model",
770 'summary' => 'Summary to parse',
771 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
772 'title' => "Title of page the text belongs to. " .
773 "If omitted, {$p}contentmodel must be specified, and \"API\" will be used as the title",
774 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
775 'pageid' => "Parse the content of this page. Overrides {$p}page",
776 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
777 'prop' => array(
778 'Which pieces of information to get',
779 ' text - Gives the parsed text of the wikitext',
780 ' langlinks - Gives the language links in the parsed wikitext',
781 ' categories - Gives the categories in the parsed wikitext',
782 ' categorieshtml - Gives the HTML version of the categories',
783 ' languageshtml - DEPRECATED. Will be removed in MediaWiki 1.24.',
784 ' Gives the HTML version of the language links',
785 ' links - Gives the internal links in the parsed wikitext',
786 ' templates - Gives the templates in the parsed wikitext',
787 ' images - Gives the images in the parsed wikitext',
788 ' externallinks - Gives the external links in the parsed wikitext',
789 ' sections - Gives the sections in the parsed wikitext',
790 ' revid - Adds the revision ID of the parsed page',
791 ' displaytitle - Adds the title of the parsed wikitext',
792 ' headitems - Gives items to put in the <head> of the page',
793 ' headhtml - Gives parsed <head> of the page',
794 ' modules - Gives the ResourceLoader modules used on the page',
795 ' iwlinks - Gives interwiki links in the parsed wikitext',
796 ' wikitext - Gives the original wikitext that was parsed',
797 ' properties - Gives various properties defined in the parsed wikitext',
798 ' limitreportdata - Gives the limit report in a structured way.',
799 " Gives no data, when {$p}disablepp is set.",
800 ' limitreporthtml - Gives the HTML version of the limit report.',
801 " Gives no data, when {$p}disablepp is set.",
803 'effectivelanglinks' => array(
804 'Includes language links supplied by extensions',
805 '(for use with prop=langlinks|languageshtml)',
807 'pst' => array(
808 'Do a pre-save transform on the input before parsing it',
809 "Only valid when used with {$p}text",
811 'onlypst' => array(
812 'Do a pre-save transform (PST) on the input, but don\'t parse it',
813 'Returns the same wikitext, after a PST has been applied.',
814 "Only valid when used with {$p}text",
816 'uselang' => 'Which language to parse the request in',
817 'section' => 'Only retrieve the content of this section number',
818 'disablepp' => 'Disable the PP Report from the parser output',
819 'generatexml' => "Generate XML parse tree (requires contentmodel=$wikitext)",
820 'preview' => 'Parse in preview mode',
821 'sectionpreview' => 'Parse in section preview mode (enables preview mode too)',
822 'disabletoc' => 'Disable table of contents in output',
823 'contentformat' => array(
824 'Content serialization format used for the input text',
825 "Only valid when used with {$p}text",
827 'contentmodel' => array(
828 "Content model of the input text. If omitted, ${p}title must be specified, " .
829 "and default will be the model of the specified ${p}title",
830 "Only valid when used with {$p}text",
835 public function getDescription() {
836 $p = $this->getModulePrefix();
838 return array(
839 'Parses content and returns parser output.',
840 'See the various prop-Modules of action=query to get information from the current' .
841 'version of a page.',
842 'There are several ways to specify the text to parse:',
843 "1) Specify a page or revision, using {$p}page, {$p}pageid, or {$p}oldid.",
844 "2) Specify content explicitly, using {$p}text, {$p}title, and {$p}contentmodel.",
845 "3) Specify only a summary to parse. {$p}prop should be given an empty value.",
849 public function getPossibleErrors() {
850 return array_merge( parent::getPossibleErrors(), array(
851 array(
852 'code' => 'params',
853 'info' => 'The page parameter cannot be used together with the text and title parameters'
855 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
856 array(
857 'code' => 'permissiondenied',
858 'info' => 'You don\'t have permission to view deleted revisions'
860 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
861 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
862 array( 'nosuchpageid' ),
863 array( 'invalidtitle', 'title' ),
864 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
865 array(
866 'code' => 'notwikitext',
867 'info' => 'The requested operation is only supported on wikitext content.'
869 ) );
872 public function getExamples() {
873 return array(
874 'api.php?action=parse&page=Project:Sandbox' => 'Parse a page',
875 'api.php?action=parse&text={{Project:Sandbox}}&contentmodel=wikitext' => 'Parse wikitext',
876 'api.php?action=parse&text={{PAGENAME}}&title=Test'
877 => 'Parse wikitext, specifying the page title',
878 'api.php?action=parse&summary=Some+[[link]]&prop=' => 'Parse a summary',
882 public function getHelpUrls() {
883 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';