* (bug 23460) Parse action should have a section option
[lhc/web/wiklou.git] / includes / api / ApiParse.php
1 <?php
2
3 /**
4 * Created on Dec 01, 2007
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright © 2007 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( "ApiBase.php" );
29 }
30
31 /**
32 * @ingroup API
33 */
34 class ApiParse extends ApiBase {
35
36 public function __construct( $main, $action ) {
37 parent::__construct( $main, $action );
38 }
39
40 public function execute() {
41 // Get parameters
42 $params = $this->extractRequestParams();
43 $text = $params['text'];
44 $title = $params['title'];
45 $page = $params['page'];
46 $pageid = $params['pageid'];
47 $oldid = $params['oldid'];
48
49 if ( !is_null( $page ) && ( !is_null( $text ) || $title != 'API' ) ) {
50 $this->dieUsage( 'The page parameter cannot be used together with the text and title parameters', 'params' );
51 }
52 $prop = array_flip( $params['prop'] );
53 $revid = false;
54
55 if ( isset( $params['section'] ) ) {
56 $this->section = $params['section'];
57 } else {
58 $this->section = false;
59 }
60
61 // The parser needs $wgTitle to be set, apparently the
62 // $title parameter in Parser::parse isn't enough *sigh*
63 global $wgParser, $wgUser, $wgTitle, $wgEnableParserCache, $wgLang;
64
65 // Currently unncessary, code to act as a safeguard against any change in current behaviour of uselang breaks
66 $oldLang = null;
67 if ( isset( $params['uselang'] ) && $params['uselang'] != $wgLang->getCode() ) {
68 $oldLang = $wgLang; // Backup wgLang
69 $wgLang = Language::factory( $params['uselang'] );
70 }
71
72 $popts = new ParserOptions();
73 $popts->setTidy( true );
74 $popts->enableLimitReport();
75 $redirValues = null;
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 ) ) {
84 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
85 }
86
87 $text = $rev->getText( Revision::FOR_THIS_USER );
88 $titleObj = $rev->getTitle();
89 $wgTitle = $titleObj;
90
91 if ( $this->section !== false ) {
92 $text = $this->getSectionText( $text, 'r' . $rev );
93 }
94
95 $p_result = $wgParser->parse( $text, $titleObj, $popts );
96 } else {
97 if ( !is_null ( $pageid ) ) {
98 $titleObj = Title::newFromID( $pageid );
99
100 if ( !$titleObj ) {
101 $this->dieUsageMsg( array( 'nosuchpageid', $pageid ) );
102 }
103 } else {
104 if ( $params['redirects'] ) {
105 $req = new FauxRequest( array(
106 'action' => 'query',
107 'redirects' => '',
108 'titles' => $page
109 ) );
110 $main = new ApiMain( $req );
111 $main->execute();
112 $data = $main->getResultData();
113 $redirValues = @$data['query']['redirects'];
114 $to = $page;
115 foreach ( (array)$redirValues as $r ) {
116 $to = $r['to'];
117 }
118 } else {
119 $to = $page;
120 }
121 $titleObj = Title::newFromText( $to );
122 if ( !$titleObj ) {
123 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
124 }
125 }
126 $wgTitle = $titleObj;
127
128 $articleObj = new Article( $titleObj );
129 if ( isset( $prop['revid'] ) ) {
130 $oldid = $articleObj->getRevIdFetched();
131 }
132
133 if ( $this->section !== false ) {
134 $text = $this->getSectionText( $text, !is_null ( $pageid ) ? 'page id ' . $pageid : $titleObj->getText() );
135 $p_result = $wgParser->parse( $text, $titleObj, $popts );
136 } else {
137 // Try the parser cache first
138 $p_result = false;
139 $pcache = ParserCache::singleton();
140 if ( $wgEnableParserCache ) {
141 $p_result = $pcache->get( $articleObj, $wgUser );
142 }
143 if ( !$p_result ) {
144 $p_result = $wgParser->parse( $articleObj->getContent(), $titleObj, $popts );
145
146 if ( $wgEnableParserCache ) {
147 $pcache->save( $p_result, $articleObj, $popts );
148 }
149 }
150 }
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 if ( $params['redirects'] && !is_null( $redirValues ) ) {
180 $result_array['redirects'] = $redirValues;
181 }
182
183 if ( isset( $prop['text'] ) ) {
184 $result_array['text'] = array();
185 $result->setContent( $result_array['text'], $p_result->getText() );
186 }
187
188 if ( !is_null( $params['summary'] ) ) {
189 $result_array['parsedsummary'] = array();
190 $result->setContent( $result_array['parsedsummary'], $wgUser->getSkin()->formatComment( $params['summary'], $titleObj ) );
191 }
192
193 if ( isset( $prop['langlinks'] ) ) {
194 $result_array['langlinks'] = $this->formatLangLinks( $p_result->getLanguageLinks() );
195 }
196 if ( isset( $prop['categories'] ) ) {
197 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
198 }
199 if ( isset( $prop['links'] ) ) {
200 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
201 }
202 if ( isset( $prop['templates'] ) ) {
203 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
204 }
205 if ( isset( $prop['images'] ) ) {
206 $result_array['images'] = array_keys( $p_result->getImages() );
207 }
208 if ( isset( $prop['externallinks'] ) ) {
209 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
210 }
211 if ( isset( $prop['sections'] ) ) {
212 $result_array['sections'] = $p_result->getSections();
213 }
214 if ( isset( $prop['displaytitle'] ) ) {
215 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
216 $p_result->getDisplayTitle() :
217 $titleObj->getPrefixedText();
218 }
219
220 if ( isset( $prop['headitems'] ) ) {
221 $result_array['headitems'] = $this->formatHeadItems( $p_result->getHeadItems() );
222 }
223
224 if ( isset( $prop['headhtml'] ) ) {
225 $out = new OutputPage;
226 $out->addParserOutputNoText( $p_result );
227 $result_array['headhtml'] = array();
228 $result->setContent( $result_array['headhtml'], $out->headElement( $wgUser->getSkin() ) );
229 }
230
231 if ( !is_null( $oldid ) ) {
232 $result_array['revid'] = intval( $oldid );
233 }
234
235 $result_mapping = array(
236 'redirects' => 'r',
237 'langlinks' => 'll',
238 'categories' => 'cl',
239 'links' => 'pl',
240 'templates' => 'tl',
241 'images' => 'img',
242 'externallinks' => 'el',
243 'sections' => 's',
244 'headitems' => 'hi'
245 );
246 $this->setIndexedTagNames( $result_array, $result_mapping );
247 $result->addValue( null, $this->getModuleName(), $result_array );
248
249 if ( !is_null( $oldLang ) ) {
250 $wgLang = $oldLang; // Reset $wgLang to $oldLang
251 }
252 }
253
254 private function getSectionText( $text, $what ) {
255 global $wgParser;
256 $text = $wgParser->getSection( $text, $this->section, false );
257 if ( $text === false ) {
258 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
259 }
260 return $text;
261 }
262
263 private function formatLangLinks( $links ) {
264 $result = array();
265 foreach ( $links as $link ) {
266 $entry = array();
267 $bits = explode( ':', $link, 2 );
268 $entry['lang'] = $bits[0];
269 $this->getResult()->setContent( $entry, $bits[1] );
270 $result[] = $entry;
271 }
272 return $result;
273 }
274
275 private function formatCategoryLinks( $links ) {
276 $result = array();
277 foreach ( $links as $link => $sortkey ) {
278 $entry = array();
279 $entry['sortkey'] = $sortkey;
280 $this->getResult()->setContent( $entry, $link );
281 $result[] = $entry;
282 }
283 return $result;
284 }
285
286 private function formatLinks( $links ) {
287 $result = array();
288 foreach ( $links as $ns => $nslinks ) {
289 foreach ( $nslinks as $title => $id ) {
290 $entry = array();
291 $entry['ns'] = $ns;
292 $this->getResult()->setContent( $entry, Title::makeTitle( $ns, $title )->getFullText() );
293 if ( $id != 0 ) {
294 $entry['exists'] = '';
295 }
296 $result[] = $entry;
297 }
298 }
299 return $result;
300 }
301
302 private function formatHeadItems( $headItems ) {
303 $result = array();
304 foreach ( $headItems as $tag => $content ) {
305 $entry = array();
306 $entry['tag'] = $tag;
307 $this->getResult()->setContent( $entry, $content );
308 $result[] = $entry;
309 }
310 return $result;
311 }
312
313 private function setIndexedTagNames( &$array, $mapping ) {
314 foreach ( $mapping as $key => $name ) {
315 if ( isset( $array[$key] ) ) {
316 $this->getResult()->setIndexedTagName( $array[$key], $name );
317 }
318 }
319 }
320
321 public function getAllowedParams() {
322 return array(
323 'title' => array(
324 ApiBase::PARAM_DFLT => 'API',
325 ),
326 'text' => null,
327 'summary' => null,
328 'page' => null,
329 'pageid' => null,
330 'redirects' => false,
331 'oldid' => null,
332 'prop' => array(
333 ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|images|externallinks|sections|revid|displaytitle',
334 ApiBase::PARAM_ISMULTI => true,
335 ApiBase::PARAM_TYPE => array(
336 'text',
337 'langlinks',
338 'categories',
339 'links',
340 'templates',
341 'images',
342 'externallinks',
343 'sections',
344 'revid',
345 'displaytitle',
346 'headitems',
347 'headhtml'
348 )
349 ),
350 'pst' => false,
351 'onlypst' => false,
352 'uselang' => null,
353 'section' => null,
354 );
355 }
356
357 public function getParamDescription() {
358 return array(
359 'text' => 'Wikitext to parse.',
360 'summary' => 'Summary to parse.',
361 'redirects' => 'If the page parameter is set to a redirect, resolve it.',
362 'title' => 'Title of page the text belongs to.',
363 'page' => 'Parse the content of this page. Cannot be used together with text and title.',
364 'pageid' => 'Parse the content of this page. Overrides page.',
365 'oldid' => 'Parse the content of this revision. Overrides page and pageid.',
366 'prop' => array( 'Which pieces of information to get.',
367 'NOTE: Section tree is only generated if there are more than 4 sections, or if the __TOC__ keyword is present.'
368 ),
369 'pst' => array( 'Do a pre-save transform on the input before parsing it.',
370 'Ignored if page, pageid or oldid is used.'
371 ),
372 'onlypst' => array( 'Do a pre-save transform (PST) on the input, but don\'t parse it.',
373 'Returns the same wikitext, after a PST has been applied. Ignored if page, pageid or oldid is used.'
374 ),
375 'uselang' => 'Which language to parse the request in.',
376 'section' => 'Only retrieve the content of this section number',
377 );
378 }
379
380 public function getDescription() {
381 return 'This module parses wikitext and returns parser output';
382 }
383
384 public function getPossibleErrors() {
385 return array_merge( parent::getPossibleErrors(), array(
386 array( 'code' => 'params', 'info' => 'The page parameter cannot be used together with the text and title parameters' ),
387 array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
388 array( 'code' => 'permissiondenied', 'info' => 'You don\'t have permission to view deleted revisions' ),
389 array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
390 array( 'code' => 'nosuchsection', 'info' => 'There is no section in '),
391 array( 'nosuchpageid' ),
392 ) );
393 }
394
395 protected function getExamples() {
396 return array(
397 'api.php?action=parse&text={{Project:Sandbox}}'
398 );
399 }
400
401 public function getVersion() {
402 return __CLASS__ . ': $Id$';
403 }
404 }