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