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 // TODO: Does this still need $wgTitle?
66 global $wgParser, $wgTitle, $wgLang;
68 // Currently unnecessary, code to act as a safeguard against any change in current behaviour of uselang breaks
70 if ( isset( $params['uselang'] ) && $params['uselang'] != $wgLang->getCode() ) {
71 $oldLang = $wgLang; // Backup wgLang
72 $wgLang = Language
::factory( $params['uselang'] );
75 $popts = new ParserOptions();
76 $popts->setTidy( true );
77 $popts->enableLimitReport( !$params['disablepp'] );
82 $result = $this->getResult();
84 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 // May get from/save to parser cache
104 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
105 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 // Should we save old revision parses to the parser cache?
116 $p_result = $wgParser->parse( $this->text
, $titleObj, $popts );
118 } else { // Not $oldid, but $pageid or $page
119 if ( $params['redirects'] ) {
124 if ( !is_null ( $pageid ) ) {
125 $reqParams['pageids'] = $pageid;
127 $reqParams['titles'] = $page;
129 $req = new FauxRequest( $reqParams );
130 $main = new ApiMain( $req );
132 $data = $main->getResultData();
133 $redirValues = isset( $data['query']['redirects'] )
134 ?
$data['query']['redirects']
137 foreach ( (array)$redirValues as $r ) {
140 $titleObj = Title
::newFromText( $to );
142 if ( !is_null ( $pageid ) ) {
143 $reqParams['pageids'] = $pageid;
144 $titleObj = Title
::newFromID( $pageid );
147 $titleObj = Title
::newFromText( $to );
150 if ( !is_null ( $pageid ) ) {
152 // Still throw nosuchpageid error if pageid was provided
153 $this->dieUsageMsg( array( 'nosuchpageid', $pageid ) );
155 } elseif ( !$titleObj ||
!$titleObj->exists() ) {
156 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
158 $wgTitle = $titleObj;
160 $articleObj = new Article( $titleObj, 0 );
161 if ( isset( $prop['revid'] ) ) {
162 $oldid = $articleObj->getRevIdFetched();
165 // Potentially cached
166 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
167 isset( $prop['wikitext'] ) ) ;
169 } else { // Not $oldid, $pageid, $page. Hence based on $text
172 $titleObj = Title
::newFromText( $title );
174 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
176 $wgTitle = $titleObj;
178 if ( $this->section
!== false ) {
179 $this->text
= $this->getSectionText( $this->text
, $titleObj->getText() );
182 if ( $params['pst'] ||
$params['onlypst'] ) {
183 $this->pstText
= $wgParser->preSaveTransform( $this->text
, $titleObj, $this->getUser(), $popts );
185 if ( $params['onlypst'] ) {
186 // Build a result and bail out
187 $result_array = array();
188 $result_array['text'] = array();
189 $result->setContent( $result_array['text'], $this->pstText
);
190 if ( isset( $prop['wikitext'] ) ) {
191 $result_array['wikitext'] = array();
192 $result->setContent( $result_array['wikitext'], $this->text
);
194 $result->addValue( null, $this->getModuleName(), $result_array );
197 // Not cached (save or load)
198 $p_result = $wgParser->parse( $params['pst'] ?
$this->pstText
: $this->text
, $titleObj, $popts );
201 $result_array = array();
203 $result_array['title'] = $titleObj->getPrefixedText();
205 if ( !is_null( $oldid ) ) {
206 $result_array['revid'] = intval( $oldid );
209 if ( $params['redirects'] && !is_null( $redirValues ) ) {
210 $result_array['redirects'] = $redirValues;
213 if ( isset( $prop['text'] ) ) {
214 $result_array['text'] = array();
215 $result->setContent( $result_array['text'], $p_result->getText() );
218 if ( !is_null( $params['summary'] ) ) {
219 $result_array['parsedsummary'] = array();
220 $result->setContent( $result_array['parsedsummary'], Linker
::formatComment( $params['summary'], $titleObj ) );
223 if ( isset( $prop['langlinks'] ) ) {
224 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
226 if ( isset( $prop['languageshtml'] ) ) {
227 $languagesHtml = $this->languagesHtml( $p_result->getLanguageLinks() );
228 $result_array['languageshtml'] = array();
229 $result->setContent( $result_array['languageshtml'], $languagesHtml );
231 if ( isset( $prop['categories'] ) ) {
232 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
234 if ( isset( $prop['categorieshtml'] ) ) {
235 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
236 $result_array['categorieshtml'] = array();
237 $result->setContent( $result_array['categorieshtml'], $categoriesHtml );
239 if ( isset( $prop['links'] ) ) {
240 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
242 if ( isset( $prop['templates'] ) ) {
243 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
245 if ( isset( $prop['images'] ) ) {
246 $result_array['images'] = array_keys( $p_result->getImages() );
248 if ( isset( $prop['externallinks'] ) ) {
249 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
251 if ( isset( $prop['sections'] ) ) {
252 $result_array['sections'] = $p_result->getSections();
255 if ( isset( $prop['displaytitle'] ) ) {
256 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
257 $p_result->getDisplayTitle() :
258 $titleObj->getPrefixedText();
261 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
262 $context = $this->getContext();
263 $context->setTitle( $titleObj );
264 $context->getOutput()->addParserOutputNoText( $p_result );
266 if ( isset( $prop['headitems'] ) ) {
267 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
269 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
271 $scripts = array( $context->getOutput()->getHeadScripts() );
273 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
276 if ( isset( $prop['headhtml'] ) ) {
277 $result_array['headhtml'] = array();
278 $result->setContent( $result_array['headhtml'], $context->getOutput()->headElement( $context->getSkin() ) );
282 if ( isset( $prop['iwlinks'] ) ) {
283 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
286 if ( isset( $prop['wikitext'] ) ) {
287 $result_array['wikitext'] = array();
288 $result->setContent( $result_array['wikitext'], $this->text
);
289 if ( !is_null( $this->pstText
) ) {
290 $result_array['psttext'] = array();
291 $result->setContent( $result_array['psttext'], $this->pstText
);
295 $result_mapping = array(
298 'categories' => 'cl',
302 'externallinks' => 'el',
307 $this->setIndexedTagNames( $result_array, $result_mapping );
308 $result->addValue( null, $this->getModuleName(), $result_array );
310 if ( !is_null( $oldLang ) ) {
311 $wgLang = $oldLang; // Reset $wgLang to $oldLang
316 * @param $articleObj Article
317 * @param $titleObj Title
318 * @param $popts ParserOptions
320 * @param $getWikitext Bool
321 * @return ParserOutput
323 private function getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageId = null, $getWikitext = false ) {
324 if ( $this->section
!== false ) {
327 $this->text
= $this->getSectionText( $articleObj->getRawText(), !is_null( $pageId )
328 ?
'page id ' . $pageId : $titleObj->getText() );
330 // Not cached (save or load)
331 return $wgParser->parse( $this->text
, $titleObj, $popts );
333 // Try the parser cache first
334 // getParserOutput will save to Parser cache if able
335 $pout = $articleObj->getParserOutput();
336 if ( $getWikitext ) {
337 $rev = Revision
::newFromTitle( $titleObj );
339 $this->text
= $rev->getText();
346 private function getSectionText( $text, $what ) {
348 // Not cached (save or load)
349 $text = $wgParser->getSection( $text, $this->section
, false );
350 if ( $text === false ) {
351 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
356 private function formatLangLinks( $links ) {
358 foreach ( $links as $link ) {
360 $bits = explode( ':', $link, 2 );
361 $title = Title
::newFromText( $link );
363 $entry['lang'] = $bits[0];
365 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
367 $this->getResult()->setContent( $entry, $bits[1] );
373 private function formatCategoryLinks( $links ) {
375 foreach ( $links as $link => $sortkey ) {
377 $entry['sortkey'] = $sortkey;
378 $this->getResult()->setContent( $entry, $link );
384 private function categoriesHtml( $categories ) {
385 $context = $this->getContext();
386 $context->getOutput()->addCategoryLinks( $categories );
387 return $context->getSkin()->getCategories();
391 * @deprecated since 1.18 No modern skin generates language links this way, please use language links
392 * data to generate your own HTML.
393 * @param $languages array
396 private function languagesHtml( $languages ) {
397 global $wgContLang, $wgHideInterlanguageLinks;
399 if ( $wgHideInterlanguageLinks ||
count( $languages ) == 0 ) {
403 $s = htmlspecialchars( wfMsg( 'otherlanguages' ) . wfMsg( 'colon-separator' ) );
406 foreach ( $languages as $l ) {
407 $nt = Title
::newFromText( $l );
408 $text = $wgContLang->getLanguageName( $nt->getInterwiki() );
410 $langs[] = Html
::element( 'a',
411 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => "external" ),
412 $text == '' ?
$l : $text );
415 $s .= implode( htmlspecialchars( wfMsgExt( 'pipe-separator', 'escapenoentities' ) ), $langs );
417 if ( $wgContLang->isRTL() ) {
418 $s = Html
::rawElement( 'span', array( 'dir' => "LTR" ), $s );
424 private function formatLinks( $links ) {
426 foreach ( $links as $ns => $nslinks ) {
427 foreach ( $nslinks as $title => $id ) {
430 $this->getResult()->setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
432 $entry['exists'] = '';
440 private function formatIWLinks( $iw ) {
442 foreach ( $iw as $prefix => $titles ) {
443 foreach ( array_keys( $titles ) as $title ) {
445 $entry['prefix'] = $prefix;
447 $title = Title
::newFromText( "{$prefix}:{$title}" );
449 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
452 $this->getResult()->setContent( $entry, $title->getFullText() );
459 private function formatHeadItems( $headItems ) {
461 foreach ( $headItems as $tag => $content ) {
463 $entry['tag'] = $tag;
464 $this->getResult()->setContent( $entry, $content );
470 private function formatCss( $css ) {
472 foreach ( $css as $file => $link ) {
474 $entry['file'] = $file;
475 $this->getResult()->setContent( $entry, $link );
481 private function setIndexedTagNames( &$array, $mapping ) {
482 foreach ( $mapping as $key => $name ) {
483 if ( isset( $array[$key] ) ) {
484 $this->getResult()->setIndexedTagName( $array[$key], $name );
489 public function getAllowedParams() {
492 ApiBase
::PARAM_DFLT
=> 'API',
498 ApiBase
::PARAM_TYPE
=> 'integer',
500 'redirects' => false,
502 ApiBase
::PARAM_TYPE
=> 'integer',
505 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle',
506 ApiBase
::PARAM_ISMULTI
=> true,
507 ApiBase
::PARAM_TYPE
=> array(
530 'disablepp' => false,
534 public function getParamDescription() {
535 $p = $this->getModulePrefix();
537 'text' => 'Wikitext to parse',
538 'summary' => 'Summary to parse',
539 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
540 'title' => 'Title of page the text belongs to',
541 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
542 'pageid' => "Parse the content of this page. Overrides {$p}page",
543 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
545 'Which pieces of information to get',
546 ' text - Gives the parsed text of the wikitext',
547 ' langlinks - Gives the language links in the parsed wikitext',
548 ' categories - Gives the categories in the parsed wikitext',
549 ' categorieshtml - Gives the HTML version of the categories',
550 ' languageshtml - Gives the HTML version of the language links',
551 ' links - Gives the internal links in the parsed wikitext',
552 ' templates - Gives the templates in the parsed wikitext',
553 ' images - Gives the images in the parsed wikitext',
554 ' externallinks - Gives the external links in the parsed wikitext',
555 ' sections - Gives the sections in the parsed wikitext',
556 ' revid - Adds the revision ID of the parsed page',
557 ' displaytitle - Adds the title of the parsed wikitext',
558 ' headitems - Gives items to put in the <head> of the page',
559 ' headhtml - Gives parsed <head> of the page',
560 ' iwlinks - Gives interwiki links in the parsed wikitext',
561 ' wikitext - Gives the original wikitext that was parsed',
564 'Do a pre-save transform on the input before parsing it',
565 'Ignored if page, pageid or oldid is used'
568 'Do a pre-save transform (PST) on the input, but don\'t parse it',
569 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
571 'uselang' => 'Which language to parse the request in',
572 'section' => 'Only retrieve the content of this section number',
573 'disablepp' => 'Disable the PP Report from the parser output',
577 public function getDescription() {
578 return 'Parses wikitext and returns parser output';
581 public function getPossibleErrors() {
582 return array_merge( parent
::getPossibleErrors(), array(
583 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
584 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
585 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
586 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
587 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
588 array( 'nosuchpageid' ),
589 array( 'invalidtitle', 'title' ),
593 public function getExamples() {
595 'api.php?action=parse&text={{Project:Sandbox}}'
599 public function getHelpUrls() {
600 return 'http://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
603 public function getVersion() {
604 return __CLASS__
. ': $Id$';