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, $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();
157 $popts = $pageObj->makeParserOptions( $this->getContext() );
158 $popts->enableLimitReport( !$params['disablepp'] );
160 // Potentially cached
161 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
162 isset( $prop['wikitext'] ) ) ;
164 } else { // Not $oldid, $pageid, $page. Hence based on $text
165 $titleObj = Title
::newFromText( $title );
167 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
169 $wgTitle = $titleObj;
170 $pageObj = WikiPage
::factory( $titleObj );
172 $popts = $pageObj->makeParserOptions( $this->getContext() );
173 $popts->enableLimitReport( !$params['disablepp'] );
175 if ( is_null( $text ) ) {
176 $this->dieUsage( 'The text parameter should be passed with the title parameter. Should you be using the "page" parameter instead?', 'params' );
180 $this->content
= ContentHandler
::makeContent( $text, $titleObj, $model, $format );
181 } catch ( MWContentSerializationException
$ex ) {
182 $this->dieUsage( $ex->getMessage(), 'parseerror' );
185 if ( $this->section
!== false ) {
186 $this->content
= $this->getSectionContent( $this->content
, $titleObj->getText() );
189 if ( $params['pst'] ||
$params['onlypst'] ) {
190 $this->pstContent
= $this->content
->preSaveTransform( $titleObj, $this->getUser(), $popts );
192 if ( $params['onlypst'] ) {
193 // Build a result and bail out
194 $result_array = array();
195 $result_array['text'] = array();
196 $result->setContent( $result_array['text'], $this->pstContent
->serialize( $format ) );
197 if ( isset( $prop['wikitext'] ) ) {
198 $result_array['wikitext'] = array();
199 $result->setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
201 $result->addValue( null, $this->getModuleName(), $result_array );
205 // Not cached (save or load)
206 if ( $params['pst'] ) {
207 $p_result = $this->pstContent
->getParserOutput( $titleObj, $popts );
209 $p_result = $this->content
->getParserOutput( $titleObj, $popts );
213 $result_array = array();
215 $result_array['title'] = $titleObj->getPrefixedText();
217 if ( !is_null( $oldid ) ) {
218 $result_array['revid'] = intval( $oldid );
221 if ( $params['redirects'] && !is_null( $redirValues ) ) {
222 $result_array['redirects'] = $redirValues;
225 if ( isset( $prop['text'] ) ) {
226 $result_array['text'] = array();
227 $result->setContent( $result_array['text'], $p_result->getText() );
230 if ( !is_null( $params['summary'] ) ) {
231 $result_array['parsedsummary'] = array();
232 $result->setContent( $result_array['parsedsummary'], Linker
::formatComment( $params['summary'], $titleObj ) );
235 if ( isset( $prop['langlinks'] ) ) {
236 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
238 if ( isset( $prop['languageshtml'] ) ) {
239 $languagesHtml = $this->languagesHtml( $p_result->getLanguageLinks() );
240 $result_array['languageshtml'] = array();
241 $result->setContent( $result_array['languageshtml'], $languagesHtml );
243 if ( isset( $prop['categories'] ) ) {
244 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
246 if ( isset( $prop['categorieshtml'] ) ) {
247 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
248 $result_array['categorieshtml'] = array();
249 $result->setContent( $result_array['categorieshtml'], $categoriesHtml );
251 if ( isset( $prop['links'] ) ) {
252 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
254 if ( isset( $prop['templates'] ) ) {
255 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
257 if ( isset( $prop['images'] ) ) {
258 $result_array['images'] = array_keys( $p_result->getImages() );
260 if ( isset( $prop['externallinks'] ) ) {
261 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
263 if ( isset( $prop['sections'] ) ) {
264 $result_array['sections'] = $p_result->getSections();
267 if ( isset( $prop['displaytitle'] ) ) {
268 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
269 $p_result->getDisplayTitle() :
270 $titleObj->getPrefixedText();
273 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
274 $context = $this->getContext();
275 $context->setTitle( $titleObj );
276 $context->getOutput()->addParserOutputNoText( $p_result );
278 if ( isset( $prop['headitems'] ) ) {
279 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
281 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
283 $scripts = array( $context->getOutput()->getHeadScripts() );
285 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
288 if ( isset( $prop['headhtml'] ) ) {
289 $result_array['headhtml'] = array();
290 $result->setContent( $result_array['headhtml'], $context->getOutput()->headElement( $context->getSkin() ) );
294 if ( isset( $prop['iwlinks'] ) ) {
295 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
298 if ( isset( $prop['wikitext'] ) ) {
299 $result_array['wikitext'] = array();
300 $result->setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
301 if ( !is_null( $this->pstContent
) ) {
302 $result_array['psttext'] = array();
303 $result->setContent( $result_array['psttext'], $this->pstContent
->serialize( $format ) );
306 if ( isset( $prop['properties'] ) ) {
307 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
310 if ( $params['generatexml'] ) {
311 if ( $this->content
->getModel() != CONTENT_MODEL_WIKITEXT
) {
312 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
315 $wgParser->startExternalParse( $titleObj, $popts, OT_PREPROCESS
);
316 $dom = $wgParser->preprocessToDom( $this->content
->getNativeData() );
317 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
318 $xml = $dom->saveXML();
320 $xml = $dom->__toString();
322 $result_array['parsetree'] = array();
323 $result->setContent( $result_array['parsetree'], $xml );
326 $result_mapping = array(
329 'categories' => 'cl',
333 'externallinks' => 'el',
337 'properties' => 'pp',
339 $this->setIndexedTagNames( $result_array, $result_mapping );
340 $result->addValue( null, $this->getModuleName(), $result_array );
342 if ( !is_null( $oldLang ) ) {
343 $this->getContext()->setLanguage( $oldLang ); // Reset language to $oldLang
348 * @param $page WikiPage
349 * @param $popts ParserOptions
351 * @param $getWikitext Bool
352 * @return ParserOutput
354 private function getParsedContent( WikiPage
$page, $popts, $pageId = null, $getWikitext = false ) {
355 $this->content
= $page->getContent( Revision
::RAW
); //XXX: really raw?
357 if ( $this->section
!== false ) {
358 $this->content
= $this->getSectionContent(
360 !is_null( $pageId ) ?
'page id ' . $pageId : $page->getTitle()->getText() );
362 // Not cached (save or load)
363 return $this->content
->getParserOutput( $page->getTitle(), $popts );
365 // Try the parser cache first
366 // getParserOutput will save to Parser cache if able
367 $pout = $page->getParserOutput( $popts );
369 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
371 if ( $getWikitext ) {
372 $this->content
= $page->getContent( Revision
::RAW
);
378 private function getSectionContent( Content
$content, $what ) {
379 // Not cached (save or load)
380 $section = $content->getSection( $this->section
);
381 if ( $section === false ) {
382 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
384 if ( $section === null ) {
385 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
391 private function formatLangLinks( $links ) {
393 foreach ( $links as $link ) {
395 $bits = explode( ':', $link, 2 );
396 $title = Title
::newFromText( $link );
398 $entry['lang'] = $bits[0];
400 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
402 $this->getResult()->setContent( $entry, $bits[1] );
408 private function formatCategoryLinks( $links ) {
410 foreach ( $links as $link => $sortkey ) {
412 $entry['sortkey'] = $sortkey;
413 $this->getResult()->setContent( $entry, $link );
419 private function categoriesHtml( $categories ) {
420 $context = $this->getContext();
421 $context->getOutput()->addCategoryLinks( $categories );
422 return $context->getSkin()->getCategories();
426 * @deprecated since 1.18 No modern skin generates language links this way, please use language links
427 * data to generate your own HTML.
428 * @param $languages array
431 private function languagesHtml( $languages ) {
432 wfDeprecated( __METHOD__
, '1.18' );
434 global $wgContLang, $wgHideInterlanguageLinks;
436 if ( $wgHideInterlanguageLinks ||
count( $languages ) == 0 ) {
440 $s = htmlspecialchars( wfMessage( 'otherlanguages' )->text() . wfMessage( 'colon-separator' )->text() );
443 foreach ( $languages as $l ) {
444 $nt = Title
::newFromText( $l );
445 $text = Language
::fetchLanguageName( $nt->getInterwiki() );
447 $langs[] = Html
::element( 'a',
448 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => "external" ),
449 $text == '' ?
$l : $text );
452 $s .= implode( wfMessage( 'pipe-separator' )->escaped(), $langs );
454 if ( $wgContLang->isRTL() ) {
455 $s = Html
::rawElement( 'span', array( 'dir' => "LTR" ), $s );
461 private function formatLinks( $links ) {
463 foreach ( $links as $ns => $nslinks ) {
464 foreach ( $nslinks as $title => $id ) {
467 $this->getResult()->setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
469 $entry['exists'] = '';
477 private function formatIWLinks( $iw ) {
479 foreach ( $iw as $prefix => $titles ) {
480 foreach ( array_keys( $titles ) as $title ) {
482 $entry['prefix'] = $prefix;
484 $title = Title
::newFromText( "{$prefix}:{$title}" );
486 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
489 $this->getResult()->setContent( $entry, $title->getFullText() );
496 private function formatHeadItems( $headItems ) {
498 foreach ( $headItems as $tag => $content ) {
500 $entry['tag'] = $tag;
501 $this->getResult()->setContent( $entry, $content );
507 private function formatProperties( $properties ) {
509 foreach ( $properties as $name => $value ) {
511 $entry['name'] = $name;
512 $this->getResult()->setContent( $entry, $value );
518 private function formatCss( $css ) {
520 foreach ( $css as $file => $link ) {
522 $entry['file'] = $file;
523 $this->getResult()->setContent( $entry, $link );
529 private function setIndexedTagNames( &$array, $mapping ) {
530 foreach ( $mapping as $key => $name ) {
531 if ( isset( $array[$key] ) ) {
532 $this->getResult()->setIndexedTagName( $array[$key], $name );
537 public function getAllowedParams() {
540 ApiBase
::PARAM_DFLT
=> 'API',
546 ApiBase
::PARAM_TYPE
=> 'integer',
548 'redirects' => false,
550 ApiBase
::PARAM_TYPE
=> 'integer',
553 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle|iwlinks|properties',
554 ApiBase
::PARAM_ISMULTI
=> true,
555 ApiBase
::PARAM_TYPE
=> array(
579 'disablepp' => false,
580 'generatexml' => false,
581 'contentformat' => array(
582 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
584 'contentmodel' => array(
585 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
590 public function getParamDescription() {
591 $p = $this->getModulePrefix();
593 'text' => 'Wikitext to parse',
594 'summary' => 'Summary to parse',
595 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
596 'title' => 'Title of page the text belongs to',
597 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
598 'pageid' => "Parse the content of this page. Overrides {$p}page",
599 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
601 'Which pieces of information to get',
602 ' text - Gives the parsed text of the wikitext',
603 ' langlinks - Gives the language links in the parsed wikitext',
604 ' categories - Gives the categories in the parsed wikitext',
605 ' categorieshtml - Gives the HTML version of the categories',
606 ' languageshtml - Gives the HTML version of the language links',
607 ' links - Gives the internal links in the parsed wikitext',
608 ' templates - Gives the templates in the parsed wikitext',
609 ' images - Gives the images in the parsed wikitext',
610 ' externallinks - Gives the external links in the parsed wikitext',
611 ' sections - Gives the sections in the parsed wikitext',
612 ' revid - Adds the revision ID of the parsed page',
613 ' displaytitle - Adds the title of the parsed wikitext',
614 ' headitems - Gives items to put in the <head> of the page',
615 ' headhtml - Gives parsed <head> of the page',
616 ' iwlinks - Gives interwiki links in the parsed wikitext',
617 ' wikitext - Gives the original wikitext that was parsed',
618 ' properties - Gives various properties defined in the parsed wikitext',
621 'Do a pre-save transform on the input before parsing it',
622 'Ignored if page, pageid or oldid is used'
625 'Do a pre-save transform (PST) on the input, but don\'t parse it',
626 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
628 'uselang' => 'Which language to parse the request in',
629 'section' => 'Only retrieve the content of this section number',
630 'disablepp' => 'Disable the PP Report from the parser output',
631 'generatexml' => 'Generate XML parse tree',
632 'contentformat' => 'Content serialization format used for the input text',
633 'contentmodel' => 'Content model of the new content',
637 public function getDescription() {
639 'Parses wikitext and returns parser output',
640 'See the various prop-Modules of action=query to get information from the current version of a page',
644 public function getPossibleErrors() {
645 return array_merge( parent
::getPossibleErrors(), array(
646 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
647 array( 'code' => 'params', 'info' => 'The text parameter should be passed with the title parameter. Should you be using the "page" parameter instead?' ),
648 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
649 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
650 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
651 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
652 array( 'nosuchpageid' ),
653 array( 'invalidtitle', 'title' ),
654 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
655 array( 'code' => 'notwikitext', 'info' => 'The requested operation is only supported on wikitext content.' ),
659 public function getExamples() {
661 'api.php?action=parse&text={{Project:Sandbox}}'
665 public function getHelpUrls() {
666 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
669 public function getVersion() {
670 return __CLASS__
. ': $Id$';