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