Complete dieUsage errors in 6 more Api files
[lhc/web/wiklou.git] / includes / api / ApiEditPage.php
1 <?php
2
3 /*
4 * Created on August 16, 2007
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2007 Iker Labarga <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 * A module that allows for editing and creating pages.
33 *
34 * Currently, this wraps around the EditPage class in an ugly way,
35 * EditPage.php should be rewritten to provide a cleaner interface
36 * @ingroup API
37 */
38 class ApiEditPage extends ApiBase {
39
40 public function __construct( $query, $moduleName ) {
41 parent :: __construct( $query, $moduleName );
42 }
43
44 public function execute() {
45 global $wgUser;
46 $params = $this->extractRequestParams();
47
48 if ( is_null( $params['title'] ) )
49 $this->dieUsageMsg( array( 'missingparam', 'title' ) );
50
51 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
52 is_null( $params['prependtext'] ) &&
53 $params['undo'] == 0 )
54 $this->dieUsageMsg( array( 'missingtext' ) );
55
56 if ( is_null( $params['token'] ) )
57 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
58
59 if ( !$wgUser->matchEditToken( $params['token'] ) )
60 $this->dieUsageMsg( array( 'sessionfailure' ) );
61
62 $titleObj = Title::newFromText( $params['title'] );
63 if ( !$titleObj || $titleObj->isExternal() )
64 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
65
66 // Some functions depend on $wgTitle == $ep->mTitle
67 global $wgTitle;
68 $wgTitle = $titleObj;
69
70 if ( $params['createonly'] && $titleObj->exists() )
71 $this->dieUsageMsg( array( 'createonly-exists' ) );
72 if ( $params['nocreate'] && !$titleObj->exists() )
73 $this->dieUsageMsg( array( 'nocreate-missing' ) );
74
75 // Now let's check whether we're even allowed to do this
76 $errors = $titleObj->getUserPermissionsErrors( 'edit', $wgUser );
77 if ( !$titleObj->exists() )
78 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $wgUser ) );
79 if ( count( $errors ) )
80 $this->dieUsageMsg( $errors[0] );
81
82 $articleObj = new Article( $titleObj );
83 $toMD5 = $params['text'];
84 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
85 {
86 // For non-existent pages, Article::getContent()
87 // returns an interface message rather than ''
88 // We do want getContent()'s behavior for non-existent
89 // MediaWiki: pages, though
90 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI )
91 $content = '';
92 else
93 $content = $articleObj->getContent();
94
95 if ( !is_null( $params['section'] ) )
96 {
97 // Process the content for section edits
98 global $wgParser;
99 $section = intval( $params['section'] );
100 $content = $wgParser->getSection( $content, $section, false );
101 if ( $content === false )
102 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
103 }
104 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
105 $toMD5 = $params['prependtext'] . $params['appendtext'];
106 }
107
108 if ( $params['undo'] > 0 )
109 {
110 if ( $params['undoafter'] > 0 )
111 {
112 if ( $params['undo'] < $params['undoafter'] )
113 list( $params['undo'], $params['undoafter'] ) =
114 array( $params['undoafter'], $params['undo'] );
115 $undoafterRev = Revision::newFromID( $params['undoafter'] );
116 }
117 $undoRev = Revision::newFromID( $params['undo'] );
118 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) )
119 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
120
121 if ( $params['undoafter'] == 0 )
122 $undoafterRev = $undoRev->getPrevious();
123 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) )
124 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
125
126 if ( $undoRev->getPage() != $articleObj->getID() )
127 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
128 if ( $undoafterRev->getPage() != $articleObj->getID() )
129 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
130
131 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
132 if ( $newtext === false )
133 $this->dieUsageMsg( array( 'undo-failure' ) );
134 $params['text'] = $newtext;
135 // If no summary was given and we only undid one rev,
136 // use an autosummary
137 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] )
138 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
139 }
140
141 // See if the MD5 hash checks out
142 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] )
143 $this->dieUsageMsg( array( 'hashcheckfailed' ) );
144
145 $ep = new EditPage( $articleObj );
146 // EditPage wants to parse its stuff from a WebRequest
147 // That interface kind of sucks, but it's workable
148 $reqArr = array( 'wpTextbox1' => $params['text'],
149 'wpEditToken' => $params['token'],
150 'wpIgnoreBlankSummary' => ''
151 );
152
153 if ( !is_null( $params['summary'] ) )
154 $reqArr['wpSummary'] = $params['summary'];
155
156 // Watch out for basetimestamp == ''
157 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
158 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' )
159 $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
160 else
161 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
162
163 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' )
164 $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
165 else
166 $reqArr['wpStarttime'] = $reqArr['wpEdittime']; // Fake wpStartime
167
168 if ( $params['minor'] || ( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) )
169 $reqArr['wpMinoredit'] = '';
170
171 if ( $params['recreate'] )
172 $reqArr['wpRecreate'] = '';
173
174 if ( !is_null( $params['section'] ) )
175 {
176 $section = intval( $params['section'] );
177 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' )
178 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
179 $reqArr['wpSection'] = $params['section'];
180 }
181 else
182 $reqArr['wpSection'] = '';
183
184 // Handle watchlist settings
185 switch ( $params['watchlist'] )
186 {
187 case 'watch':
188 $watch = true;
189 break;
190 case 'unwatch':
191 $watch = false;
192 break;
193 case 'preferences':
194 if ( $titleObj->exists() )
195 $watch = $wgUser->getOption( 'watchdefault' ) || $titleObj->userIsWatching();
196 else
197 $watch = $wgUser->getOption( 'watchcreations' );
198 break;
199 case 'nochange':
200 default:
201 $watch = $titleObj->userIsWatching();
202 }
203 // Deprecated parameters
204 if ( $params['watch'] )
205 $watch = true;
206 elseif ( $params['unwatch'] )
207 $watch = false;
208
209 if ( $watch )
210 $reqArr['wpWatchthis'] = '';
211
212 $req = new FauxRequest( $reqArr, true );
213 $ep->importFormData( $req );
214
215 // Run hooks
216 // Handle CAPTCHA parameters
217 global $wgRequest;
218 if ( !is_null( $params['captchaid'] ) )
219 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
220 if ( !is_null( $params['captchaword'] ) )
221 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
222
223 $r = array();
224 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) )
225 {
226 if ( count( $r ) )
227 {
228 $r['result'] = "Failure";
229 $this->getResult()->addValue( null, $this->getModuleName(), $r );
230 return;
231 }
232 else
233 $this->dieUsageMsg( array( 'hookaborted' ) );
234 }
235
236 // Do the actual save
237 $oldRevId = $articleObj->getRevIdFetched();
238 $result = null;
239 // Fake $wgRequest for some hooks inside EditPage
240 // FIXME: This interface SUCKS
241 $oldRequest = $wgRequest;
242 $wgRequest = $req;
243
244 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
245 $wgRequest = $oldRequest;
246 switch( $retval )
247 {
248 case EditPage::AS_HOOK_ERROR:
249 case EditPage::AS_HOOK_ERROR_EXPECTED:
250 $this->dieUsageMsg( array( 'hookaborted' ) );
251
252 case EditPage::AS_IMAGE_REDIRECT_ANON:
253 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
254
255 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
256 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
257
258 case EditPage::AS_SPAM_ERROR:
259 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
260
261 case EditPage::AS_FILTERING:
262 $this->dieUsageMsg( array( 'filtered' ) );
263
264 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
265 $this->dieUsageMsg( array( 'blockedtext' ) );
266
267 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
268 case EditPage::AS_CONTENT_TOO_BIG:
269 global $wgMaxArticleSize;
270 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
271
272 case EditPage::AS_READ_ONLY_PAGE_ANON:
273 $this->dieUsageMsg( array( 'noedit-anon' ) );
274
275 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
276 $this->dieUsageMsg( array( 'noedit' ) );
277
278 case EditPage::AS_READ_ONLY_PAGE:
279 $this->dieReadOnly();
280
281 case EditPage::AS_RATE_LIMITED:
282 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
283
284 case EditPage::AS_ARTICLE_WAS_DELETED:
285 $this->dieUsageMsg( array( 'wasdeleted' ) );
286
287 case EditPage::AS_NO_CREATE_PERMISSION:
288 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
289
290 case EditPage::AS_BLANK_ARTICLE:
291 $this->dieUsageMsg( array( 'blankpage' ) );
292
293 case EditPage::AS_CONFLICT_DETECTED:
294 $this->dieUsageMsg( array( 'editconflict' ) );
295
296 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
297 case EditPage::AS_TEXTBOX_EMPTY:
298 $this->dieUsageMsg( array( 'emptynewsection' ) );
299
300 case EditPage::AS_SUCCESS_NEW_ARTICLE:
301 $r['new'] = '';
302 case EditPage::AS_SUCCESS_UPDATE:
303 $r['result'] = "Success";
304 $r['pageid'] = intval( $titleObj->getArticleID() );
305 $r['title'] = $titleObj->getPrefixedText();
306 // HACK: We create a new Article object here because getRevIdFetched()
307 // refuses to be run twice, and because Title::getLatestRevId()
308 // won't fetch from the master unless we select for update, which we
309 // don't want to do.
310 $newArticle = new Article( $titleObj );
311 $newRevId = $newArticle->getRevIdFetched();
312 if ( $newRevId == $oldRevId )
313 $r['nochange'] = '';
314 else
315 {
316 $r['oldrevid'] = intval( $oldRevId );
317 $r['newrevid'] = intval( $newRevId );
318 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
319 $newArticle->getTimestamp() );
320 }
321 break;
322
323 case EditPage::AS_END:
324 // This usually means some kind of race condition
325 // or DB weirdness occurred. Fall through to throw an unknown
326 // error.
327
328 // This needs fixing higher up, as Article::doEdit should be
329 // used rather than Article::updateArticle, so that specific
330 // error conditions can be returned
331 default:
332 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
333 }
334 $this->getResult()->addValue( null, $this->getModuleName(), $r );
335 }
336
337 public function mustBePosted() {
338 return true;
339 }
340
341 public function isWriteMode() {
342 return true;
343 }
344
345 protected function getDescription() {
346 return 'Create and edit pages.';
347 }
348
349 public function getPossibleErrors() {
350 return array_merge( parent::getPossibleErrors(), array(
351 array( 'missingparam', 'title' ),
352 array( 'missingtext' ),
353 array( 'missingparam', 'token' ),
354 array( 'sessionfailure' ),
355 array( 'invalidtitle', 'title' ),
356 array( 'createonly-exists' ),
357 array( 'nocreate-missing' ),
358 array( 'nosuchrevid', 'undo' ),
359 array( 'nosuchrevid', 'undoafter' ),
360 array( 'revwrongpage', 'id', 'text' ),
361 array( 'revwrongpage', 'id', 'text' ),
362 array( 'undo-failure' ),
363 array( 'hashcheckfailed' ),
364 array( 'hookaborted' ),
365 array( 'hookaborted' ),
366 array( 'noimageredirect-anon' ),
367 array( 'noimageredirect-logged' ),
368 array( 'spamdetected', 'spam' ),
369 array( 'filtered' ),
370 array( 'blockedtext' ),
371 array( 'contenttoobig', $this->getMaxArticleSize() ),
372 array( 'noedit-anon' ),
373 array( 'noedit' ),
374 array( 'actionthrottledtext' ),
375 array( 'wasdeleted' ),
376 array( 'nocreate-loggedin' ),
377 array( 'blankpage' ),
378 array( 'editconflict' ),
379 array( 'emptynewsection' ),
380 array( 'unknownerror', 'retval' ),
381 array( 'code' => 'nosuchsection', 'info' => '' ), "There is no section section.", ''
382 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
383 ) );
384 }
385
386 private function getMaxArticleSize() {
387 global $wgMaxArticleSize;
388 return $wgMaxArticleSize;
389 }
390
391 protected function getAllowedParams() {
392 return array (
393 'title' => null,
394 'section' => null,
395 'text' => null,
396 'token' => null,
397 'summary' => null,
398 'minor' => false,
399 'notminor' => false,
400 'bot' => false,
401 'basetimestamp' => null,
402 'starttimestamp' => null,
403 'recreate' => false,
404 'createonly' => false,
405 'nocreate' => false,
406 'captchaword' => null,
407 'captchaid' => null,
408 'watch' => array(
409 ApiBase :: PARAM_DFLT => false,
410 ApiBase :: PARAM_DEPRECATED => true,
411 ),
412 'unwatch' => array(
413 ApiBase :: PARAM_DFLT => false,
414 ApiBase :: PARAM_DEPRECATED => true,
415 ),
416 'watchlist' => array(
417 ApiBase :: PARAM_DFLT => 'preferences',
418 ApiBase :: PARAM_TYPE => array(
419 'watch',
420 'unwatch',
421 'preferences',
422 'nochange'
423 ),
424 ),
425 'md5' => null,
426 'prependtext' => null,
427 'appendtext' => null,
428 'undo' => array(
429 ApiBase :: PARAM_TYPE => 'integer'
430 ),
431 'undoafter' => array(
432 ApiBase :: PARAM_TYPE => 'integer'
433 ),
434 );
435 }
436
437 protected function getParamDescription() {
438 return array (
439 'title' => 'Page title',
440 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
441 'text' => 'Page content',
442 'token' => 'Edit token. You can get one of these through prop=info',
443 'summary' => 'Edit summary. Also section title when section=new',
444 'minor' => 'Minor edit',
445 'notminor' => 'Non-minor edit',
446 'bot' => 'Mark this edit as bot',
447 'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
448 'Used to detect edit conflicts; leave unset to ignore conflicts.'
449 ),
450 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
451 'Used to detect edit conflicts; leave unset to ignore conflicts.'
452 ),
453 'recreate' => 'Override any errors about the article having been deleted in the meantime',
454 'createonly' => 'Don\'t edit the page if it exists already',
455 'nocreate' => 'Throw an error if the page doesn\'t exist',
456 'watch' => 'Add the page to your watchlist',
457 'unwatch' => 'Remove the page from your watchlist',
458 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
459 'captchaid' => 'CAPTCHA ID from previous request',
460 'captchaword' => 'Answer to the CAPTCHA',
461 'md5' => array( 'The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated.',
462 'If set, the edit won\'t be done unless the hash is correct' ),
463 'prependtext' => 'Add this text to the beginning of the page. Overrides text.',
464 'appendtext' => 'Add this text to the end of the page. Overrides text',
465 'undo' => 'Undo this revision. Overrides text, prependtext and appendtext',
466 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
467 );
468 }
469
470 protected function getExamples() {
471 return array (
472 "Edit a page (anonymous user):",
473 " api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\",
474 "Prepend __NOTOC__ to a page (anonymous user):",
475 " api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\",
476 "Undo r13579 through r13585 with autosummary(anonymous user):",
477 " api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\",
478 );
479 }
480
481 public function getVersion() {
482 return __CLASS__ . ': $Id$';
483 }
484 }