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
25 if ( !defined( 'MEDIAWIKI' ) ) {
26 // Eclipse helper - will be ignored in production
27 require_once( "ApiBase.php" );
33 class ApiParse
extends ApiBase
{
34 private $section, $text, $pstText = null;
36 public function __construct( $main, $action ) {
37 parent
::__construct( $main, $action );
40 public function execute() {
41 // The data is hot but user-dependent, like page views, so we set vary cookies
42 $this->getMain()->setCacheMode( 'anon-public-user-private' );
45 $params = $this->extractRequestParams();
46 $text = $params['text'];
47 $title = $params['title'];
48 $page = $params['page'];
49 $pageid = $params['pageid'];
50 $oldid = $params['oldid'];
52 if ( !is_null( $page ) && ( !is_null( $text ) ||
$title != 'API' ) ) {
53 $this->dieUsage( 'The page parameter cannot be used together with the text and title parameters', 'params' );
55 $prop = array_flip( $params['prop'] );
57 if ( isset( $params['section'] ) ) {
58 $this->section
= $params['section'];
60 $this->section
= false;
63 // The parser needs $wgTitle to be set, apparently the
64 // $title parameter in Parser::parse isn't enough *sigh*
65 global $wgParser, $wgUser, $wgTitle, $wgLang;
67 // Currently unnecessary, code to act as a safeguard against any change in current behaviour of uselang breaks
69 if ( isset( $params['uselang'] ) && $params['uselang'] != $wgLang->getCode() ) {
70 $oldLang = $wgLang; // Backup wgLang
71 $wgLang = Language
::factory( $params['uselang'] );
74 $popts = new ParserOptions();
75 $popts->setTidy( true );
76 $popts->enableLimitReport( !$params['disablepp'] );
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
) ) {
91 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
94 $titleObj = $rev->getTitle();
98 // If for some reason the "oldid" is actually the current revision, it may be cached
99 if ( $titleObj->getLatestRevID() === intval( $oldid ) ) {
100 $articleObj = new Article( $titleObj, 0 );
102 // May get from/save to parser cache
103 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
104 isset( $prop['wikitext'] ) ) ;
105 } else { // This is an old revision, so get the text differently
106 $this->text
= $rev->getText( Revision
::FOR_THIS_USER
);
108 $wgTitle = $titleObj;
110 if ( $this->section
!== false ) {
111 $this->text
= $this->getSectionText( $this->text
, 'r' . $rev->getId() );
114 // Should we save old revision parses to the parser cache?
115 $p_result = $wgParser->parse( $this->text
, $titleObj, $popts );
117 } else { // Not $oldid, but $pageid or $page
118 if ( $params['redirects'] ) {
123 if ( !is_null ( $pageid ) ) {
124 $reqParams['pageids'] = $pageid;
126 $reqParams['titles'] = $page;
128 $req = new FauxRequest( $reqParams );
129 $main = new ApiMain( $req );
131 $data = $main->getResultData();
132 $redirValues = isset( $data['query']['redirects'] )
133 ?
$data['query']['redirects']
136 foreach ( (array)$redirValues as $r ) {
139 $titleObj = Title
::newFromText( $to );
141 if ( !is_null ( $pageid ) ) {
142 $reqParams['pageids'] = $pageid;
143 $titleObj = Title
::newFromID( $pageid );
146 $titleObj = Title
::newFromText( $to );
149 if ( !is_null ( $pageid ) ) {
151 // Still throw nosuchpageid error if pageid was provided
152 $this->dieUsageMsg( array( 'nosuchpageid', $pageid ) );
154 } elseif ( !$titleObj ||
!$titleObj->exists() ) {
155 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
157 $wgTitle = $titleObj;
159 $articleObj = new Article( $titleObj, 0 );
160 if ( isset( $prop['revid'] ) ) {
161 $oldid = $articleObj->getRevIdFetched();
164 // Potentially cached
165 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
166 isset( $prop['wikitext'] ) ) ;
168 } else { // Not $oldid, $pageid, $page. Hence based on $text
171 $titleObj = Title
::newFromText( $title );
173 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
175 $wgTitle = $titleObj;
177 if ( $this->section
!== false ) {
178 $this->text
= $this->getSectionText( $this->text
, $titleObj->getText() );
181 if ( $params['pst'] ||
$params['onlypst'] ) {
182 $this->pstText
= $wgParser->preSaveTransform( $this->text
, $titleObj, $wgUser, $popts );
184 if ( $params['onlypst'] ) {
185 // Build a result and bail out
186 $result_array = array();
187 $result_array['text'] = array();
188 $result->setContent( $result_array['text'], $this->pstText
);
189 if ( isset( $prop['wikitext'] ) ) {
190 $result_array['wikitext'] = array();
191 $result->setContent( $result_array['wikitext'], $this->text
);
193 $result->addValue( null, $this->getModuleName(), $result_array );
196 // Not cached (save or load)
197 $p_result = $wgParser->parse( $params['pst'] ?
$this->pstText
: $this->text
, $titleObj, $popts );
200 $result_array = array();
202 $result_array['title'] = $titleObj->getPrefixedText();
204 if ( !is_null( $oldid ) ) {
205 $result_array['revid'] = intval( $oldid );
208 if ( $params['redirects'] && !is_null( $redirValues ) ) {
209 $result_array['redirects'] = $redirValues;
212 if ( isset( $prop['text'] ) ) {
213 $result_array['text'] = array();
214 $result->setContent( $result_array['text'], $p_result->getText() );
217 if ( !is_null( $params['summary'] ) ) {
218 $result_array['parsedsummary'] = array();
219 $result->setContent( $result_array['parsedsummary'], Linker
::formatComment( $params['summary'], $titleObj ) );
222 if ( isset( $prop['langlinks'] ) ) {
223 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
225 if ( isset( $prop['languageshtml'] ) ) {
226 $languagesHtml = $this->languagesHtml( $p_result->getLanguageLinks() );
227 $result_array['languageshtml'] = array();
228 $result->setContent( $result_array['languageshtml'], $languagesHtml );
230 if ( isset( $prop['categories'] ) ) {
231 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
233 if ( isset( $prop['categorieshtml'] ) ) {
234 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
235 $result_array['categorieshtml'] = array();
236 $result->setContent( $result_array['categorieshtml'], $categoriesHtml );
238 if ( isset( $prop['links'] ) ) {
239 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
241 if ( isset( $prop['templates'] ) ) {
242 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
244 if ( isset( $prop['images'] ) ) {
245 $result_array['images'] = array_keys( $p_result->getImages() );
247 if ( isset( $prop['externallinks'] ) ) {
248 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
250 if ( isset( $prop['sections'] ) ) {
251 $result_array['sections'] = $p_result->getSections();
254 if ( isset( $prop['displaytitle'] ) ) {
255 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
256 $p_result->getDisplayTitle() :
257 $titleObj->getPrefixedText();
260 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
261 $context = $this->createContext();
262 $context->setTitle( $titleObj );
263 $context->getOutput()->addParserOutputNoText( $p_result );
265 if ( isset( $prop['headitems'] ) ) {
266 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
268 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
270 $scripts = array( $context->getOutput()->getHeadScripts() );
272 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
275 if ( isset( $prop['headhtml'] ) ) {
276 $result_array['headhtml'] = array();
277 $result->setContent( $result_array['headhtml'], $context->getOutput()->headElement( $context->getSkin() ) );
281 if ( isset( $prop['iwlinks'] ) ) {
282 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
285 if ( isset( $prop['wikitext'] ) ) {
286 $result_array['wikitext'] = array();
287 $result->setContent( $result_array['wikitext'], $this->text
);
288 if ( !is_null( $this->pstText
) ) {
289 $result_array['psttext'] = array();
290 $result->setContent( $result_array['psttext'], $this->pstText
);
294 $result_mapping = array(
297 'categories' => 'cl',
301 'externallinks' => 'el',
306 $this->setIndexedTagNames( $result_array, $result_mapping );
307 $result->addValue( null, $this->getModuleName(), $result_array );
309 if ( !is_null( $oldLang ) ) {
310 $wgLang = $oldLang; // Reset $wgLang to $oldLang
315 * @param $articleObj Article
316 * @param $titleObj Title
317 * @param $popts ParserOptions
319 * @param $getWikitext Bool
320 * @return ParserOutput
322 private function getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageId = null, $getWikitext = false ) {
323 if ( $this->section
!== false ) {
326 $this->text
= $this->getSectionText( $articleObj->getRawText(), !is_null( $pageId )
327 ?
'page id ' . $pageId : $titleObj->getText() );
329 // Not cached (save or load)
330 return $wgParser->parse( $this->text
, $titleObj, $popts );
332 // Try the parser cache first
333 // getParserOutput will save to Parser cache if able
334 $pout = $articleObj->getParserOutput();
335 if ( $getWikitext ) {
336 $rev = Revision
::newFromTitle( $titleObj );
338 $this->text
= $rev->getText();
345 private function getSectionText( $text, $what ) {
347 // Not cached (save or load)
348 $text = $wgParser->getSection( $text, $this->section
, false );
349 if ( $text === false ) {
350 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
355 private function formatLangLinks( $links ) {
357 foreach ( $links as $link ) {
359 $bits = explode( ':', $link, 2 );
360 $title = Title
::newFromText( $link );
362 $entry['lang'] = $bits[0];
364 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
366 $this->getResult()->setContent( $entry, $bits[1] );
372 private function formatCategoryLinks( $links ) {
374 foreach ( $links as $link => $sortkey ) {
376 $entry['sortkey'] = $sortkey;
377 $this->getResult()->setContent( $entry, $link );
383 private function categoriesHtml( $categories ) {
384 $context = $this->createContext();
385 $context->getOutput()->addCategoryLinks( $categories );
386 return $context->getSkin()->getCategories();
390 * @deprecated since 1.18 No modern skin generates language links this way, please use language links
391 * data to generate your own HTML.
393 private function languagesHtml( $languages ) {
394 global $wgContLang, $wgHideInterlanguageLinks;
396 if ( $wgHideInterlanguageLinks ||
count( $languages ) == 0 ) {
400 $s = htmlspecialchars( wfMsg( 'otherlanguages' ) . wfMsg( 'colon-separator' ) );
403 foreach ( $languages as $l ) {
404 $nt = Title
::newFromText( $l );
405 $text = $wgContLang->getLanguageName( $nt->getInterwiki() );
407 $langs[] = Html
::element( 'a',
408 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => "external" ),
409 $text == '' ?
$l : $text );
412 $s .= implode( htmlspecialchars( wfMsgExt( 'pipe-separator', 'escapenoentities' ) ), $langs );
414 if ( $wgContLang->isRTL() ) {
415 $s = Html
::rawElement( 'span', array( 'dir' => "LTR" ), $s );
421 private function formatLinks( $links ) {
423 foreach ( $links as $ns => $nslinks ) {
424 foreach ( $nslinks as $title => $id ) {
427 $this->getResult()->setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
429 $entry['exists'] = '';
437 private function formatIWLinks( $iw ) {
439 foreach ( $iw as $prefix => $titles ) {
440 foreach ( array_keys( $titles ) as $title ) {
442 $entry['prefix'] = $prefix;
444 $title = Title
::newFromText( "{$prefix}:{$title}" );
446 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
449 $this->getResult()->setContent( $entry, $title->getFullText() );
456 private function formatHeadItems( $headItems ) {
458 foreach ( $headItems as $tag => $content ) {
460 $entry['tag'] = $tag;
461 $this->getResult()->setContent( $entry, $content );
467 private function formatCss( $css ) {
469 foreach ( $css as $file => $link ) {
471 $entry['file'] = $file;
472 $this->getResult()->setContent( $entry, $link );
478 private function setIndexedTagNames( &$array, $mapping ) {
479 foreach ( $mapping as $key => $name ) {
480 if ( isset( $array[$key] ) ) {
481 $this->getResult()->setIndexedTagName( $array[$key], $name );
486 public function getAllowedParams() {
489 ApiBase
::PARAM_DFLT
=> 'API',
495 ApiBase
::PARAM_TYPE
=> 'integer',
497 'redirects' => false,
499 ApiBase
::PARAM_TYPE
=> 'integer',
502 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle',
503 ApiBase
::PARAM_ISMULTI
=> true,
504 ApiBase
::PARAM_TYPE
=> array(
527 'disablepp' => false,
531 public function getParamDescription() {
532 $p = $this->getModulePrefix();
534 'text' => 'Wikitext to parse',
535 'summary' => 'Summary to parse',
536 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
537 'title' => 'Title of page the text belongs to',
538 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
539 'pageid' => "Parse the content of this page. Overrides {$p}page",
540 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
542 'Which pieces of information to get',
543 ' text - Gives the parsed text of the wikitext',
544 ' langlinks - Gives the language links in the parsed wikitext',
545 ' categories - Gives the categories in the parsed wikitext',
546 ' categorieshtml - Gives the HTML version of the categories',
547 ' languageshtml - Gives the HTML version of the language links',
548 ' links - Gives the internal links in the parsed wikitext',
549 ' templates - Gives the templates in the parsed wikitext',
550 ' images - Gives the images in the parsed wikitext',
551 ' externallinks - Gives the external links in the parsed wikitext',
552 ' sections - Gives the sections in the parsed wikitext',
553 ' revid - Adds the revision ID of the parsed page',
554 ' displaytitle - Adds the title of the parsed wikitext',
555 ' headitems - Gives items to put in the <head> of the page',
556 ' headhtml - Gives parsed <head> of the page',
557 ' iwlinks - Gives interwiki links in the parsed wikitext',
558 ' wikitext - Gives the original wikitext that was parsed',
561 'Do a pre-save transform on the input before parsing it',
562 'Ignored if page, pageid or oldid is used'
565 'Do a pre-save transform (PST) on the input, but don\'t parse it',
566 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
568 'uselang' => 'Which language to parse the request in',
569 'section' => 'Only retrieve the content of this section number',
570 'disablepp' => 'Disable the PP Report from the parser output',
574 public function getDescription() {
575 return 'Parses wikitext and returns parser output';
578 public function getPossibleErrors() {
579 return array_merge( parent
::getPossibleErrors(), array(
580 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
581 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
582 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
583 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
584 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
585 array( 'nosuchpageid' ),
586 array( 'invalidtitle', 'title' ),
590 public function getExamples() {
592 'api.php?action=parse&text={{Project:Sandbox}}'
596 public function getHelpUrls() {
597 return 'http://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
600 public function getVersion() {
601 return __CLASS__
. ': $Id$';