correct typo in r102393
[mediawiki.git] / includes / api / ApiParse.php
blobb1e344c9137b958e048546a9730293700a2ce361
1 <?php
2 /**
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
22 * @file
25 if ( !defined( 'MEDIAWIKI' ) ) {
26 // Eclipse helper - will be ignored in production
27 require_once( "ApiBase.php" );
30 /**
31 * @ingroup API
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' );
44 // Get parameters
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'];
59 } else {
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
69 $oldLang = null;
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'] );
79 $redirValues = null;
81 // Return result
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 );
88 if ( !$rev ) {
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();
97 $wgTitle = $titleObj;
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'] ) {
120 $reqParams = array(
121 'action' => 'query',
122 'redirects' => '',
124 if ( !is_null ( $pageid ) ) {
125 $reqParams['pageids'] = $pageid;
126 } else { // $page
127 $reqParams['titles'] = $page;
129 $req = new FauxRequest( $reqParams );
130 $main = new ApiMain( $req );
131 $main->execute();
132 $data = $main->getResultData();
133 $redirValues = isset( $data['query']['redirects'] )
134 ? $data['query']['redirects']
135 : array();
136 $to = $page;
137 foreach ( (array)$redirValues as $r ) {
138 $to = $r['to'];
140 $titleObj = Title::newFromText( $to );
141 } else {
142 if ( !is_null ( $pageid ) ) {
143 $reqParams['pageids'] = $pageid;
144 $titleObj = Title::newFromID( $pageid );
145 } else { // $page
146 $to = $page;
147 $titleObj = Title::newFromText( $to );
150 if ( !is_null ( $pageid ) ) {
151 if ( !$titleObj ) {
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
171 $this->text = $text;
172 $titleObj = Title::newFromText( $title );
173 if ( !$titleObj ) {
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 );
195 return;
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(
296 'redirects' => 'r',
297 'langlinks' => 'll',
298 'categories' => 'cl',
299 'links' => 'pl',
300 'templates' => 'tl',
301 'images' => 'img',
302 'externallinks' => 'el',
303 'iwlinks' => 'iw',
304 'sections' => 's',
305 'headitems' => 'hi',
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
319 * @param $pageId Int
320 * @param $getWikitext Bool
321 * @return ParserOutput
323 private function getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageId = null, $getWikitext = false ) {
324 if ( $this->section !== false ) {
325 global $wgParser;
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 );
332 } else {
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 );
338 if ( $rev ) {
339 $this->text = $rev->getText();
342 return $pout;
346 private function getSectionText( $text, $what ) {
347 global $wgParser;
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' );
353 return $text;
356 private function formatLangLinks( $links ) {
357 $result = array();
358 foreach ( $links as $link ) {
359 $entry = array();
360 $bits = explode( ':', $link, 2 );
361 $title = Title::newFromText( $link );
363 $entry['lang'] = $bits[0];
364 if ( $title ) {
365 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
367 $this->getResult()->setContent( $entry, $bits[1] );
368 $result[] = $entry;
370 return $result;
373 private function formatCategoryLinks( $links ) {
374 $result = array();
375 foreach ( $links as $link => $sortkey ) {
376 $entry = array();
377 $entry['sortkey'] = $sortkey;
378 $this->getResult()->setContent( $entry, $link );
379 $result[] = $entry;
381 return $result;
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
394 * @return string
396 private function languagesHtml( $languages ) {
397 global $wgContLang, $wgHideInterlanguageLinks;
399 if ( $wgHideInterlanguageLinks || count( $languages ) == 0 ) {
400 return '';
403 $s = htmlspecialchars( wfMsg( 'otherlanguages' ) . wfMsg( 'colon-separator' ) );
405 $langs = array();
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 );
421 return $s;
424 private function formatLinks( $links ) {
425 $result = array();
426 foreach ( $links as $ns => $nslinks ) {
427 foreach ( $nslinks as $title => $id ) {
428 $entry = array();
429 $entry['ns'] = $ns;
430 $this->getResult()->setContent( $entry, Title::makeTitle( $ns, $title )->getFullText() );
431 if ( $id != 0 ) {
432 $entry['exists'] = '';
434 $result[] = $entry;
437 return $result;
440 private function formatIWLinks( $iw ) {
441 $result = array();
442 foreach ( $iw as $prefix => $titles ) {
443 foreach ( array_keys( $titles ) as $title ) {
444 $entry = array();
445 $entry['prefix'] = $prefix;
447 $title = Title::newFromText( "{$prefix}:{$title}" );
448 if ( $title ) {
449 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
452 $this->getResult()->setContent( $entry, $title->getFullText() );
453 $result[] = $entry;
456 return $result;
459 private function formatHeadItems( $headItems ) {
460 $result = array();
461 foreach ( $headItems as $tag => $content ) {
462 $entry = array();
463 $entry['tag'] = $tag;
464 $this->getResult()->setContent( $entry, $content );
465 $result[] = $entry;
467 return $result;
470 private function formatCss( $css ) {
471 $result = array();
472 foreach ( $css as $file => $link ) {
473 $entry = array();
474 $entry['file'] = $file;
475 $this->getResult()->setContent( $entry, $link );
476 $result[] = $entry;
478 return $result;
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() {
490 return array(
491 'title' => array(
492 ApiBase::PARAM_DFLT => 'API',
494 'text' => null,
495 'summary' => null,
496 'page' => null,
497 'pageid' => array(
498 ApiBase::PARAM_TYPE => 'integer',
500 'redirects' => false,
501 'oldid' => array(
502 ApiBase::PARAM_TYPE => 'integer',
504 'prop' => array(
505 ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle',
506 ApiBase::PARAM_ISMULTI => true,
507 ApiBase::PARAM_TYPE => array(
508 'text',
509 'langlinks',
510 'languageshtml',
511 'categories',
512 'categorieshtml',
513 'links',
514 'templates',
515 'images',
516 'externallinks',
517 'sections',
518 'revid',
519 'displaytitle',
520 'headitems',
521 'headhtml',
522 'iwlinks',
523 'wikitext',
526 'pst' => false,
527 'onlypst' => false,
528 'uselang' => null,
529 'section' => null,
530 'disablepp' => false,
534 public function getParamDescription() {
535 $p = $this->getModulePrefix();
536 return array(
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",
544 'prop' => array(
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',
563 'pst' => array(
564 'Do a pre-save transform on the input before parsing it',
565 'Ignored if page, pageid or oldid is used'
567 'onlypst' => array(
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' ),
590 ) );
593 public function getExamples() {
594 return array(
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$';