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 __construct( $main, $action ) {
40 parent
::__construct( $main, $action );
43 public function execute() {
44 // The data is hot but user-dependent, like page views, so we set vary cookies
45 $this->getMain()->setCacheMode( 'anon-public-user-private' );
48 $params = $this->extractRequestParams();
49 $text = $params['text'];
50 $title = $params['title'];
51 $page = $params['page'];
52 $pageid = $params['pageid'];
53 $oldid = $params['oldid'];
55 $model = $params['contentmodel'];
56 $format = $params['contentformat'];
58 if ( !is_null( $page ) && ( !is_null( $text ) ||
$title != 'API' ) ) {
59 $this->dieUsage( 'The page parameter cannot be used together with the text and title parameters', 'params' );
62 $prop = array_flip( $params['prop'] );
64 if ( isset( $params['section'] ) ) {
65 $this->section
= $params['section'];
67 $this->section
= false;
70 // The parser needs $wgTitle to be set, apparently the
71 // $title parameter in Parser::parse isn't enough *sigh*
72 // TODO: Does this still need $wgTitle?
73 global $wgParser, $wgTitle;
75 // Currently unnecessary, code to act as a safeguard against any change in current behaviour of uselang breaks
77 if ( isset( $params['uselang'] ) && $params['uselang'] != $this->getContext()->getLanguage()->getCode() ) {
78 $oldLang = $this->getContext()->getLanguage(); // Backup language
79 $this->getContext()->setLanguage( Language
::factory( $params['uselang'] ) );
85 $result = $this->getResult();
87 if ( !is_null( $oldid ) ||
!is_null( $pageid ) ||
!is_null( $page ) ) {
88 if ( !is_null( $oldid ) ) {
89 // Don't use the parser cache
90 $rev = Revision
::newFromID( $oldid );
92 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
94 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
95 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
98 $titleObj = $rev->getTitle();
100 $pageObj = WikiPage
::factory( $titleObj );
101 $popts = $pageObj->makeParserOptions( $this->getContext() );
102 $popts->enableLimitReport( !$params['disablepp'] );
104 // If for some reason the "oldid" is actually the current revision, it may be cached
105 if ( $rev->isCurrent() ) {
106 // May get from/save to parser cache
107 $p_result = $this->getParsedContent( $pageObj, $popts,
108 $pageid, isset( $prop['wikitext'] ) ) ;
109 } else { // This is an old revision, so get the text differently
110 $this->content
= $rev->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
112 if ( $this->section
!== false ) {
113 $this->content
= $this->getSectionContent( $this->content
, 'r' . $rev->getId() );
116 // Should we save old revision parses to the parser cache?
117 $p_result = $this->content
->getParserOutput( $titleObj, $rev->getId(), $popts );
119 } else { // Not $oldid, but $pageid or $page
120 if ( $params['redirects'] ) {
125 if ( !is_null ( $pageid ) ) {
126 $reqParams['pageids'] = $pageid;
128 $reqParams['titles'] = $page;
130 $req = new FauxRequest( $reqParams );
131 $main = new ApiMain( $req );
133 $data = $main->getResultData();
134 $redirValues = isset( $data['query']['redirects'] )
135 ?
$data['query']['redirects']
138 foreach ( (array)$redirValues as $r ) {
141 $pageParams = array( 'title' => $to );
142 } elseif ( !is_null( $pageid ) ) {
143 $pageParams = array( 'pageid' => $pageid );
145 $pageParams = array( 'title' => $page );
148 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
149 $titleObj = $pageObj->getTitle();
150 $wgTitle = $titleObj;
152 if ( isset( $prop['revid'] ) ) {
153 $oldid = $pageObj->getLatest();
156 $popts = $pageObj->makeParserOptions( $this->getContext() );
157 $popts->enableLimitReport( !$params['disablepp'] );
159 // Potentially cached
160 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
161 isset( $prop['wikitext'] ) ) ;
163 } else { // Not $oldid, $pageid, $page. Hence based on $text
164 $titleObj = Title
::newFromText( $title );
166 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
168 $wgTitle = $titleObj;
169 $pageObj = WikiPage
::factory( $titleObj );
171 $popts = $pageObj->makeParserOptions( $this->getContext() );
172 $popts->enableLimitReport( !$params['disablepp'] );
174 if ( is_null( $text ) ) {
175 $this->dieUsage( 'The text parameter should be passed with the title parameter. Should you be using the "page" parameter instead?', 'params' );
179 $this->content
= ContentHandler
::makeContent( $text, $titleObj, $model, $format );
180 } catch ( MWContentSerializationException
$ex ) {
181 $this->dieUsage( $ex->getMessage(), 'parseerror' );
184 if ( $this->section
!== false ) {
185 $this->content
= $this->getSectionContent( $this->content
, $titleObj->getText() );
188 if ( $params['pst'] ||
$params['onlypst'] ) {
189 $this->pstContent
= $this->content
->preSaveTransform( $titleObj, $this->getUser(), $popts );
191 if ( $params['onlypst'] ) {
192 // Build a result and bail out
193 $result_array = array();
194 $result_array['text'] = array();
195 $result->setContent( $result_array['text'], $this->pstContent
->serialize( $format ) );
196 if ( isset( $prop['wikitext'] ) ) {
197 $result_array['wikitext'] = array();
198 $result->setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
200 $result->addValue( null, $this->getModuleName(), $result_array );
204 // Not cached (save or load)
205 if ( $params['pst'] ) {
206 $p_result = $this->pstContent
->getParserOutput( $titleObj, null, $popts );
208 $p_result = $this->content
->getParserOutput( $titleObj, null, $popts );
212 $result_array = array();
214 $result_array['title'] = $titleObj->getPrefixedText();
216 if ( !is_null( $oldid ) ) {
217 $result_array['revid'] = intval( $oldid );
220 if ( $params['redirects'] && !is_null( $redirValues ) ) {
221 $result_array['redirects'] = $redirValues;
224 if ( isset( $prop['text'] ) ) {
225 $result_array['text'] = array();
226 $result->setContent( $result_array['text'], $p_result->getText() );
229 if ( !is_null( $params['summary'] ) ) {
230 $result_array['parsedsummary'] = array();
231 $result->setContent( $result_array['parsedsummary'], Linker
::formatComment( $params['summary'], $titleObj ) );
234 if ( isset( $prop['langlinks'] ) ) {
235 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
237 if ( isset( $prop['languageshtml'] ) ) {
238 $languagesHtml = $this->languagesHtml( $p_result->getLanguageLinks() );
239 $result_array['languageshtml'] = array();
240 $result->setContent( $result_array['languageshtml'], $languagesHtml );
242 if ( isset( $prop['categories'] ) ) {
243 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
245 if ( isset( $prop['categorieshtml'] ) ) {
246 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
247 $result_array['categorieshtml'] = array();
248 $result->setContent( $result_array['categorieshtml'], $categoriesHtml );
250 if ( isset( $prop['links'] ) ) {
251 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
253 if ( isset( $prop['templates'] ) ) {
254 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
256 if ( isset( $prop['images'] ) ) {
257 $result_array['images'] = array_keys( $p_result->getImages() );
259 if ( isset( $prop['externallinks'] ) ) {
260 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
262 if ( isset( $prop['sections'] ) ) {
263 $result_array['sections'] = $p_result->getSections();
266 if ( isset( $prop['displaytitle'] ) ) {
267 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
268 $p_result->getDisplayTitle() :
269 $titleObj->getPrefixedText();
272 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
273 $context = $this->getContext();
274 $context->setTitle( $titleObj );
275 $context->getOutput()->addParserOutputNoText( $p_result );
277 if ( isset( $prop['headitems'] ) ) {
278 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
280 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
282 $scripts = array( $context->getOutput()->getHeadScripts() );
284 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
287 if ( isset( $prop['headhtml'] ) ) {
288 $result_array['headhtml'] = array();
289 $result->setContent( $result_array['headhtml'], $context->getOutput()->headElement( $context->getSkin() ) );
293 if ( isset( $prop['iwlinks'] ) ) {
294 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
297 if ( isset( $prop['wikitext'] ) ) {
298 $result_array['wikitext'] = array();
299 $result->setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
300 if ( !is_null( $this->pstContent
) ) {
301 $result_array['psttext'] = array();
302 $result->setContent( $result_array['psttext'], $this->pstContent
->serialize( $format ) );
305 if ( isset( $prop['properties'] ) ) {
306 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
309 if ( $params['generatexml'] ) {
310 if ( $this->content
->getModel() != CONTENT_MODEL_WIKITEXT
) {
311 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
314 $wgParser->startExternalParse( $titleObj, $popts, OT_PREPROCESS
);
315 $dom = $wgParser->preprocessToDom( $this->content
->getNativeData() );
316 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
317 $xml = $dom->saveXML();
319 $xml = $dom->__toString();
321 $result_array['parsetree'] = array();
322 $result->setContent( $result_array['parsetree'], $xml );
325 $result_mapping = array(
328 'categories' => 'cl',
332 'externallinks' => 'el',
336 'properties' => 'pp',
338 $this->setIndexedTagNames( $result_array, $result_mapping );
339 $result->addValue( null, $this->getModuleName(), $result_array );
341 if ( !is_null( $oldLang ) ) {
342 $this->getContext()->setLanguage( $oldLang ); // Reset language to $oldLang
347 * @param $page WikiPage
348 * @param $popts ParserOptions
350 * @param $getWikitext Bool
351 * @return ParserOutput
353 private function getParsedContent( WikiPage
$page, $popts, $pageId = null, $getWikitext = false ) {
354 $this->content
= $page->getContent( Revision
::RAW
); //XXX: really raw?
356 if ( $this->section
!== false ) {
357 $this->content
= $this->getSectionContent(
359 !is_null( $pageId ) ?
'page id ' . $pageId : $page->getTitle()->getText() );
361 // Not cached (save or load)
362 return $this->content
->getParserOutput( $page->getTitle(), null, $popts );
364 // Try the parser cache first
365 // getParserOutput will save to Parser cache if able
366 $pout = $page->getParserOutput( $popts );
368 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
370 if ( $getWikitext ) {
371 $this->content
= $page->getContent( Revision
::RAW
);
377 private function getSectionContent( Content
$content, $what ) {
378 // Not cached (save or load)
379 $section = $content->getSection( $this->section
);
380 if ( $section === false ) {
381 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
383 if ( $section === null ) {
384 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
390 private function formatLangLinks( $links ) {
392 foreach ( $links as $link ) {
394 $bits = explode( ':', $link, 2 );
395 $title = Title
::newFromText( $link );
397 $entry['lang'] = $bits[0];
399 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
401 $this->getResult()->setContent( $entry, $bits[1] );
407 private function formatCategoryLinks( $links ) {
409 foreach ( $links as $link => $sortkey ) {
411 $entry['sortkey'] = $sortkey;
412 $this->getResult()->setContent( $entry, $link );
418 private function categoriesHtml( $categories ) {
419 $context = $this->getContext();
420 $context->getOutput()->addCategoryLinks( $categories );
421 return $context->getSkin()->getCategories();
425 * @deprecated since 1.18 No modern skin generates language links this way, please use language links
426 * data to generate your own HTML.
427 * @param $languages array
430 private function languagesHtml( $languages ) {
431 wfDeprecated( __METHOD__
, '1.18' );
433 global $wgContLang, $wgHideInterlanguageLinks;
435 if ( $wgHideInterlanguageLinks ||
count( $languages ) == 0 ) {
439 $s = htmlspecialchars( wfMessage( 'otherlanguages' )->text() . wfMessage( 'colon-separator' )->text() );
442 foreach ( $languages as $l ) {
443 $nt = Title
::newFromText( $l );
444 $text = Language
::fetchLanguageName( $nt->getInterwiki() );
446 $langs[] = Html
::element( 'a',
447 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => "external" ),
448 $text == '' ?
$l : $text );
451 $s .= implode( wfMessage( 'pipe-separator' )->escaped(), $langs );
453 if ( $wgContLang->isRTL() ) {
454 $s = Html
::rawElement( 'span', array( 'dir' => "LTR" ), $s );
460 private function formatLinks( $links ) {
462 foreach ( $links as $ns => $nslinks ) {
463 foreach ( $nslinks as $title => $id ) {
466 $this->getResult()->setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
468 $entry['exists'] = '';
476 private function formatIWLinks( $iw ) {
478 foreach ( $iw as $prefix => $titles ) {
479 foreach ( array_keys( $titles ) as $title ) {
481 $entry['prefix'] = $prefix;
483 $title = Title
::newFromText( "{$prefix}:{$title}" );
485 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
488 $this->getResult()->setContent( $entry, $title->getFullText() );
495 private function formatHeadItems( $headItems ) {
497 foreach ( $headItems as $tag => $content ) {
499 $entry['tag'] = $tag;
500 $this->getResult()->setContent( $entry, $content );
506 private function formatProperties( $properties ) {
508 foreach ( $properties as $name => $value ) {
510 $entry['name'] = $name;
511 $this->getResult()->setContent( $entry, $value );
517 private function formatCss( $css ) {
519 foreach ( $css as $file => $link ) {
521 $entry['file'] = $file;
522 $this->getResult()->setContent( $entry, $link );
528 private function setIndexedTagNames( &$array, $mapping ) {
529 foreach ( $mapping as $key => $name ) {
530 if ( isset( $array[$key] ) ) {
531 $this->getResult()->setIndexedTagName( $array[$key], $name );
536 public function getAllowedParams() {
539 ApiBase
::PARAM_DFLT
=> 'API',
545 ApiBase
::PARAM_TYPE
=> 'integer',
547 'redirects' => false,
549 ApiBase
::PARAM_TYPE
=> 'integer',
552 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle|iwlinks|properties',
553 ApiBase
::PARAM_ISMULTI
=> true,
554 ApiBase
::PARAM_TYPE
=> array(
578 'disablepp' => false,
579 'generatexml' => false,
580 'contentformat' => array(
581 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
583 'contentmodel' => array(
584 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
589 public function getParamDescription() {
590 $p = $this->getModulePrefix();
592 'text' => 'Wikitext to parse',
593 'summary' => 'Summary to parse',
594 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
595 'title' => 'Title of page the text belongs to',
596 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
597 'pageid' => "Parse the content of this page. Overrides {$p}page",
598 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
600 'Which pieces of information to get',
601 ' text - Gives the parsed text of the wikitext',
602 ' langlinks - Gives the language links in the parsed wikitext',
603 ' categories - Gives the categories in the parsed wikitext',
604 ' categorieshtml - Gives the HTML version of the categories',
605 ' languageshtml - Gives the HTML version of the language links',
606 ' links - Gives the internal links in the parsed wikitext',
607 ' templates - Gives the templates in the parsed wikitext',
608 ' images - Gives the images in the parsed wikitext',
609 ' externallinks - Gives the external links in the parsed wikitext',
610 ' sections - Gives the sections in the parsed wikitext',
611 ' revid - Adds the revision ID of the parsed page',
612 ' displaytitle - Adds the title of the parsed wikitext',
613 ' headitems - Gives items to put in the <head> of the page',
614 ' headhtml - Gives parsed <head> of the page',
615 ' iwlinks - Gives interwiki links in the parsed wikitext',
616 ' wikitext - Gives the original wikitext that was parsed',
617 ' properties - Gives various properties defined in the parsed wikitext',
620 'Do a pre-save transform on the input before parsing it',
621 'Ignored if page, pageid or oldid is used'
624 'Do a pre-save transform (PST) on the input, but don\'t parse it',
625 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
627 'uselang' => 'Which language to parse the request in',
628 'section' => 'Only retrieve the content of this section number',
629 'disablepp' => 'Disable the PP Report from the parser output',
630 'generatexml' => 'Generate XML parse tree',
631 'contentformat' => 'Content serialization format used for the input text',
632 'contentmodel' => 'Content model of the new content',
636 public function getDescription() {
638 'Parses wikitext and returns parser output',
639 'See the various prop-Modules of action=query to get information from the current version of a page',
643 public function getPossibleErrors() {
644 return array_merge( parent
::getPossibleErrors(), array(
645 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
646 array( 'code' => 'params', 'info' => 'The text parameter should be passed with the title parameter. Should you be using the "page" parameter instead?' ),
647 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
648 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
649 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
650 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
651 array( 'nosuchpageid' ),
652 array( 'invalidtitle', 'title' ),
653 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
654 array( 'code' => 'notwikitext', 'info' => 'The requested operation is only supported on wikitext content.' ),
658 public function getExamples() {
660 'api.php?action=parse&text={{Project:Sandbox}}'
664 public function getHelpUrls() {
665 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
668 public function getVersion() {
669 return __CLASS__
. ': $Id$';