26ad39a0e4cbfe69e6be5463030b5680221540a1
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
{
29 private $section, $text, $pstText = null;
31 public function __construct( $main, $action ) {
32 parent
::__construct( $main, $action );
35 public function execute() {
36 // The data is hot but user-dependent, like page views, so we set vary cookies
37 $this->getMain()->setCacheMode( 'anon-public-user-private' );
40 $params = $this->extractRequestParams();
41 $text = $params['text'];
42 $title = $params['title'];
43 $page = $params['page'];
44 $pageid = $params['pageid'];
45 $oldid = $params['oldid'];
47 if ( !is_null( $page ) && ( !is_null( $text ) ||
$title != 'API' ) ) {
48 $this->dieUsage( 'The page parameter cannot be used together with the text and title parameters', 'params' );
50 $prop = array_flip( $params['prop'] );
52 if ( isset( $params['section'] ) ) {
53 $this->section
= $params['section'];
55 $this->section
= false;
58 // The parser needs $wgTitle to be set, apparently the
59 // $title parameter in Parser::parse isn't enough *sigh*
60 // TODO: Does this still need $wgTitle?
61 global $wgParser, $wgTitle, $wgLang;
63 // Currently unnecessary, code to act as a safeguard against any change in current behaviour of uselang breaks
65 if ( isset( $params['uselang'] ) && $params['uselang'] != $wgLang->getCode() ) {
66 $oldLang = $wgLang; // Backup wgLang
67 $wgLang = Language
::factory( $params['uselang'] );
70 $popts = new ParserOptions();
71 $popts->setTidy( true );
72 $popts->enableLimitReport( !$params['disablepp'] );
77 $result = $this->getResult();
79 if ( !is_null( $oldid ) ||
!is_null( $pageid ) ||
!is_null( $page ) ) {
80 if ( !is_null( $oldid ) ) {
81 // Don't use the parser cache
82 $rev = Revision
::newFromID( $oldid );
84 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
86 if ( !$rev->userCan( Revision
::DELETED_TEXT
) ) {
87 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
90 $titleObj = $rev->getTitle();
94 // If for some reason the "oldid" is actually the current revision, it may be cached
95 if ( $titleObj->getLatestRevID() === intval( $oldid ) ) {
96 $articleObj = new Article( $titleObj, 0 );
98 // May get from/save to parser cache
99 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
100 isset( $prop['wikitext'] ) ) ;
101 } else { // This is an old revision, so get the text differently
102 $this->text
= $rev->getText( Revision
::FOR_THIS_USER
);
104 $wgTitle = $titleObj;
106 if ( $this->section
!== false ) {
107 $this->text
= $this->getSectionText( $this->text
, 'r' . $rev->getId() );
110 // Should we save old revision parses to the parser cache?
111 $p_result = $wgParser->parse( $this->text
, $titleObj, $popts );
113 } else { // Not $oldid, but $pageid or $page
114 if ( $params['redirects'] ) {
119 if ( !is_null ( $pageid ) ) {
120 $reqParams['pageids'] = $pageid;
122 $reqParams['titles'] = $page;
124 $req = new FauxRequest( $reqParams );
125 $main = new ApiMain( $req );
127 $data = $main->getResultData();
128 $redirValues = isset( $data['query']['redirects'] )
129 ?
$data['query']['redirects']
132 foreach ( (array)$redirValues as $r ) {
135 $titleObj = Title
::newFromText( $to );
137 if ( !is_null ( $pageid ) ) {
138 $reqParams['pageids'] = $pageid;
139 $titleObj = Title
::newFromID( $pageid );
142 $titleObj = Title
::newFromText( $to );
145 if ( !is_null ( $pageid ) ) {
147 // Still throw nosuchpageid error if pageid was provided
148 $this->dieUsageMsg( array( 'nosuchpageid', $pageid ) );
150 } elseif ( !$titleObj ||
!$titleObj->exists() ) {
151 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
153 $wgTitle = $titleObj;
155 $articleObj = new Article( $titleObj, 0 );
156 if ( isset( $prop['revid'] ) ) {
157 $oldid = $articleObj->getRevIdFetched();
160 // Potentially cached
161 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
162 isset( $prop['wikitext'] ) ) ;
164 } else { // Not $oldid, $pageid, $page. Hence based on $text
167 $titleObj = Title
::newFromText( $title );
169 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
171 $wgTitle = $titleObj;
173 if ( $this->section
!== false ) {
174 $this->text
= $this->getSectionText( $this->text
, $titleObj->getText() );
177 if ( $params['pst'] ||
$params['onlypst'] ) {
178 $this->pstText
= $wgParser->preSaveTransform( $this->text
, $titleObj, $this->getUser(), $popts );
180 if ( $params['onlypst'] ) {
181 // Build a result and bail out
182 $result_array = array();
183 $result_array['text'] = array();
184 $result->setContent( $result_array['text'], $this->pstText
);
185 if ( isset( $prop['wikitext'] ) ) {
186 $result_array['wikitext'] = array();
187 $result->setContent( $result_array['wikitext'], $this->text
);
189 $result->addValue( null, $this->getModuleName(), $result_array );
192 // Not cached (save or load)
193 $p_result = $wgParser->parse( $params['pst'] ?
$this->pstText
: $this->text
, $titleObj, $popts );
196 $result_array = array();
198 $result_array['title'] = $titleObj->getPrefixedText();
200 if ( !is_null( $oldid ) ) {
201 $result_array['revid'] = intval( $oldid );
204 if ( $params['redirects'] && !is_null( $redirValues ) ) {
205 $result_array['redirects'] = $redirValues;
208 if ( isset( $prop['text'] ) ) {
209 $result_array['text'] = array();
210 $result->setContent( $result_array['text'], $p_result->getText() );
213 if ( !is_null( $params['summary'] ) ) {
214 $result_array['parsedsummary'] = array();
215 $result->setContent( $result_array['parsedsummary'], Linker
::formatComment( $params['summary'], $titleObj ) );
218 if ( isset( $prop['langlinks'] ) ) {
219 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
221 if ( isset( $prop['languageshtml'] ) ) {
222 $languagesHtml = $this->languagesHtml( $p_result->getLanguageLinks() );
223 $result_array['languageshtml'] = array();
224 $result->setContent( $result_array['languageshtml'], $languagesHtml );
226 if ( isset( $prop['categories'] ) ) {
227 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
229 if ( isset( $prop['categorieshtml'] ) ) {
230 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
231 $result_array['categorieshtml'] = array();
232 $result->setContent( $result_array['categorieshtml'], $categoriesHtml );
234 if ( isset( $prop['links'] ) ) {
235 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
237 if ( isset( $prop['templates'] ) ) {
238 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
240 if ( isset( $prop['images'] ) ) {
241 $result_array['images'] = array_keys( $p_result->getImages() );
243 if ( isset( $prop['externallinks'] ) ) {
244 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
246 if ( isset( $prop['sections'] ) ) {
247 $result_array['sections'] = $p_result->getSections();
250 if ( isset( $prop['displaytitle'] ) ) {
251 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
252 $p_result->getDisplayTitle() :
253 $titleObj->getPrefixedText();
256 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
257 $context = $this->getContext();
258 $context->setTitle( $titleObj );
259 $context->getOutput()->addParserOutputNoText( $p_result );
261 if ( isset( $prop['headitems'] ) ) {
262 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
264 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
266 $scripts = array( $context->getOutput()->getHeadScripts() );
268 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
271 if ( isset( $prop['headhtml'] ) ) {
272 $result_array['headhtml'] = array();
273 $result->setContent( $result_array['headhtml'], $context->getOutput()->headElement( $context->getSkin() ) );
277 if ( isset( $prop['iwlinks'] ) ) {
278 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
281 if ( isset( $prop['wikitext'] ) ) {
282 $result_array['wikitext'] = array();
283 $result->setContent( $result_array['wikitext'], $this->text
);
284 if ( !is_null( $this->pstText
) ) {
285 $result_array['psttext'] = array();
286 $result->setContent( $result_array['psttext'], $this->pstText
);
290 $result_mapping = array(
293 'categories' => 'cl',
297 'externallinks' => 'el',
302 $this->setIndexedTagNames( $result_array, $result_mapping );
303 $result->addValue( null, $this->getModuleName(), $result_array );
305 if ( !is_null( $oldLang ) ) {
306 $wgLang = $oldLang; // Reset $wgLang to $oldLang
311 * @param $articleObj Article
312 * @param $titleObj Title
313 * @param $popts ParserOptions
315 * @param $getWikitext Bool
316 * @return ParserOutput
318 private function getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageId = null, $getWikitext = false ) {
319 if ( $this->section
!== false ) {
322 $this->text
= $this->getSectionText( $articleObj->getRawText(), !is_null( $pageId )
323 ?
'page id ' . $pageId : $titleObj->getText() );
325 // Not cached (save or load)
326 return $wgParser->parse( $this->text
, $titleObj, $popts );
328 // Try the parser cache first
329 // getParserOutput will save to Parser cache if able
330 $pout = $articleObj->getParserOutput();
331 if ( $getWikitext ) {
332 $rev = Revision
::newFromTitle( $titleObj );
334 $this->text
= $rev->getText();
341 private function getSectionText( $text, $what ) {
343 // Not cached (save or load)
344 $text = $wgParser->getSection( $text, $this->section
, false );
345 if ( $text === false ) {
346 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
351 private function formatLangLinks( $links ) {
353 foreach ( $links as $link ) {
355 $bits = explode( ':', $link, 2 );
356 $title = Title
::newFromText( $link );
358 $entry['lang'] = $bits[0];
360 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
362 $this->getResult()->setContent( $entry, $bits[1] );
368 private function formatCategoryLinks( $links ) {
370 foreach ( $links as $link => $sortkey ) {
372 $entry['sortkey'] = $sortkey;
373 $this->getResult()->setContent( $entry, $link );
379 private function categoriesHtml( $categories ) {
380 $context = $this->getContext();
381 $context->getOutput()->addCategoryLinks( $categories );
382 return $context->getSkin()->getCategories();
386 * @deprecated since 1.18 No modern skin generates language links this way, please use language links
387 * data to generate your own HTML.
388 * @param $languages array
391 private function languagesHtml( $languages ) {
392 global $wgContLang, $wgHideInterlanguageLinks;
394 if ( $wgHideInterlanguageLinks ||
count( $languages ) == 0 ) {
398 $s = htmlspecialchars( wfMsg( 'otherlanguages' ) . wfMsg( 'colon-separator' ) );
401 foreach ( $languages as $l ) {
402 $nt = Title
::newFromText( $l );
403 $text = $wgContLang->getLanguageName( $nt->getInterwiki() );
405 $langs[] = Html
::element( 'a',
406 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => "external" ),
407 $text == '' ?
$l : $text );
410 $s .= implode( htmlspecialchars( wfMsgExt( 'pipe-separator', 'escapenoentities' ) ), $langs );
412 if ( $wgContLang->isRTL() ) {
413 $s = Html
::rawElement( 'span', array( 'dir' => "LTR" ), $s );
419 private function formatLinks( $links ) {
421 foreach ( $links as $ns => $nslinks ) {
422 foreach ( $nslinks as $title => $id ) {
425 $this->getResult()->setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
427 $entry['exists'] = '';
435 private function formatIWLinks( $iw ) {
437 foreach ( $iw as $prefix => $titles ) {
438 foreach ( array_keys( $titles ) as $title ) {
440 $entry['prefix'] = $prefix;
442 $title = Title
::newFromText( "{$prefix}:{$title}" );
444 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
447 $this->getResult()->setContent( $entry, $title->getFullText() );
454 private function formatHeadItems( $headItems ) {
456 foreach ( $headItems as $tag => $content ) {
458 $entry['tag'] = $tag;
459 $this->getResult()->setContent( $entry, $content );
465 private function formatCss( $css ) {
467 foreach ( $css as $file => $link ) {
469 $entry['file'] = $file;
470 $this->getResult()->setContent( $entry, $link );
476 private function setIndexedTagNames( &$array, $mapping ) {
477 foreach ( $mapping as $key => $name ) {
478 if ( isset( $array[$key] ) ) {
479 $this->getResult()->setIndexedTagName( $array[$key], $name );
484 public function getAllowedParams() {
487 ApiBase
::PARAM_DFLT
=> 'API',
493 ApiBase
::PARAM_TYPE
=> 'integer',
495 'redirects' => false,
497 ApiBase
::PARAM_TYPE
=> 'integer',
500 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle',
501 ApiBase
::PARAM_ISMULTI
=> true,
502 ApiBase
::PARAM_TYPE
=> array(
525 'disablepp' => false,
529 public function getParamDescription() {
530 $p = $this->getModulePrefix();
532 'text' => 'Wikitext to parse',
533 'summary' => 'Summary to parse',
534 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
535 'title' => 'Title of page the text belongs to',
536 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
537 'pageid' => "Parse the content of this page. Overrides {$p}page",
538 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
540 'Which pieces of information to get',
541 ' text - Gives the parsed text of the wikitext',
542 ' langlinks - Gives the language links in the parsed wikitext',
543 ' categories - Gives the categories in the parsed wikitext',
544 ' categorieshtml - Gives the HTML version of the categories',
545 ' languageshtml - Gives the HTML version of the language links',
546 ' links - Gives the internal links in the parsed wikitext',
547 ' templates - Gives the templates in the parsed wikitext',
548 ' images - Gives the images in the parsed wikitext',
549 ' externallinks - Gives the external links in the parsed wikitext',
550 ' sections - Gives the sections in the parsed wikitext',
551 ' revid - Adds the revision ID of the parsed page',
552 ' displaytitle - Adds the title of the parsed wikitext',
553 ' headitems - Gives items to put in the <head> of the page',
554 ' headhtml - Gives parsed <head> of the page',
555 ' iwlinks - Gives interwiki links in the parsed wikitext',
556 ' wikitext - Gives the original wikitext that was parsed',
559 'Do a pre-save transform on the input before parsing it',
560 'Ignored if page, pageid or oldid is used'
563 'Do a pre-save transform (PST) on the input, but don\'t parse it',
564 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
566 'uselang' => 'Which language to parse the request in',
567 'section' => 'Only retrieve the content of this section number',
568 'disablepp' => 'Disable the PP Report from the parser output',
572 public function getDescription() {
573 return 'Parses wikitext and returns parser output';
576 public function getPossibleErrors() {
577 return array_merge( parent
::getPossibleErrors(), array(
578 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
579 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
580 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
581 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
582 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
583 array( 'nosuchpageid' ),
584 array( 'invalidtitle', 'title' ),
588 public function getExamples() {
590 'api.php?action=parse&text={{Project:Sandbox}}'
594 public function getHelpUrls() {
595 return 'http://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
598 public function getVersion() {
599 return __CLASS__
. ': $Id$';