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
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' );
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
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( 'The page parameter cannot be used together with the text and title parameters', 'params' );
66 $prop = array_flip( $params['prop'] );
68 if ( isset( $params['section'] ) ) {
69 $this->section
= $params['section'];
71 $this->section
= false;
74 // The parser needs $wgTitle to be set, apparently the
75 // $title parameter in Parser::parse isn't enough *sigh*
76 // TODO: Does this still need $wgTitle?
77 global $wgParser, $wgTitle;
79 // Currently unnecessary, code to act as a safeguard against any change in current behavior of uselang
81 if ( isset( $params['uselang'] ) && $params['uselang'] != $this->getContext()->getLanguage()->getCode() ) {
82 $oldLang = $this->getContext()->getLanguage(); // Backup language
83 $this->getContext()->setLanguage( Language
::factory( $params['uselang'] ) );
89 $result = $this->getResult();
91 if ( !is_null( $oldid ) ||
!is_null( $pageid ) ||
!is_null( $page ) ) {
92 if ( !is_null( $oldid ) ) {
93 // Don't use the parser cache
94 $rev = Revision
::newFromID( $oldid );
96 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
98 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
99 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
102 $titleObj = $rev->getTitle();
103 $wgTitle = $titleObj;
104 $pageObj = WikiPage
::factory( $titleObj );
105 $popts = $this->makeParserOptions( $pageObj, $params );
107 // If for some reason the "oldid" is actually the current revision, it may be cached
108 if ( $rev->isCurrent() ) {
109 // May get from/save to parser cache
110 $p_result = $this->getParsedContent( $pageObj, $popts,
111 $pageid, isset( $prop['wikitext'] ) );
112 } else { // This is an old revision, so get the text differently
113 $this->content
= $rev->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
115 if ( $this->section
!== false ) {
116 $this->content
= $this->getSectionContent( $this->content
, 'r' . $rev->getId() );
119 // Should we save old revision parses to the parser cache?
120 $p_result = $this->content
->getParserOutput( $titleObj, $rev->getId(), $popts );
122 } else { // Not $oldid, but $pageid or $page
123 if ( $params['redirects'] ) {
128 if ( !is_null ( $pageid ) ) {
129 $reqParams['pageids'] = $pageid;
131 $reqParams['titles'] = $page;
133 $req = new FauxRequest( $reqParams );
134 $main = new ApiMain( $req );
136 $data = $main->getResultData();
137 $redirValues = isset( $data['query']['redirects'] )
138 ?
$data['query']['redirects']
141 foreach ( (array)$redirValues as $r ) {
144 $pageParams = array( 'title' => $to );
145 } elseif ( !is_null( $pageid ) ) {
146 $pageParams = array( 'pageid' => $pageid );
148 $pageParams = array( 'title' => $page );
151 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
152 $titleObj = $pageObj->getTitle();
153 if ( !$titleObj ||
!$titleObj->exists() ) {
154 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
156 $wgTitle = $titleObj;
158 if ( isset( $prop['revid'] ) ) {
159 $oldid = $pageObj->getLatest();
162 $popts = $this->makeParserOptions( $pageObj, $params );
164 // Potentially cached
165 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
166 isset( $prop['wikitext'] ) );
168 } else { // Not $oldid, $pageid, $page. Hence based on $text
169 $titleObj = Title
::newFromText( $title );
170 if ( !$titleObj ||
$titleObj->isExternal() ) {
171 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
173 if ( !$titleObj->canExist() ) {
174 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
176 $wgTitle = $titleObj;
177 $pageObj = WikiPage
::factory( $titleObj );
179 $popts = $this->makeParserOptions( $pageObj, $params );
181 if ( is_null( $text ) ) {
182 if ( $titleProvided && ( $prop ||
$params['generatexml'] ) ) {
184 "'title' used without 'text', and parsed page properties were requested " .
185 "(did you mean to use 'page' instead of 'title'?)"
188 // Prevent warning from ContentHandler::makeContent()
192 // If we are parsing text, do not use the content model of the default
193 // API title, but default to wikitext to keep BC.
194 if ( !$titleProvided && is_null( $model ) ) {
195 $model = CONTENT_MODEL_WIKITEXT
;
196 $this->setWarning( "No 'title' or 'contentmodel' was given, assuming $model." );
200 $this->content
= ContentHandler
::makeContent( $text, $titleObj, $model, $format );
201 } catch ( MWContentSerializationException
$ex ) {
202 $this->dieUsage( $ex->getMessage(), 'parseerror' );
205 if ( $this->section
!== false ) {
206 $this->content
= $this->getSectionContent( $this->content
, $titleObj->getText() );
209 if ( $params['pst'] ||
$params['onlypst'] ) {
210 $this->pstContent
= $this->content
->preSaveTransform( $titleObj, $this->getUser(), $popts );
212 if ( $params['onlypst'] ) {
213 // Build a result and bail out
214 $result_array = array();
215 $result_array['text'] = array();
216 ApiResult
::setContent( $result_array['text'], $this->pstContent
->serialize( $format ) );
217 if ( isset( $prop['wikitext'] ) ) {
218 $result_array['wikitext'] = array();
219 ApiResult
::setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
221 $result->addValue( null, $this->getModuleName(), $result_array );
225 // Not cached (save or load)
226 if ( $params['pst'] ) {
227 $p_result = $this->pstContent
->getParserOutput( $titleObj, null, $popts );
229 $p_result = $this->content
->getParserOutput( $titleObj, null, $popts );
233 $result_array = array();
235 $result_array['title'] = $titleObj->getPrefixedText();
237 if ( !is_null( $oldid ) ) {
238 $result_array['revid'] = intval( $oldid );
241 if ( $params['redirects'] && !is_null( $redirValues ) ) {
242 $result_array['redirects'] = $redirValues;
245 if ( isset( $prop['text'] ) ) {
246 $result_array['text'] = array();
247 ApiResult
::setContent( $result_array['text'], $p_result->getText() );
250 if ( !is_null( $params['summary'] ) ) {
251 $result_array['parsedsummary'] = array();
252 ApiResult
::setContent( $result_array['parsedsummary'], Linker
::formatComment( $params['summary'], $titleObj ) );
255 if ( isset( $prop['langlinks'] ) ||
isset( $prop['languageshtml'] ) ) {
256 $langlinks = $p_result->getLanguageLinks();
258 if ( $params['effectivelanglinks'] ) {
259 // Link flags are ignored for now, but may in the future be
260 // included in the result.
261 $linkFlags = array();
262 wfRunHooks( 'LanguageLinks', array( $titleObj, &$langlinks, &$linkFlags ) );
268 if ( isset( $prop['langlinks'] ) ) {
269 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
271 if ( isset( $prop['languageshtml'] ) ) {
272 $languagesHtml = $this->languagesHtml( $langlinks );
274 $result_array['languageshtml'] = array();
275 ApiResult
::setContent( $result_array['languageshtml'], $languagesHtml );
277 if ( isset( $prop['categories'] ) ) {
278 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
280 if ( isset( $prop['categorieshtml'] ) ) {
281 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
282 $result_array['categorieshtml'] = array();
283 ApiResult
::setContent( $result_array['categorieshtml'], $categoriesHtml );
285 if ( isset( $prop['links'] ) ) {
286 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
288 if ( isset( $prop['templates'] ) ) {
289 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
291 if ( isset( $prop['images'] ) ) {
292 $result_array['images'] = array_keys( $p_result->getImages() );
294 if ( isset( $prop['externallinks'] ) ) {
295 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
297 if ( isset( $prop['sections'] ) ) {
298 $result_array['sections'] = $p_result->getSections();
301 if ( isset( $prop['displaytitle'] ) ) {
302 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
303 $p_result->getDisplayTitle() :
304 $titleObj->getPrefixedText();
307 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
308 $context = $this->getContext();
309 $context->setTitle( $titleObj );
310 $context->getOutput()->addParserOutputNoText( $p_result );
312 if ( isset( $prop['headitems'] ) ) {
313 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
315 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
317 $scripts = array( $context->getOutput()->getHeadScripts() );
319 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
322 if ( isset( $prop['headhtml'] ) ) {
323 $result_array['headhtml'] = array();
324 ApiResult
::setContent( $result_array['headhtml'], $context->getOutput()->headElement( $context->getSkin() ) );
328 if ( isset( $prop['iwlinks'] ) ) {
329 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
332 if ( isset( $prop['wikitext'] ) ) {
333 $result_array['wikitext'] = array();
334 ApiResult
::setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
335 if ( !is_null( $this->pstContent
) ) {
336 $result_array['psttext'] = array();
337 ApiResult
::setContent( $result_array['psttext'], $this->pstContent
->serialize( $format ) );
340 if ( isset( $prop['properties'] ) ) {
341 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
344 if ( $params['generatexml'] ) {
345 if ( $this->content
->getModel() != CONTENT_MODEL_WIKITEXT
) {
346 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
349 $wgParser->startExternalParse( $titleObj, $popts, OT_PREPROCESS
);
350 $dom = $wgParser->preprocessToDom( $this->content
->getNativeData() );
351 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
352 $xml = $dom->saveXML();
354 $xml = $dom->__toString();
356 $result_array['parsetree'] = array();
357 ApiResult
::setContent( $result_array['parsetree'], $xml );
360 $result_mapping = array(
363 'categories' => 'cl',
367 'externallinks' => 'el',
371 'properties' => 'pp',
373 $this->setIndexedTagNames( $result_array, $result_mapping );
374 $result->addValue( null, $this->getModuleName(), $result_array );
376 if ( !is_null( $oldLang ) ) {
377 $this->getContext()->setLanguage( $oldLang ); // Reset language to $oldLang
382 * Constructs a ParserOptions object
384 * @param WikiPage $pageObj
385 * @param array $params
387 * @return ParserOptions
389 protected function makeParserOptions( WikiPage
$pageObj, array $params ) {
390 wfProfileIn( __METHOD__
);
392 $popts = $pageObj->makeParserOptions( $this->getContext() );
393 $popts->enableLimitReport( !$params['disablepp'] );
394 $popts->setIsPreview( $params['preview'] ||
$params['sectionpreview'] );
395 $popts->setIsSectionPreview( $params['sectionpreview'] );
397 wfProfileOut( __METHOD__
);
402 * @param $page WikiPage
403 * @param $popts ParserOptions
405 * @param $getWikitext Bool
406 * @return ParserOutput
408 private function getParsedContent( WikiPage
$page, $popts, $pageId = null, $getWikitext = false ) {
409 $this->content
= $page->getContent( Revision
::RAW
); //XXX: really raw?
411 if ( $this->section
!== false && $this->content
!== null ) {
412 $this->content
= $this->getSectionContent(
414 !is_null( $pageId ) ?
'page id ' . $pageId : $page->getTitle()->getText() );
416 // Not cached (save or load)
417 return $this->content
->getParserOutput( $page->getTitle(), null, $popts );
419 // Try the parser cache first
420 // getParserOutput will save to Parser cache if able
421 $pout = $page->getParserOutput( $popts );
423 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
425 if ( $getWikitext ) {
426 $this->content
= $page->getContent( Revision
::RAW
);
432 private function getSectionContent( Content
$content, $what ) {
433 // Not cached (save or load)
434 $section = $content->getSection( $this->section
);
435 if ( $section === false ) {
436 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
438 if ( $section === null ) {
439 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
445 private function formatLangLinks( $links ) {
447 foreach ( $links as $link ) {
449 $bits = explode( ':', $link, 2 );
450 $title = Title
::newFromText( $link );
452 $entry['lang'] = $bits[0];
454 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
456 ApiResult
::setContent( $entry, $bits[1] );
462 private function formatCategoryLinks( $links ) {
464 foreach ( $links as $link => $sortkey ) {
466 $entry['sortkey'] = $sortkey;
467 ApiResult
::setContent( $entry, $link );
473 private function categoriesHtml( $categories ) {
474 $context = $this->getContext();
475 $context->getOutput()->addCategoryLinks( $categories );
476 return $context->getSkin()->getCategories();
480 * @deprecated since 1.18 No modern skin generates language links this way, please use language links
481 * data to generate your own HTML.
482 * @param $languages array
485 private function languagesHtml( $languages ) {
486 wfDeprecated( __METHOD__
, '1.18' );
488 global $wgContLang, $wgHideInterlanguageLinks;
490 if ( $wgHideInterlanguageLinks ||
count( $languages ) == 0 ) {
494 $s = htmlspecialchars( wfMessage( 'otherlanguages' )->text() . wfMessage( 'colon-separator' )->text() );
497 foreach ( $languages as $l ) {
498 $nt = Title
::newFromText( $l );
499 $text = Language
::fetchLanguageName( $nt->getInterwiki() );
501 $langs[] = Html
::element( 'a',
502 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => 'external' ),
503 $text == '' ?
$l : $text );
506 $s .= implode( wfMessage( 'pipe-separator' )->escaped(), $langs );
508 if ( $wgContLang->isRTL() ) {
509 $s = Html
::rawElement( 'span', array( 'dir' => 'LTR' ), $s );
515 private function formatLinks( $links ) {
517 foreach ( $links as $ns => $nslinks ) {
518 foreach ( $nslinks as $title => $id ) {
521 ApiResult
::setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
523 $entry['exists'] = '';
531 private function formatIWLinks( $iw ) {
533 foreach ( $iw as $prefix => $titles ) {
534 foreach ( array_keys( $titles ) as $title ) {
536 $entry['prefix'] = $prefix;
538 $title = Title
::newFromText( "{$prefix}:{$title}" );
540 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
543 ApiResult
::setContent( $entry, $title->getFullText() );
550 private function formatHeadItems( $headItems ) {
552 foreach ( $headItems as $tag => $content ) {
554 $entry['tag'] = $tag;
555 ApiResult
::setContent( $entry, $content );
561 private function formatProperties( $properties ) {
563 foreach ( $properties as $name => $value ) {
565 $entry['name'] = $name;
566 ApiResult
::setContent( $entry, $value );
572 private function formatCss( $css ) {
574 foreach ( $css as $file => $link ) {
576 $entry['file'] = $file;
577 ApiResult
::setContent( $entry, $link );
583 private function setIndexedTagNames( &$array, $mapping ) {
584 foreach ( $mapping as $key => $name ) {
585 if ( isset( $array[$key] ) ) {
586 $this->getResult()->setIndexedTagName( $array[$key], $name );
591 public function getAllowedParams() {
598 ApiBase
::PARAM_TYPE
=> 'integer',
600 'redirects' => false,
602 ApiBase
::PARAM_TYPE
=> 'integer',
605 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle|iwlinks|properties',
606 ApiBase
::PARAM_ISMULTI
=> true,
607 ApiBase
::PARAM_TYPE
=> array(
629 'effectivelanglinks' => false,
632 'disablepp' => false,
633 'generatexml' => false,
635 'sectionpreview' => false,
636 'contentformat' => array(
637 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
639 'contentmodel' => array(
640 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
645 public function getParamDescription() {
646 $p = $this->getModulePrefix();
647 $wikitext = CONTENT_MODEL_WIKITEXT
;
649 'text' => "Text to parse. Use {$p}title or {$p}contentmodel to control the content model",
650 'summary' => 'Summary to parse',
651 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
652 'title' => "Title of page the text belongs to. " .
653 "If omitted, \"API\" is used as the title with content model $wikitext",
654 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
655 'pageid' => "Parse the content of this page. Overrides {$p}page",
656 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
658 'Which pieces of information to get',
659 ' text - Gives the parsed text of the wikitext',
660 ' langlinks - Gives the language links in the parsed wikitext',
661 ' categories - Gives the categories in the parsed wikitext',
662 ' categorieshtml - Gives the HTML version of the categories',
663 ' languageshtml - Gives the HTML version of the language links',
664 ' links - Gives the internal links in the parsed wikitext',
665 ' templates - Gives the templates in the parsed wikitext',
666 ' images - Gives the images in the parsed wikitext',
667 ' externallinks - Gives the external links in the parsed wikitext',
668 ' sections - Gives the sections in the parsed wikitext',
669 ' revid - Adds the revision ID of the parsed page',
670 ' displaytitle - Adds the title of the parsed wikitext',
671 ' headitems - Gives items to put in the <head> of the page',
672 ' headhtml - Gives parsed <head> of the page',
673 ' iwlinks - Gives interwiki links in the parsed wikitext',
674 ' wikitext - Gives the original wikitext that was parsed',
675 ' properties - Gives various properties defined in the parsed wikitext',
677 'effectivelanglinks' => array(
678 'Includes language links supplied by extensions',
679 '(for use with prop=langlinks|languageshtml)',
682 'Do a pre-save transform on the input before parsing it',
683 "Only valid when used with {$p}text",
686 'Do a pre-save transform (PST) on the input, but don\'t parse it',
687 'Returns the same wikitext, after a PST has been applied.',
688 "Only valid when used with {$p}text",
690 'uselang' => 'Which language to parse the request in',
691 'section' => 'Only retrieve the content of this section number',
692 'disablepp' => 'Disable the PP Report from the parser output',
693 'generatexml' => "Generate XML parse tree (requires contentmodel=$wikitext)",
694 'preview' => 'Parse in preview mode',
695 'sectionpreview' => 'Parse in section preview mode (enables preview mode too)',
696 'contentformat' => array(
697 'Content serialization format used for the input text',
698 "Only valid when used with {$p}text",
700 'contentmodel' => array(
701 "Content model of the input text. Default is the model of the " .
702 "specified ${p}title, or $wikitext if ${p}title is not specified",
703 "Only valid when used with {$p}text",
708 public function getDescription() {
709 $p = $this->getModulePrefix();
711 'Parses content and returns parser output',
712 'See the various prop-Modules of action=query to get information from the current version of a page',
713 'There are several ways to specify the text to parse:',
714 "1) Specify a page or revision, using {$p}page, {$p}pageid, or {$p}oldid.",
715 "2) Specify content explicitly, using {$p}text, {$p}title, and {$p}contentmodel.",
716 "3) Specify only a summary to parse. {$p}prop should be given an empty value.",
720 public function getPossibleErrors() {
721 return array_merge( parent
::getPossibleErrors(), array(
722 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
723 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
724 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
725 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
726 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
727 array( 'nosuchpageid' ),
728 array( 'invalidtitle', 'title' ),
729 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
730 array( 'code' => 'notwikitext', 'info' => 'The requested operation is only supported on wikitext content.' ),
731 array( 'code' => 'pagecannotexist', 'info' => "Namespace doesn't allow actual pages" ),
735 public function getExamples() {
737 'api.php?action=parse&page=Project:Sandbox' => 'Parse a page',
738 'api.php?action=parse&text={{Project:Sandbox}}' => 'Parse wikitext',
739 'api.php?action=parse&text={{PAGENAME}}&title=Test' => 'Parse wikitext, specifying the page title',
740 'api.php?action=parse&summary=Some+[[link]]&prop=' => 'Parse a summary',
744 public function getHelpUrls() {
745 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';