5 * Created on Dec 01, 2007
7 * Copyright © 2007 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiBase.php" );
35 class ApiParse
extends ApiBase
{
37 private $section, $text, $pstText = 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 if ( !is_null( $page ) && ( !is_null( $text ) ||
$title != 'API' ) ) {
56 $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 global $wgParser, $wgUser, $wgTitle, $wgLang;
70 // Currently unnecessary, code to act as a safeguard against any change in current behaviour of uselang breaks
72 if ( isset( $params['uselang'] ) && $params['uselang'] != $wgLang->getCode() ) {
73 $oldLang = $wgLang; // Backup wgLang
74 $wgLang = Language
::factory( $params['uselang'] );
77 $popts = new ParserOptions();
78 $popts->setTidy( true );
79 $popts->enableLimitReport( !$params['disablepp'] );
83 if ( !is_null( $oldid ) ||
!is_null( $pageid ) ||
!is_null( $page ) ) {
85 if ( !is_null( $oldid ) ) {
86 // Don't use the parser cache
87 $rev = Revision
::newFromID( $oldid );
89 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
91 if ( !$rev->userCan( Revision
::DELETED_TEXT
) ) {
92 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
95 $titleObj = $rev->getTitle();
99 // If for some reason the "oldid" is actually the current revision, it may be cached
100 if ( $titleObj->getLatestRevID() === intval( $oldid ) ) {
101 $articleObj = new Article( $titleObj, 0 );
103 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
104 isset( $prop['wikitext'] ) ) ;
106 } else { // This is an old revision, so get the text differently
107 $this->text
= $rev->getText( Revision
::FOR_THIS_USER
);
109 $wgTitle = $titleObj;
111 if ( $this->section
!== false ) {
112 $this->text
= $this->getSectionText( $this->text
, 'r' . $rev->getId() );
115 $p_result = $wgParser->parse( $this->text
, $titleObj, $popts );
118 } else { // Not $oldid
120 if ( !is_null ( $pageid ) ) {
121 $titleObj = Title
::newFromID( $pageid );
124 $this->dieUsageMsg( array( 'nosuchpageid', $pageid ) );
128 if ( $params['redirects'] ) {
129 $req = new FauxRequest( array(
134 $main = new ApiMain( $req );
136 $data = $main->getResultData();
137 $redirValues = isset( $data['query']['redirects'] )
138 ?
$data['query']['redirects'] : array();
140 foreach ( (array)$redirValues as $r ) {
146 $titleObj = Title
::newFromText( $to );
147 if ( !$titleObj ||
!$titleObj->exists() ) {
148 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
151 $wgTitle = $titleObj;
153 $articleObj = new Article( $titleObj, 0 );
154 if ( isset( $prop['revid'] ) ) {
155 $oldid = $articleObj->getRevIdFetched();
158 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
159 isset( $prop['wikitext'] ) ) ;
162 } else { // Not $oldid, $pageid, $page. Hence based on $text
165 $titleObj = Title
::newFromText( $title );
167 $titleObj = Title
::newFromText( 'API' );
169 $wgTitle = $titleObj;
171 if ( $this->section
!== false ) {
172 $this->text
= $this->getSectionText( $this->text
, $titleObj->getText() );
175 if ( $params['pst'] ||
$params['onlypst'] ) {
176 $this->pstText
= $wgParser->preSaveTransform( $this->text
, $titleObj, $wgUser, $popts );
178 if ( $params['onlypst'] ) {
179 // Build a result and bail out
180 $result_array['text'] = array();
181 $this->getResult()->setContent( $result_array['text'], $this->pstText
);
182 if ( isset( $prop['wikitext'] ) ) {
183 $result_array['wikitext'] = array();
184 $this->getResult()->setContent( $result_array['wikitext'], $this->text
);
186 $this->getResult()->addValue( null, $this->getModuleName(), $result_array );
189 $p_result = $wgParser->parse( $params['pst'] ?
$this->pstText
: $this->text
, $titleObj, $popts );
193 $result = $this->getResult();
194 $result_array = array();
196 $result_array['title'] = $titleObj->getPrefixedText();
198 if ( !is_null( $oldid ) ) {
199 $result_array['revid'] = intval( $oldid );
202 if ( $params['redirects'] && !is_null( $redirValues ) ) {
203 $result_array['redirects'] = $redirValues;
206 if ( isset( $prop['text'] ) ) {
207 $result_array['text'] = array();
208 $result->setContent( $result_array['text'], $p_result->getText() );
211 if ( !is_null( $params['summary'] ) ) {
212 $result_array['parsedsummary'] = array();
213 $result->setContent( $result_array['parsedsummary'], $wgUser->getSkin()->formatComment( $params['summary'], $titleObj ) );
216 if ( isset( $prop['langlinks'] ) ) {
217 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
219 if ( isset( $prop['languageshtml'] ) ) {
220 $languagesHtml = $this->languagesHtml( $p_result->getLanguageLinks() );
221 $result_array['languageshtml'] = array();
222 $result->setContent( $result_array['languageshtml'], $languagesHtml );
224 if ( isset( $prop['categories'] ) ) {
225 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
227 if ( isset( $prop['categorieshtml'] ) ) {
228 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
229 $result_array['categorieshtml'] = array();
230 $result->setContent( $result_array['categorieshtml'], $categoriesHtml );
232 if ( isset( $prop['links'] ) ) {
233 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
235 if ( isset( $prop['templates'] ) ) {
236 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
238 if ( isset( $prop['images'] ) ) {
239 $result_array['images'] = array_keys( $p_result->getImages() );
241 if ( isset( $prop['externallinks'] ) ) {
242 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
244 if ( isset( $prop['sections'] ) ) {
245 $result_array['sections'] = $p_result->getSections();
248 if ( isset( $prop['displaytitle'] ) ) {
249 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
250 $p_result->getDisplayTitle() :
251 $titleObj->getPrefixedText();
254 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
255 $context = new RequestContext
;
256 $context->output
->addParserOutputNoText( $p_result );
258 if ( isset( $prop['headitems'] ) ) {
259 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
261 $context->skin
->setupUserCss( $context->output
);
262 $css = $this->formatCss( $context->output
->buildCssLinksArray() );
264 $scripts = array( $context->output
->getHeadScripts( $context->skin
) );
266 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
269 if ( isset( $prop['headhtml'] ) ) {
270 $result_array['headhtml'] = array();
271 $result->setContent( $result_array['headhtml'], $context->output
->headElement( $context->skin
) );
275 if ( isset( $prop['iwlinks'] ) ) {
276 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
279 if ( isset( $prop['wikitext'] ) ) {
280 $result_array['wikitext'] = array();
281 $result->setContent( $result_array['wikitext'], $this->text
);
282 if ( !is_null( $this->pstText
) ) {
283 $result_array['psttext'] = array();
284 $result->setContent( $result_array['psttext'], $this->pstText
);
288 $result_mapping = array(
291 'categories' => 'cl',
295 'externallinks' => 'el',
300 $this->setIndexedTagNames( $result_array, $result_mapping );
301 $result->addValue( null, $this->getModuleName(), $result_array );
303 if ( !is_null( $oldLang ) ) {
304 $wgLang = $oldLang; // Reset $wgLang to $oldLang
309 * @param $articleObj Article
310 * @param $titleObj Title
311 * @param $popts ParserOptions
313 * @param $getWikitext Bool
314 * @return ParserOutput
316 private function getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageId = null, $getWikitext = false ) {
317 if ( $this->section
!== false ) {
320 $this->text
= $this->getSectionText( $articleObj->getRawText(), !is_null ( $pageId )
321 ?
'page id ' . $pageId : $titleObj->getText() );
323 return $wgParser->parse( $this->text
, $titleObj, $popts );
325 // Try the parser cache first
326 $pout = $articleObj->getParserOutput();
327 if ( $getWikitext ) {
328 $rev = Revision
::newFromTitle( $titleObj );
330 $this->text
= $rev->getText();
337 private function getSectionText( $text, $what ) {
339 $text = $wgParser->getSection( $text, $this->section
, false );
340 if ( $text === false ) {
341 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
346 private function formatLangLinks( $links ) {
348 foreach ( $links as $link ) {
350 $bits = explode( ':', $link, 2 );
351 $title = Title
::newFromText( $link );
353 $entry['lang'] = $bits[0];
355 $entry['url'] = $title->getFullURL();
357 $this->getResult()->setContent( $entry, $bits[1] );
363 private function formatCategoryLinks( $links ) {
365 foreach ( $links as $link => $sortkey ) {
367 $entry['sortkey'] = $sortkey;
368 $this->getResult()->setContent( $entry, $link );
374 private function categoriesHtml( $categories ) {
375 global $wgOut, $wgUser;
376 $wgOut->addCategoryLinks( $categories );
377 return $wgUser->getSkin()->getCategories();
381 * @deprecated No modern skin generates langlinks this way, please use langlinks data to generate your own html
383 private function languagesHtml( $languages ) {
384 global $wgContLang, $wgHideInterlanguageLinks;
386 if ( $wgHideInterlanguageLinks ||
count( $languages ) == 0 ) {
390 $s = htmlspecialchars( wfMsg( 'otherlanguages' ) . wfMsg( 'colon-separator' ) );
393 foreach ( $languages as $l ) {
394 $nt = Title
::newFromText( $l );
395 $text = $wgContLang->getLanguageName( $nt->getInterwiki() );
397 $langs[] = Html
::element( 'a',
398 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => "external" ),
399 $text == '' ?
$l : $text );
402 $s .= implode( htmlspecialchars( wfMsgExt( 'pipe-separator', 'escapenoentities' ) ), $langs );
404 if ( $wgContLang->isRTL() ) {
405 $s = Html
::rawElement( 'span', array( 'dir' => "LTR" ), $s );
411 private function formatLinks( $links ) {
413 foreach ( $links as $ns => $nslinks ) {
414 foreach ( $nslinks as $title => $id ) {
417 $this->getResult()->setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
419 $entry['exists'] = '';
427 private function formatIWLinks( $iw ) {
429 foreach ( $iw as $prefix => $titles ) {
430 foreach ( array_keys( $titles ) as $title ) {
432 $entry['prefix'] = $prefix;
434 $title = Title
::newFromText( "{$prefix}:{$title}" );
436 $entry['url'] = $title->getFullURL();
439 $this->getResult()->setContent( $entry, $title->getFullText() );
446 private function formatHeadItems( $headItems ) {
448 foreach ( $headItems as $tag => $content ) {
450 $entry['tag'] = $tag;
451 $this->getResult()->setContent( $entry, $content );
457 private function formatCss( $css ) {
459 foreach ( $css as $file => $link ) {
461 $entry['file'] = $file;
462 $this->getResult()->setContent( $entry, $link );
468 private function setIndexedTagNames( &$array, $mapping ) {
469 foreach ( $mapping as $key => $name ) {
470 if ( isset( $array[$key] ) ) {
471 $this->getResult()->setIndexedTagName( $array[$key], $name );
476 public function getAllowedParams() {
479 ApiBase
::PARAM_DFLT
=> 'API',
485 ApiBase
::PARAM_TYPE
=> 'integer',
487 'redirects' => false,
489 ApiBase
::PARAM_TYPE
=> 'integer',
492 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle',
493 ApiBase
::PARAM_ISMULTI
=> true,
494 ApiBase
::PARAM_TYPE
=> array(
517 'disablepp' => false,
521 public function getParamDescription() {
522 $p = $this->getModulePrefix();
524 'text' => 'Wikitext to parse',
525 'summary' => 'Summary to parse',
526 'redirects' => "If the {$p}page parameter is set to a redirect, resolve it",
527 'title' => 'Title of page the text belongs to',
528 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
529 'pageid' => "Parse the content of this page. Overrides {$p}page",
530 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
532 'Which pieces of information to get',
533 ' text - Gives the parsed text of the wikitext',
534 ' langlinks - Gives the language links in the parsed wikitext',
535 ' categories - Gives the categories in the parsed wikitext',
536 ' categorieshtml - Gives the HTML version of the categories',
537 ' languageshtml - Gives the HTML version of the language links',
538 ' links - Gives the internal links in the parsed wikitext',
539 ' templates - Gives the templates in the parsed wikitext',
540 ' images - Gives the images in the parsed wikitext',
541 ' externallinks - Gives the external links in the parsed wikitext',
542 ' sections - Gives the sections in the parsed wikitext',
543 ' revid - Adds the revision ID of the parsed page',
544 ' displaytitle - Adds the title of the parsed wikitext',
545 ' headitems - Gives items to put in the <head> of the page',
546 ' headhtml - Gives parsed <head> of the page',
547 ' iwlinks - Gives interwiki links in the parsed wikitext',
548 ' wikitext - Gives the original wikitext that was parsed',
551 'Do a pre-save transform on the input before parsing it',
552 'Ignored if page, pageid or oldid is used'
555 'Do a pre-save transform (PST) on the input, but don\'t parse it',
556 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
558 'uselang' => 'Which language to parse the request in',
559 'section' => 'Only retrieve the content of this section number',
560 'disablepp' => 'Disable the PP Report from the parser output',
564 public function getDescription() {
565 return 'Parses wikitext and returns parser output';
568 public function getPossibleErrors() {
569 return array_merge( parent
::getPossibleErrors(), array(
570 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
571 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
572 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
573 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
574 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
575 array( 'nosuchpageid' ),
579 protected function getExamples() {
581 'api.php?action=parse&text={{Project:Sandbox}}'
585 public function getVersion() {
586 return __CLASS__
. ': $Id$';