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 $page = $params['page'];
48 $pageid = $params['pageid'];
49 $oldid = $params['oldid'];
51 $model = $params['contentmodel'];
52 $format = $params['contentformat'];
54 if ( !is_null( $page ) && ( !is_null( $text ) ||
$title != 'API' ) ) {
55 $this->dieUsage( 'The page parameter cannot be used together with the text and title parameters', 'params' );
58 $prop = array_flip( $params['prop'] );
60 if ( isset( $params['section'] ) ) {
61 $this->section
= $params['section'];
63 $this->section
= false;
66 // The parser needs $wgTitle to be set, apparently the
67 // $title parameter in Parser::parse isn't enough *sigh*
68 // TODO: Does this still need $wgTitle?
69 global $wgParser, $wgTitle;
71 // Currently unnecessary, code to act as a safeguard against any change in current behavior of uselang
73 if ( isset( $params['uselang'] ) && $params['uselang'] != $this->getContext()->getLanguage()->getCode() ) {
74 $oldLang = $this->getContext()->getLanguage(); // Backup language
75 $this->getContext()->setLanguage( Language
::factory( $params['uselang'] ) );
81 $result = $this->getResult();
83 if ( !is_null( $oldid ) ||
!is_null( $pageid ) ||
!is_null( $page ) ) {
84 if ( !is_null( $oldid ) ) {
85 // Don't use the parser cache
86 $rev = Revision
::newFromID( $oldid );
88 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
90 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
91 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
94 $titleObj = $rev->getTitle();
96 $pageObj = WikiPage
::factory( $titleObj );
97 $popts = $this->makeParserOptions( $pageObj, $params );
99 // If for some reason the "oldid" is actually the current revision, it may be cached
100 if ( $rev->isCurrent() ) {
101 // May get from/save to parser cache
102 $p_result = $this->getParsedContent( $pageObj, $popts,
103 $pageid, isset( $prop['wikitext'] ) );
104 } else { // This is an old revision, so get the text differently
105 $this->content
= $rev->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
107 if ( $this->section
!== false ) {
108 $this->content
= $this->getSectionContent( $this->content
, 'r' . $rev->getId() );
111 // Should we save old revision parses to the parser cache?
112 $p_result = $this->content
->getParserOutput( $titleObj, $rev->getId(), $popts );
114 } else { // Not $oldid, but $pageid or $page
115 if ( $params['redirects'] ) {
120 if ( !is_null ( $pageid ) ) {
121 $reqParams['pageids'] = $pageid;
123 $reqParams['titles'] = $page;
125 $req = new FauxRequest( $reqParams );
126 $main = new ApiMain( $req );
128 $data = $main->getResultData();
129 $redirValues = isset( $data['query']['redirects'] )
130 ?
$data['query']['redirects']
133 foreach ( (array)$redirValues as $r ) {
136 $pageParams = array( 'title' => $to );
137 } elseif ( !is_null( $pageid ) ) {
138 $pageParams = array( 'pageid' => $pageid );
140 $pageParams = array( 'title' => $page );
143 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
144 $titleObj = $pageObj->getTitle();
145 if ( !$titleObj ||
!$titleObj->exists() ) {
146 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
148 $wgTitle = $titleObj;
150 if ( isset( $prop['revid'] ) ) {
151 $oldid = $pageObj->getLatest();
154 $popts = $this->makeParserOptions( $pageObj, $params );
156 // Potentially cached
157 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
158 isset( $prop['wikitext'] ) );
160 } else { // Not $oldid, $pageid, $page. Hence based on $text
161 $titleObj = Title
::newFromText( $title );
162 if ( !$titleObj ||
$titleObj->isExternal() ) {
163 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
165 if ( !$titleObj->canExist() ) {
166 $this->dieUsage( "Namespace doesn't allow actual pages", 'pagecannotexist' );
168 $wgTitle = $titleObj;
169 $pageObj = WikiPage
::factory( $titleObj );
171 $popts = $this->makeParserOptions( $pageObj, $params );
173 if ( is_null( $text ) ) {
174 $this->dieUsage( 'The text parameter should be passed with the title parameter. Should you be using the "page" parameter instead?', 'params' );
178 $this->content
= ContentHandler
::makeContent( $text, $titleObj, $model, $format );
179 } catch ( MWContentSerializationException
$ex ) {
180 $this->dieUsage( $ex->getMessage(), 'parseerror' );
183 if ( $this->section
!== false ) {
184 $this->content
= $this->getSectionContent( $this->content
, $titleObj->getText() );
187 if ( $params['pst'] ||
$params['onlypst'] ) {
188 $this->pstContent
= $this->content
->preSaveTransform( $titleObj, $this->getUser(), $popts );
190 if ( $params['onlypst'] ) {
191 // Build a result and bail out
192 $result_array = array();
193 $result_array['text'] = array();
194 ApiResult
::setContent( $result_array['text'], $this->pstContent
->serialize( $format ) );
195 if ( isset( $prop['wikitext'] ) ) {
196 $result_array['wikitext'] = array();
197 ApiResult
::setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
199 $result->addValue( null, $this->getModuleName(), $result_array );
203 // Not cached (save or load)
204 if ( $params['pst'] ) {
205 $p_result = $this->pstContent
->getParserOutput( $titleObj, null, $popts );
207 $p_result = $this->content
->getParserOutput( $titleObj, null, $popts );
211 $result_array = array();
213 $result_array['title'] = $titleObj->getPrefixedText();
215 if ( !is_null( $oldid ) ) {
216 $result_array['revid'] = intval( $oldid );
219 if ( $params['redirects'] && !is_null( $redirValues ) ) {
220 $result_array['redirects'] = $redirValues;
223 if ( isset( $prop['text'] ) ) {
224 $result_array['text'] = array();
225 ApiResult
::setContent( $result_array['text'], $p_result->getText() );
228 if ( !is_null( $params['summary'] ) ) {
229 $result_array['parsedsummary'] = array();
230 ApiResult
::setContent( $result_array['parsedsummary'], Linker
::formatComment( $params['summary'], $titleObj ) );
233 if ( isset( $prop['langlinks'] ) ||
isset( $prop['languageshtml'] ) ) {
234 $langlinks = $p_result->getLanguageLinks();
236 if ( $params['effectivelanglinks'] ) {
237 // Link flags are ignored for now, but may in the future be
238 // included in the result.
239 $linkFlags = array();
240 wfRunHooks( 'LanguageLinks', array( $titleObj, &$langlinks, &$linkFlags ) );
246 if ( isset( $prop['langlinks'] ) ) {
247 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
249 if ( isset( $prop['languageshtml'] ) ) {
250 $languagesHtml = $this->languagesHtml( $langlinks );
252 $result_array['languageshtml'] = array();
253 ApiResult
::setContent( $result_array['languageshtml'], $languagesHtml );
255 if ( isset( $prop['categories'] ) ) {
256 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
258 if ( isset( $prop['categorieshtml'] ) ) {
259 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
260 $result_array['categorieshtml'] = array();
261 ApiResult
::setContent( $result_array['categorieshtml'], $categoriesHtml );
263 if ( isset( $prop['links'] ) ) {
264 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
266 if ( isset( $prop['templates'] ) ) {
267 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
269 if ( isset( $prop['images'] ) ) {
270 $result_array['images'] = array_keys( $p_result->getImages() );
272 if ( isset( $prop['externallinks'] ) ) {
273 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
275 if ( isset( $prop['sections'] ) ) {
276 $result_array['sections'] = $p_result->getSections();
279 if ( isset( $prop['displaytitle'] ) ) {
280 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
281 $p_result->getDisplayTitle() :
282 $titleObj->getPrefixedText();
285 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
286 $context = $this->getContext();
287 $context->setTitle( $titleObj );
288 $context->getOutput()->addParserOutputNoText( $p_result );
290 if ( isset( $prop['headitems'] ) ) {
291 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
293 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
295 $scripts = array( $context->getOutput()->getHeadScripts() );
297 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
300 if ( isset( $prop['headhtml'] ) ) {
301 $result_array['headhtml'] = array();
302 ApiResult
::setContent( $result_array['headhtml'], $context->getOutput()->headElement( $context->getSkin() ) );
306 if ( isset( $prop['iwlinks'] ) ) {
307 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
310 if ( isset( $prop['wikitext'] ) ) {
311 $result_array['wikitext'] = array();
312 ApiResult
::setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
313 if ( !is_null( $this->pstContent
) ) {
314 $result_array['psttext'] = array();
315 ApiResult
::setContent( $result_array['psttext'], $this->pstContent
->serialize( $format ) );
318 if ( isset( $prop['properties'] ) ) {
319 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
322 if ( $params['generatexml'] ) {
323 if ( $this->content
->getModel() != CONTENT_MODEL_WIKITEXT
) {
324 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
327 $wgParser->startExternalParse( $titleObj, $popts, OT_PREPROCESS
);
328 $dom = $wgParser->preprocessToDom( $this->content
->getNativeData() );
329 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
330 $xml = $dom->saveXML();
332 $xml = $dom->__toString();
334 $result_array['parsetree'] = array();
335 ApiResult
::setContent( $result_array['parsetree'], $xml );
338 $result_mapping = array(
341 'categories' => 'cl',
345 'externallinks' => 'el',
349 'properties' => 'pp',
351 $this->setIndexedTagNames( $result_array, $result_mapping );
352 $result->addValue( null, $this->getModuleName(), $result_array );
354 if ( !is_null( $oldLang ) ) {
355 $this->getContext()->setLanguage( $oldLang ); // Reset language to $oldLang
360 * Constructs a ParserOptions object
362 * @param WikiPage $pageObj
363 * @param array $params
365 * @return ParserOptions
367 protected function makeParserOptions( WikiPage
$pageObj, array $params ) {
368 wfProfileIn( __METHOD__
);
370 $popts = $pageObj->makeParserOptions( $this->getContext() );
371 $popts->enableLimitReport( !$params['disablepp'] );
372 $popts->setIsPreview( $params['preview'] ||
$params['sectionpreview'] );
373 $popts->setIsSectionPreview( $params['sectionpreview'] );
375 wfProfileOut( __METHOD__
);
380 * @param $page WikiPage
381 * @param $popts ParserOptions
383 * @param $getWikitext Bool
384 * @return ParserOutput
386 private function getParsedContent( WikiPage
$page, $popts, $pageId = null, $getWikitext = false ) {
387 $this->content
= $page->getContent( Revision
::RAW
); //XXX: really raw?
389 if ( $this->section
!== false && $this->content
!== null ) {
390 $this->content
= $this->getSectionContent(
392 !is_null( $pageId ) ?
'page id ' . $pageId : $page->getTitle()->getText() );
394 // Not cached (save or load)
395 return $this->content
->getParserOutput( $page->getTitle(), null, $popts );
397 // Try the parser cache first
398 // getParserOutput will save to Parser cache if able
399 $pout = $page->getParserOutput( $popts );
401 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
403 if ( $getWikitext ) {
404 $this->content
= $page->getContent( Revision
::RAW
);
410 private function getSectionContent( Content
$content, $what ) {
411 // Not cached (save or load)
412 $section = $content->getSection( $this->section
);
413 if ( $section === false ) {
414 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
416 if ( $section === null ) {
417 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
423 private function formatLangLinks( $links ) {
425 foreach ( $links as $link ) {
427 $bits = explode( ':', $link, 2 );
428 $title = Title
::newFromText( $link );
430 $entry['lang'] = $bits[0];
432 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
434 ApiResult
::setContent( $entry, $bits[1] );
440 private function formatCategoryLinks( $links ) {
442 foreach ( $links as $link => $sortkey ) {
444 $entry['sortkey'] = $sortkey;
445 ApiResult
::setContent( $entry, $link );
451 private function categoriesHtml( $categories ) {
452 $context = $this->getContext();
453 $context->getOutput()->addCategoryLinks( $categories );
454 return $context->getSkin()->getCategories();
458 * @deprecated since 1.18 No modern skin generates language links this way, please use language links
459 * data to generate your own HTML.
460 * @param $languages array
463 private function languagesHtml( $languages ) {
464 wfDeprecated( __METHOD__
, '1.18' );
466 global $wgContLang, $wgHideInterlanguageLinks;
468 if ( $wgHideInterlanguageLinks ||
count( $languages ) == 0 ) {
472 $s = htmlspecialchars( wfMessage( 'otherlanguages' )->text() . wfMessage( 'colon-separator' )->text() );
475 foreach ( $languages as $l ) {
476 $nt = Title
::newFromText( $l );
477 $text = Language
::fetchLanguageName( $nt->getInterwiki() );
479 $langs[] = Html
::element( 'a',
480 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => 'external' ),
481 $text == '' ?
$l : $text );
484 $s .= implode( wfMessage( 'pipe-separator' )->escaped(), $langs );
486 if ( $wgContLang->isRTL() ) {
487 $s = Html
::rawElement( 'span', array( 'dir' => 'LTR' ), $s );
493 private function formatLinks( $links ) {
495 foreach ( $links as $ns => $nslinks ) {
496 foreach ( $nslinks as $title => $id ) {
499 ApiResult
::setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
501 $entry['exists'] = '';
509 private function formatIWLinks( $iw ) {
511 foreach ( $iw as $prefix => $titles ) {
512 foreach ( array_keys( $titles ) as $title ) {
514 $entry['prefix'] = $prefix;
516 $title = Title
::newFromText( "{$prefix}:{$title}" );
518 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
521 ApiResult
::setContent( $entry, $title->getFullText() );
528 private function formatHeadItems( $headItems ) {
530 foreach ( $headItems as $tag => $content ) {
532 $entry['tag'] = $tag;
533 ApiResult
::setContent( $entry, $content );
539 private function formatProperties( $properties ) {
541 foreach ( $properties as $name => $value ) {
543 $entry['name'] = $name;
544 ApiResult
::setContent( $entry, $value );
550 private function formatCss( $css ) {
552 foreach ( $css as $file => $link ) {
554 $entry['file'] = $file;
555 ApiResult
::setContent( $entry, $link );
561 private function setIndexedTagNames( &$array, $mapping ) {
562 foreach ( $mapping as $key => $name ) {
563 if ( isset( $array[$key] ) ) {
564 $this->getResult()->setIndexedTagName( $array[$key], $name );
569 public function getAllowedParams() {
572 ApiBase
::PARAM_DFLT
=> 'API',
578 ApiBase
::PARAM_TYPE
=> 'integer',
580 'redirects' => false,
582 ApiBase
::PARAM_TYPE
=> 'integer',
585 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle|iwlinks|properties',
586 ApiBase
::PARAM_ISMULTI
=> true,
587 ApiBase
::PARAM_TYPE
=> array(
609 'effectivelanglinks' => false,
612 'disablepp' => false,
613 'generatexml' => false,
615 'sectionpreview' => false,
616 'contentformat' => array(
617 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
619 'contentmodel' => array(
620 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
625 public function getParamDescription() {
626 $p = $this->getModulePrefix();
628 'text' => 'Wikitext to parse',
629 'summary' => 'Summary to parse',
630 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
631 'title' => 'Title of page the text belongs to',
632 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
633 'pageid' => "Parse the content of this page. Overrides {$p}page",
634 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
636 'Which pieces of information to get',
637 ' text - Gives the parsed text of the wikitext',
638 ' langlinks - Gives the language links in the parsed wikitext',
639 ' categories - Gives the categories in the parsed wikitext',
640 ' categorieshtml - Gives the HTML version of the categories',
641 ' languageshtml - Gives the HTML version of the language links',
642 ' links - Gives the internal links in the parsed wikitext',
643 ' templates - Gives the templates in the parsed wikitext',
644 ' images - Gives the images in the parsed wikitext',
645 ' externallinks - Gives the external links in the parsed wikitext',
646 ' sections - Gives the sections in the parsed wikitext',
647 ' revid - Adds the revision ID of the parsed page',
648 ' displaytitle - Adds the title of the parsed wikitext',
649 ' headitems - Gives items to put in the <head> of the page',
650 ' headhtml - Gives parsed <head> of the page',
651 ' iwlinks - Gives interwiki links in the parsed wikitext',
652 ' wikitext - Gives the original wikitext that was parsed',
653 ' properties - Gives various properties defined in the parsed wikitext',
655 'effectivelanglinks' => array(
656 'Includes language links supplied by extensions',
657 '(for use with prop=langlinks|languageshtml)',
660 'Do a pre-save transform on the input before parsing it',
661 'Ignored if page, pageid or oldid is used'
664 'Do a pre-save transform (PST) on the input, but don\'t parse it',
665 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
667 'uselang' => 'Which language to parse the request in',
668 'section' => 'Only retrieve the content of this section number',
669 'disablepp' => 'Disable the PP Report from the parser output',
670 'generatexml' => 'Generate XML parse tree (requires prop=wikitext)',
671 'preview' => 'Parse in preview mode',
672 'sectionpreview' => 'Parse in section preview mode (enables preview mode too)',
673 'contentformat' => 'Content serialization format used for the input text',
674 'contentmodel' => 'Content model of the new content',
678 public function getDescription() {
680 'Parses wikitext and returns parser output',
681 'See the various prop-Modules of action=query to get information from the current version of a page',
685 public function getPossibleErrors() {
686 return array_merge( parent
::getPossibleErrors(), array(
687 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
688 array( 'code' => 'params', 'info' => 'The text parameter should be passed with the title parameter. Should you be using the "page" parameter instead?' ),
689 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
690 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
691 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
692 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
693 array( 'nosuchpageid' ),
694 array( 'invalidtitle', 'title' ),
695 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
696 array( 'code' => 'notwikitext', 'info' => 'The requested operation is only supported on wikitext content.' ),
697 array( 'code' => 'pagecannotexist', 'info' => "Namespace doesn't allow actual pages" ),
701 public function getExamples() {
703 'api.php?action=parse&text={{Project:Sandbox}}'
707 public function getHelpUrls() {
708 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';