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