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
{
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 ) ;
105 } else { // This is an old revision, so get the text differently
106 $text = $rev->getText( Revision
::FOR_THIS_USER
);
108 $wgTitle = $titleObj;
110 if ( $this->section
!== false ) {
111 $text = $this->getSectionText( $text, 'r' . $rev->getId() );
114 $p_result = $wgParser->parse( $text, $titleObj, $popts );
117 } else { // Not $oldid
119 if ( !is_null ( $pageid ) ) {
120 $titleObj = Title
::newFromID( $pageid );
123 $this->dieUsageMsg( array( 'nosuchpageid', $pageid ) );
127 if ( $params['redirects'] ) {
128 $req = new FauxRequest( array(
133 $main = new ApiMain( $req );
135 $data = $main->getResultData();
136 $redirValues = @$data['query']['redirects'];
138 foreach ( (array)$redirValues as $r ) {
144 $titleObj = Title
::newFromText( $to );
145 if ( !$titleObj ||
!$titleObj->exists() ) {
146 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
149 $wgTitle = $titleObj;
151 $articleObj = new Article( $titleObj, 0 );
152 if ( isset( $prop['revid'] ) ) {
153 $oldid = $articleObj->getRevIdFetched();
156 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid ) ;
159 } else { // Not $oldid, $pageid, $page. Hence based on $text
161 $titleObj = Title
::newFromText( $title );
163 $titleObj = Title
::newFromText( 'API' );
165 $wgTitle = $titleObj;
167 if ( $this->section
!== false ) {
168 $text = $this->getSectionText( $text, $titleObj->getText() );
171 if ( $params['pst'] ||
$params['onlypst'] ) {
172 $text = $wgParser->preSaveTransform( $text, $titleObj, $wgUser, $popts );
174 if ( $params['onlypst'] ) {
175 // Build a result and bail out
176 $result_array['text'] = array();
177 $this->getResult()->setContent( $result_array['text'], $text );
178 $this->getResult()->addValue( null, $this->getModuleName(), $result_array );
181 $p_result = $wgParser->parse( $text, $titleObj, $popts );
185 $result = $this->getResult();
186 $result_array = array();
188 $result_array['title'] = $titleObj->getPrefixedText();
190 if ( !is_null( $oldid ) ) {
191 $result_array['revid'] = intval( $oldid );
194 if ( $params['redirects'] && !is_null( $redirValues ) ) {
195 $result_array['redirects'] = $redirValues;
198 if ( isset( $prop['text'] ) ) {
199 $result_array['text'] = array();
200 $result->setContent( $result_array['text'], $p_result->getText() );
203 if ( !is_null( $params['summary'] ) ) {
204 $result_array['parsedsummary'] = array();
205 $result->setContent( $result_array['parsedsummary'], $wgUser->getSkin()->formatComment( $params['summary'], $titleObj ) );
208 if ( isset( $prop['langlinks'] ) ) {
209 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
211 if ( isset( $prop['languageshtml'] ) ) {
212 $languagesHtml = $this->languagesHtml( $p_result->getLanguageLinks() );
213 $result_array['languageshtml'] = array();
214 $result->setContent( $result_array['languageshtml'], $languagesHtml );
216 if ( isset( $prop['categories'] ) ) {
217 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
219 if ( isset( $prop['categorieshtml'] ) ) {
220 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
221 $result_array['categorieshtml'] = array();
222 $result->setContent( $result_array['categorieshtml'], $categoriesHtml );
224 if ( isset( $prop['links'] ) ) {
225 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
227 if ( isset( $prop['templates'] ) ) {
228 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
230 if ( isset( $prop['images'] ) ) {
231 $result_array['images'] = array_keys( $p_result->getImages() );
233 if ( isset( $prop['externallinks'] ) ) {
234 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
236 if ( isset( $prop['sections'] ) ) {
237 $result_array['sections'] = $p_result->getSections();
240 if ( isset( $prop['displaytitle'] ) ) {
241 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
242 $p_result->getDisplayTitle() :
243 $titleObj->getPrefixedText();
246 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
247 $out = new OutputPage
;
248 $out->addParserOutputNoText( $p_result );
249 $userSkin = $wgUser->getSkin();
252 if ( isset( $prop['headitems'] ) ) {
253 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
255 $userSkin->setupUserCss( $out );
256 $css = $this->formatCss( $out->buildCssLinksArray() );
258 $scripts = array( $out->getHeadScripts( $userSkin ) );
260 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
263 if ( isset( $prop['headhtml'] ) ) {
264 $result_array['headhtml'] = array();
265 $result->setContent( $result_array['headhtml'], $out->headElement( $userSkin ) );
268 if ( isset( $prop['iwlinks'] ) ) {
269 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
272 $result_mapping = array(
275 'categories' => 'cl',
279 'externallinks' => 'el',
284 $this->setIndexedTagNames( $result_array, $result_mapping );
285 $result->addValue( null, $this->getModuleName(), $result_array );
287 if ( !is_null( $oldLang ) ) {
288 $wgLang = $oldLang; // Reset $wgLang to $oldLang
293 * @param $articleObj Article
294 * @param $titleObj Title
295 * @param $popts ParserOptions
297 * @return ParserOutput
299 private function getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageId = null ) {
300 if ( $this->section
!== false ) {
303 $text = $this->getSectionText( $articleObj->getRawText(), !is_null ( $pageId )
304 ?
'page id ' . $pageId : $titleObj->getText() );
306 return $wgParser->parse( $text, $titleObj, $popts );
308 // Try the parser cache first
309 return $articleObj->getParserOutput();
313 private function getSectionText( $text, $what ) {
315 $text = $wgParser->getSection( $text, $this->section
, false );
316 if ( $text === false ) {
317 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
322 private function formatLangLinks( $links ) {
324 foreach ( $links as $link ) {
326 $bits = explode( ':', $link, 2 );
327 $entry['lang'] = $bits[0];
328 $this->getResult()->setContent( $entry, $bits[1] );
334 private function formatCategoryLinks( $links ) {
336 foreach ( $links as $link => $sortkey ) {
338 $entry['sortkey'] = $sortkey;
339 $this->getResult()->setContent( $entry, $link );
345 private function categoriesHtml( $categories ) {
346 global $wgOut, $wgUser;
347 $wgOut->addCategoryLinks( $categories );
348 $sk = $wgUser->getSkin();
349 return $sk->getCategories();
352 private function languagesHtml( $languages ) {
353 global $wgOut, $wgUser;
354 $wgOut->setLanguageLinks( $languages );
355 $sk = $wgUser->getSkin();
356 return $sk->otherLanguages();
359 private function formatLinks( $links ) {
361 foreach ( $links as $ns => $nslinks ) {
362 foreach ( $nslinks as $title => $id ) {
365 $this->getResult()->setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
367 $entry['exists'] = '';
375 private function formatIWLinks( $iw ) {
377 foreach ( $iw as $prefix => $titles ) {
378 foreach ( array_keys( $titles ) as $title ) {
380 $entry['prefix'] = $prefix;
382 $title = Title
::newFromText( "{$prefix}:{$title}" );
384 $entry['url'] = $title->getFullURL();
387 $this->getResult()->setContent( $entry, $title->getFullText() );
394 private function formatHeadItems( $headItems ) {
396 foreach ( $headItems as $tag => $content ) {
398 $entry['tag'] = $tag;
399 $this->getResult()->setContent( $entry, $content );
405 private function formatCss( $css ) {
407 foreach ( $css as $file => $link ) {
409 $entry['file'] = $file;
410 $this->getResult()->setContent( $entry, $link );
416 private function setIndexedTagNames( &$array, $mapping ) {
417 foreach ( $mapping as $key => $name ) {
418 if ( isset( $array[$key] ) ) {
419 $this->getResult()->setIndexedTagName( $array[$key], $name );
424 public function getAllowedParams() {
427 ApiBase
::PARAM_DFLT
=> 'API',
433 'redirects' => false,
436 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle',
437 ApiBase
::PARAM_ISMULTI
=> true,
438 ApiBase
::PARAM_TYPE
=> array(
460 'disablepp' => false,
464 public function getParamDescription() {
465 $p = $this->getModulePrefix();
467 'text' => 'Wikitext to parse',
468 'summary' => 'Summary to parse',
469 'redirects' => "If the {$p}page parameter is set to a redirect, resolve it",
470 'title' => 'Title of page the text belongs to',
471 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
472 'pageid' => "Parse the content of this page. Overrides {$p}page",
473 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
475 'Which pieces of information to get',
476 ' text - Gives the parsed text of the wikitext',
477 ' langlinks - Gives the language links in the parsed wikitext',
478 ' categories - Gives the categories in the parsed wikitext',
479 ' categorieshtml - Gives the HTML version of the categories',
480 ' languageshtml - Gives the HTML version of the language links',
481 ' links - Gives the internal links in the parsed wikitext',
482 ' templates - Gives the templates in the parsed wikitext',
483 ' images - Gives the images in the parsed wikitext',
484 ' externallinks - Gives the external links in the parsed wikitext',
485 ' sections - Gives the sections in the parsed wikitext',
486 ' revid - Adds the revision ID of the parsed page',
487 ' displaytitle - Adds the title of the parsed wikitext',
488 ' headitems - Gives items to put in the <head> of the page',
489 ' headhtml - Gives parsed <head> of the page',
490 ' iwlinks - Gives interwiki links in the parsed wikitext',
491 'NOTE: Section tree is only generated if there are more than 4 sections, or if the __TOC__ keyword is present'
494 'Do a pre-save transform on the input before parsing it',
495 'Ignored if page, pageid or oldid is used'
498 'Do a pre-save transform (PST) on the input, but don\'t parse it',
499 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
501 'uselang' => 'Which language to parse the request in',
502 'section' => 'Only retrieve the content of this section number',
503 'disablepp' => 'Disable the PP Report from the parser output',
507 public function getDescription() {
508 return 'This module parses wikitext and returns parser output';
511 public function getPossibleErrors() {
512 return array_merge( parent
::getPossibleErrors(), array(
513 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
514 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
515 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
516 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
517 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
518 array( 'nosuchpageid' ),
522 protected function getExamples() {
524 'api.php?action=parse&text={{Project:Sandbox}}'
528 public function getVersion() {
529 return __CLASS__
. ': $Id$';