* (bug 25133) allow redirects also for action=parse&pageid
[lhc/web/wiklou.git] / includes / api / ApiParse.php
1 <?php
2 /**
3 * Created on Dec 01, 2007
4 *
5 * Copyright © 2007 Yuri Astrakhan <Firstname><Lastname>@gmail.com
6 *
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.
11 *
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.
16 *
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
21 *
22 * @file
23 */
24
25 if ( !defined( 'MEDIAWIKI' ) ) {
26 // Eclipse helper - will be ignored in production
27 require_once( "ApiBase.php" );
28 }
29
30 /**
31 * @ingroup API
32 */
33 class ApiParse extends ApiBase {
34 private $section, $text, $pstText = null;
35
36 public function __construct( $main, $action ) {
37 parent::__construct( $main, $action );
38 }
39
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' );
43
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'];
51
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' );
54 }
55 $prop = array_flip( $params['prop'] );
56
57 if ( isset( $params['section'] ) ) {
58 $this->section = $params['section'];
59 } else {
60 $this->section = false;
61 }
62
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;
66
67 // Currently unnecessary, code to act as a safeguard against any change in current behaviour of uselang breaks
68 $oldLang = null;
69 if ( isset( $params['uselang'] ) && $params['uselang'] != $wgLang->getCode() ) {
70 $oldLang = $wgLang; // Backup wgLang
71 $wgLang = Language::factory( $params['uselang'] );
72 }
73
74 $popts = new ParserOptions();
75 $popts->setTidy( true );
76 $popts->enableLimitReport( !$params['disablepp'] );
77
78 $redirValues = null;
79
80 if ( !is_null( $oldid ) || !is_null( $pageid ) || !is_null( $page ) ) {
81 if ( !is_null( $oldid ) ) {
82 // Don't use the parser cache
83 $rev = Revision::newFromID( $oldid );
84 if ( !$rev ) {
85 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
86 }
87 if ( !$rev->userCan( Revision::DELETED_TEXT ) ) {
88 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
89 }
90
91 $titleObj = $rev->getTitle();
92
93 $wgTitle = $titleObj;
94
95 // If for some reason the "oldid" is actually the current revision, it may be cached
96 if ( $titleObj->getLatestRevID() === intval( $oldid ) ) {
97 $articleObj = new Article( $titleObj, 0 );
98
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 );
103
104 $wgTitle = $titleObj;
105
106 if ( $this->section !== false ) {
107 $this->text = $this->getSectionText( $this->text, 'r' . $rev->getId() );
108 }
109
110 $p_result = $wgParser->parse( $this->text, $titleObj, $popts );
111 }
112 } else { // Not $oldid
113 if ( $params['redirects'] ) {
114 $reqParams = array(
115 'action' => 'query',
116 'redirects' => '',
117 );
118 if ( !is_null ( $pageid ) ) {
119 $reqParams['pageids'] = $pageid;
120 } else { // $page
121 $reqParams['titles'] = $page;
122 }
123 $req = new FauxRequest( $reqParams );
124 $main = new ApiMain( $req );
125 $main->execute();
126 $data = $main->getResultData();
127 $redirValues = isset( $data['query']['redirects'] )
128 ? $data['query']['redirects']
129 : array();
130 $to = $page;
131 foreach ( (array)$redirValues as $r ) {
132 $to = $r['to'];
133 }
134 $titleObj = Title::newFromText( $to );
135 } else {
136 if ( !is_null ( $pageid ) ) {
137 $reqParams['pageids'] = $pageid;
138 $titleObj = Title::newFromID( $pageid );
139 } else { // $page
140 $to = $page;
141 $titleObj = Title::newFromText( $to );
142 }
143 }
144 if ( !is_null ( $pageid ) ) {
145 if ( !$titleObj ) {
146 // Still throw nosuchpageid error if pageid was provided
147 $this->dieUsageMsg( array( 'nosuchpageid', $pageid ) );
148 }
149 } elseif ( !$titleObj || !$titleObj->exists() ) {
150 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
151 }
152 $wgTitle = $titleObj;
153
154 $articleObj = new Article( $titleObj, 0 );
155 if ( isset( $prop['revid'] ) ) {
156 $oldid = $articleObj->getRevIdFetched();
157 }
158
159 $p_result = $this->getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageid,
160 isset( $prop['wikitext'] ) ) ;
161 }
162 } else { // Not $oldid, $pageid, $page. Hence based on $text
163
164 $this->text = $text;
165 $titleObj = Title::newFromText( $title );
166 if ( !$titleObj ) {
167 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
168 }
169 $wgTitle = $titleObj;
170
171 if ( $this->section !== false ) {
172 $this->text = $this->getSectionText( $this->text, $titleObj->getText() );
173 }
174
175 if ( $params['pst'] || $params['onlypst'] ) {
176 $this->pstText = $wgParser->preSaveTransform( $this->text, $titleObj, $wgUser, $popts );
177 }
178 if ( $params['onlypst'] ) {
179 // Build a result and bail out
180 $result_array['text'] = array();
181 $this->getResult()->setContent( $result_array['text'], $this->pstText );
182 if ( isset( $prop['wikitext'] ) ) {
183 $result_array['wikitext'] = array();
184 $this->getResult()->setContent( $result_array['wikitext'], $this->text );
185 }
186 $this->getResult()->addValue( null, $this->getModuleName(), $result_array );
187 return;
188 }
189 $p_result = $wgParser->parse( $params['pst'] ? $this->pstText : $this->text, $titleObj, $popts );
190 }
191
192 // Return result
193 $result = $this->getResult();
194 $result_array = array();
195
196 $result_array['title'] = $titleObj->getPrefixedText();
197
198 if ( !is_null( $oldid ) ) {
199 $result_array['revid'] = intval( $oldid );
200 }
201
202 if ( $params['redirects'] && !is_null( $redirValues ) ) {
203 $result_array['redirects'] = $redirValues;
204 }
205
206 if ( isset( $prop['text'] ) ) {
207 $result_array['text'] = array();
208 $result->setContent( $result_array['text'], $p_result->getText() );
209 }
210
211 if ( !is_null( $params['summary'] ) ) {
212 $result_array['parsedsummary'] = array();
213 $result->setContent( $result_array['parsedsummary'], $wgUser->getSkin()->formatComment( $params['summary'], $titleObj ) );
214 }
215
216 if ( isset( $prop['langlinks'] ) ) {
217 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
218 }
219 if ( isset( $prop['languageshtml'] ) ) {
220 $languagesHtml = $this->languagesHtml( $p_result->getLanguageLinks() );
221 $result_array['languageshtml'] = array();
222 $result->setContent( $result_array['languageshtml'], $languagesHtml );
223 }
224 if ( isset( $prop['categories'] ) ) {
225 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
226 }
227 if ( isset( $prop['categorieshtml'] ) ) {
228 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
229 $result_array['categorieshtml'] = array();
230 $result->setContent( $result_array['categorieshtml'], $categoriesHtml );
231 }
232 if ( isset( $prop['links'] ) ) {
233 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
234 }
235 if ( isset( $prop['templates'] ) ) {
236 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
237 }
238 if ( isset( $prop['images'] ) ) {
239 $result_array['images'] = array_keys( $p_result->getImages() );
240 }
241 if ( isset( $prop['externallinks'] ) ) {
242 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
243 }
244 if ( isset( $prop['sections'] ) ) {
245 $result_array['sections'] = $p_result->getSections();
246 }
247
248 if ( isset( $prop['displaytitle'] ) ) {
249 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
250 $p_result->getDisplayTitle() :
251 $titleObj->getPrefixedText();
252 }
253
254 if ( isset( $prop['headitems'] ) || isset( $prop['headhtml'] ) ) {
255 $context = new RequestContext;
256 $context->getOutput()->addParserOutputNoText( $p_result );
257
258 if ( isset( $prop['headitems'] ) ) {
259 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
260
261 $context->getSkin()->setupUserCss( $context->getOutput() );
262 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
263
264 $scripts = array( $context->getOutput()->getHeadScripts( $context->getSkin() ) );
265
266 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
267 }
268
269 if ( isset( $prop['headhtml'] ) ) {
270 $result_array['headhtml'] = array();
271 $result->setContent( $result_array['headhtml'], $context->getOutput()->headElement( $context->getSkin() ) );
272 }
273 }
274
275 if ( isset( $prop['iwlinks'] ) ) {
276 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
277 }
278
279 if ( isset( $prop['wikitext'] ) ) {
280 $result_array['wikitext'] = array();
281 $result->setContent( $result_array['wikitext'], $this->text );
282 if ( !is_null( $this->pstText ) ) {
283 $result_array['psttext'] = array();
284 $result->setContent( $result_array['psttext'], $this->pstText );
285 }
286 }
287
288 $result_mapping = array(
289 'redirects' => 'r',
290 'langlinks' => 'll',
291 'categories' => 'cl',
292 'links' => 'pl',
293 'templates' => 'tl',
294 'images' => 'img',
295 'externallinks' => 'el',
296 'iwlinks' => 'iw',
297 'sections' => 's',
298 'headitems' => 'hi',
299 );
300 $this->setIndexedTagNames( $result_array, $result_mapping );
301 $result->addValue( null, $this->getModuleName(), $result_array );
302
303 if ( !is_null( $oldLang ) ) {
304 $wgLang = $oldLang; // Reset $wgLang to $oldLang
305 }
306 }
307
308 /**
309 * @param $articleObj Article
310 * @param $titleObj Title
311 * @param $popts ParserOptions
312 * @param $pageId Int
313 * @param $getWikitext Bool
314 * @return ParserOutput
315 */
316 private function getParsedSectionOrText( $articleObj, $titleObj, $popts, $pageId = null, $getWikitext = false ) {
317 if ( $this->section !== false ) {
318 global $wgParser;
319
320 $this->text = $this->getSectionText( $articleObj->getRawText(), !is_null ( $pageId )
321 ? 'page id ' . $pageId : $titleObj->getText() );
322
323 return $wgParser->parse( $this->text, $titleObj, $popts );
324 } else {
325 // Try the parser cache first
326 $pout = $articleObj->getParserOutput();
327 if ( $getWikitext ) {
328 $rev = Revision::newFromTitle( $titleObj );
329 if ( $rev ) {
330 $this->text = $rev->getText();
331 }
332 }
333 return $pout;
334 }
335 }
336
337 private function getSectionText( $text, $what ) {
338 global $wgParser;
339 $text = $wgParser->getSection( $text, $this->section, false );
340 if ( $text === false ) {
341 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
342 }
343 return $text;
344 }
345
346 private function formatLangLinks( $links ) {
347 $result = array();
348 foreach ( $links as $link ) {
349 $entry = array();
350 $bits = explode( ':', $link, 2 );
351 $title = Title::newFromText( $link );
352
353 $entry['lang'] = $bits[0];
354 if ( $title ) {
355 $entry['url'] = $title->getFullURL();
356 }
357 $this->getResult()->setContent( $entry, $bits[1] );
358 $result[] = $entry;
359 }
360 return $result;
361 }
362
363 private function formatCategoryLinks( $links ) {
364 $result = array();
365 foreach ( $links as $link => $sortkey ) {
366 $entry = array();
367 $entry['sortkey'] = $sortkey;
368 $this->getResult()->setContent( $entry, $link );
369 $result[] = $entry;
370 }
371 return $result;
372 }
373
374 private function categoriesHtml( $categories ) {
375 global $wgOut, $wgUser;
376 $wgOut->addCategoryLinks( $categories );
377 return $wgUser->getSkin()->getCategories();
378 }
379
380 /**
381 * @deprecated since 1.18 No modern skin generates language links this way, please use language links
382 * data to generate your own HTML.
383 */
384 private function languagesHtml( $languages ) {
385 global $wgContLang, $wgHideInterlanguageLinks;
386
387 if ( $wgHideInterlanguageLinks || count( $languages ) == 0 ) {
388 return '';
389 }
390
391 $s = htmlspecialchars( wfMsg( 'otherlanguages' ) . wfMsg( 'colon-separator' ) );
392
393 $langs = array();
394 foreach ( $languages as $l ) {
395 $nt = Title::newFromText( $l );
396 $text = $wgContLang->getLanguageName( $nt->getInterwiki() );
397
398 $langs[] = Html::element( 'a',
399 array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => "external" ),
400 $text == '' ? $l : $text );
401 }
402
403 $s .= implode( htmlspecialchars( wfMsgExt( 'pipe-separator', 'escapenoentities' ) ), $langs );
404
405 if ( $wgContLang->isRTL() ) {
406 $s = Html::rawElement( 'span', array( 'dir' => "LTR" ), $s );
407 }
408
409 return $s;
410 }
411
412 private function formatLinks( $links ) {
413 $result = array();
414 foreach ( $links as $ns => $nslinks ) {
415 foreach ( $nslinks as $title => $id ) {
416 $entry = array();
417 $entry['ns'] = $ns;
418 $this->getResult()->setContent( $entry, Title::makeTitle( $ns, $title )->getFullText() );
419 if ( $id != 0 ) {
420 $entry['exists'] = '';
421 }
422 $result[] = $entry;
423 }
424 }
425 return $result;
426 }
427
428 private function formatIWLinks( $iw ) {
429 $result = array();
430 foreach ( $iw as $prefix => $titles ) {
431 foreach ( array_keys( $titles ) as $title ) {
432 $entry = array();
433 $entry['prefix'] = $prefix;
434
435 $title = Title::newFromText( "{$prefix}:{$title}" );
436 if ( $title ) {
437 $entry['url'] = $title->getFullURL();
438 }
439
440 $this->getResult()->setContent( $entry, $title->getFullText() );
441 $result[] = $entry;
442 }
443 }
444 return $result;
445 }
446
447 private function formatHeadItems( $headItems ) {
448 $result = array();
449 foreach ( $headItems as $tag => $content ) {
450 $entry = array();
451 $entry['tag'] = $tag;
452 $this->getResult()->setContent( $entry, $content );
453 $result[] = $entry;
454 }
455 return $result;
456 }
457
458 private function formatCss( $css ) {
459 $result = array();
460 foreach ( $css as $file => $link ) {
461 $entry = array();
462 $entry['file'] = $file;
463 $this->getResult()->setContent( $entry, $link );
464 $result[] = $entry;
465 }
466 return $result;
467 }
468
469 private function setIndexedTagNames( &$array, $mapping ) {
470 foreach ( $mapping as $key => $name ) {
471 if ( isset( $array[$key] ) ) {
472 $this->getResult()->setIndexedTagName( $array[$key], $name );
473 }
474 }
475 }
476
477 public function getAllowedParams() {
478 return array(
479 'title' => array(
480 ApiBase::PARAM_DFLT => 'API',
481 ),
482 'text' => null,
483 'summary' => null,
484 'page' => null,
485 'pageid' => array(
486 ApiBase::PARAM_TYPE => 'integer',
487 ),
488 'redirects' => false,
489 'oldid' => array(
490 ApiBase::PARAM_TYPE => 'integer',
491 ),
492 'prop' => array(
493 ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle',
494 ApiBase::PARAM_ISMULTI => true,
495 ApiBase::PARAM_TYPE => array(
496 'text',
497 'langlinks',
498 'languageshtml',
499 'categories',
500 'categorieshtml',
501 'links',
502 'templates',
503 'images',
504 'externallinks',
505 'sections',
506 'revid',
507 'displaytitle',
508 'headitems',
509 'headhtml',
510 'iwlinks',
511 'wikitext',
512 )
513 ),
514 'pst' => false,
515 'onlypst' => false,
516 'uselang' => null,
517 'section' => null,
518 'disablepp' => false,
519 );
520 }
521
522 public function getParamDescription() {
523 $p = $this->getModulePrefix();
524 return array(
525 'text' => 'Wikitext to parse',
526 'summary' => 'Summary to parse',
527 'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
528 'title' => 'Title of page the text belongs to',
529 'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
530 'pageid' => "Parse the content of this page. Overrides {$p}page",
531 'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
532 'prop' => array(
533 'Which pieces of information to get',
534 ' text - Gives the parsed text of the wikitext',
535 ' langlinks - Gives the language links in the parsed wikitext',
536 ' categories - Gives the categories in the parsed wikitext',
537 ' categorieshtml - Gives the HTML version of the categories',
538 ' languageshtml - Gives the HTML version of the language links',
539 ' links - Gives the internal links in the parsed wikitext',
540 ' templates - Gives the templates in the parsed wikitext',
541 ' images - Gives the images in the parsed wikitext',
542 ' externallinks - Gives the external links in the parsed wikitext',
543 ' sections - Gives the sections in the parsed wikitext',
544 ' revid - Adds the revision ID of the parsed page',
545 ' displaytitle - Adds the title of the parsed wikitext',
546 ' headitems - Gives items to put in the <head> of the page',
547 ' headhtml - Gives parsed <head> of the page',
548 ' iwlinks - Gives interwiki links in the parsed wikitext',
549 ' wikitext - Gives the original wikitext that was parsed',
550 ),
551 'pst' => array(
552 'Do a pre-save transform on the input before parsing it',
553 'Ignored if page, pageid or oldid is used'
554 ),
555 'onlypst' => array(
556 'Do a pre-save transform (PST) on the input, but don\'t parse it',
557 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used'
558 ),
559 'uselang' => 'Which language to parse the request in',
560 'section' => 'Only retrieve the content of this section number',
561 'disablepp' => 'Disable the PP Report from the parser output',
562 );
563 }
564
565 public function getDescription() {
566 return 'Parses wikitext and returns parser output';
567 }
568
569 public function getPossibleErrors() {
570 return array_merge( parent::getPossibleErrors(), array(
571 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
572 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
573 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
574 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
575 array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
576 array( 'nosuchpageid' ),
577 array( 'invalidtitle', 'title' ),
578 ) );
579 }
580
581 protected function getExamples() {
582 return array(
583 'api.php?action=parse&text={{Project:Sandbox}}'
584 );
585 }
586
587 public function getVersion() {
588 return __CLASS__ . ': $Id$';
589 }
590 }