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