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