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