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