Per Aaron, fix for r89405: introduced DerivativeRequest to allow to override the...
[mediawiki.git] / includes / api / ApiEditPage.php
blobe3106461a877f97f0dea509e225533e3cdb4384f
1 <?php
2 /**
5 * Created on August 16, 2007
7 * Copyright © 2007 Iker Labarga <Firstname><Lastname>@gmail.com
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.
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.
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
24 * @file
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiBase.php" );
32 /**
33 * A module that allows for editing and creating pages.
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
39 class ApiEditPage extends ApiBase {
41 public function __construct( $query, $moduleName ) {
42 parent::__construct( $query, $moduleName );
45 public function execute() {
46 $user = $this->getUser();
47 $params = $this->extractRequestParams();
49 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
50 is_null( $params['prependtext'] ) &&
51 $params['undo'] == 0 )
53 $this->dieUsageMsg( 'missingtext' );
56 $titleObj = Title::newFromText( $params['title'] );
57 if ( !$titleObj || $titleObj->isExternal() ) {
58 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
61 $apiResult = $this->getResult();
63 if ( $params['redirect'] ) {
64 if ( $titleObj->isRedirect() ) {
65 $oldTitle = $titleObj;
67 $titles = Title::newFromRedirectArray( Revision::newFromTitle( $oldTitle )->getText( Revision::FOR_THIS_USER ) );
68 // array_shift( $titles );
70 $redirValues = array();
71 foreach ( $titles as $id => $newTitle ) {
73 if ( !isset( $titles[ $id - 1 ] ) ) {
74 $titles[ $id - 1 ] = $oldTitle;
77 $redirValues[] = array(
78 'from' => $titles[ $id - 1 ]->getPrefixedText(),
79 'to' => $newTitle->getPrefixedText()
82 $titleObj = $newTitle;
85 $apiResult->setIndexedTagName( $redirValues, 'r' );
86 $apiResult->addValue( null, 'redirects', $redirValues );
90 // Some functions depend on $wgTitle == $ep->mTitle
91 // TODO: Make them not or check if they still do
92 global $wgTitle;
93 $wgTitle = $titleObj;
95 if ( $params['createonly'] && $titleObj->exists() ) {
96 $this->dieUsageMsg( 'createonly-exists' );
98 if ( $params['nocreate'] && !$titleObj->exists() ) {
99 $this->dieUsageMsg( 'nocreate-missing' );
102 // Now let's check whether we're even allowed to do this
103 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
104 if ( !$titleObj->exists() ) {
105 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
107 if ( count( $errors ) ) {
108 $this->dieUsageMsg( $errors[0] );
111 $articleObj = new Article( $titleObj );
112 $toMD5 = $params['text'];
113 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
115 // For non-existent pages, Article::getContent()
116 // returns an interface message rather than ''
117 // We do want getContent()'s behavior for non-existent
118 // MediaWiki: pages, though
119 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI ) {
120 $content = '';
121 } else {
122 $content = $articleObj->getContent();
125 if ( !is_null( $params['section'] ) ) {
126 // Process the content for section edits
127 global $wgParser;
128 $section = intval( $params['section'] );
129 $content = $wgParser->getSection( $content, $section, false );
130 if ( $content === false ) {
131 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
134 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
135 $toMD5 = $params['prependtext'] . $params['appendtext'];
138 if ( $params['undo'] > 0 ) {
139 if ( $params['undoafter'] > 0 ) {
140 if ( $params['undo'] < $params['undoafter'] ) {
141 list( $params['undo'], $params['undoafter'] ) =
142 array( $params['undoafter'], $params['undo'] );
144 $undoafterRev = Revision::newFromID( $params['undoafter'] );
146 $undoRev = Revision::newFromID( $params['undo'] );
147 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
148 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
151 if ( $params['undoafter'] == 0 ) {
152 $undoafterRev = $undoRev->getPrevious();
154 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
155 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
158 if ( $undoRev->getPage() != $articleObj->getID() ) {
159 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
161 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
162 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
165 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
166 if ( $newtext === false ) {
167 $this->dieUsageMsg( 'undo-failure' );
169 $params['text'] = $newtext;
170 // If no summary was given and we only undid one rev,
171 // use an autosummary
172 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
173 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
177 // See if the MD5 hash checks out
178 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
179 $this->dieUsageMsg( 'hashcheckfailed' );
182 $ep = new EditPage( $articleObj );
183 $ep->setContextTitle( $titleObj );
185 // EditPage wants to parse its stuff from a WebRequest
186 // That interface kind of sucks, but it's workable
187 $reqArr = array(
188 'wpTextbox1' => $params['text'],
189 'wpEditToken' => $params['token'],
190 'wpIgnoreBlankSummary' => ''
193 if ( !is_null( $params['summary'] ) ) {
194 $reqArr['wpSummary'] = $params['summary'];
197 // Watch out for basetimestamp == ''
198 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
199 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
200 $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
201 } else {
202 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
205 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
206 $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
207 } else {
208 $reqArr['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
211 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
212 $reqArr['wpMinoredit'] = '';
215 if ( $params['recreate'] ) {
216 $reqArr['wpRecreate'] = '';
219 if ( !is_null( $params['section'] ) ) {
220 $section = intval( $params['section'] );
221 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
222 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
224 $reqArr['wpSection'] = $params['section'];
225 } else {
226 $reqArr['wpSection'] = '';
229 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
231 // Deprecated parameters
232 if ( $params['watch'] ) {
233 $watch = true;
234 } elseif ( $params['unwatch'] ) {
235 $watch = false;
238 if ( $watch ) {
239 $reqArr['wpWatchthis'] = '';
242 global $wgRequest;
243 $req = new DerivativeRequest( $wgRequest, $reqArr, true );
244 $ep->importFormData( $req );
246 // Run hooks
247 // Handle CAPTCHA parameters
248 if ( !is_null( $params['captchaid'] ) ) {
249 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
251 if ( !is_null( $params['captchaword'] ) ) {
252 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
255 $r = array();
256 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
257 if ( count( $r ) ) {
258 $r['result'] = 'Failure';
259 $apiResult->addValue( null, $this->getModuleName(), $r );
260 return;
261 } else {
262 $this->dieUsageMsg( 'hookaborted' );
266 // Do the actual save
267 $oldRevId = $articleObj->getRevIdFetched();
268 $result = null;
269 // Fake $wgRequest for some hooks inside EditPage
270 // @todo FIXME: This interface SUCKS
271 $oldRequest = $wgRequest;
272 $wgRequest = $req;
274 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
275 $wgRequest = $oldRequest;
276 global $wgMaxArticleSize;
278 switch( $status->value ) {
279 case EditPage::AS_HOOK_ERROR:
280 case EditPage::AS_HOOK_ERROR_EXPECTED:
281 $this->dieUsageMsg( 'hookaborted' );
283 case EditPage::AS_IMAGE_REDIRECT_ANON:
284 $this->dieUsageMsg( 'noimageredirect-anon' );
286 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
287 $this->dieUsageMsg( 'noimageredirect-logged' );
289 case EditPage::AS_SPAM_ERROR:
290 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
292 case EditPage::AS_FILTERING:
293 $this->dieUsageMsg( 'filtered' );
295 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
296 $this->dieUsageMsg( 'blockedtext' );
298 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
299 case EditPage::AS_CONTENT_TOO_BIG:
300 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
302 case EditPage::AS_READ_ONLY_PAGE_ANON:
303 $this->dieUsageMsg( 'noedit-anon' );
305 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
306 $this->dieUsageMsg( 'noedit' );
308 case EditPage::AS_READ_ONLY_PAGE:
309 $this->dieReadOnly();
311 case EditPage::AS_RATE_LIMITED:
312 $this->dieUsageMsg( 'actionthrottledtext' );
314 case EditPage::AS_ARTICLE_WAS_DELETED:
315 $this->dieUsageMsg( 'wasdeleted' );
317 case EditPage::AS_NO_CREATE_PERMISSION:
318 $this->dieUsageMsg( 'nocreate-loggedin' );
320 case EditPage::AS_BLANK_ARTICLE:
321 $this->dieUsageMsg( 'blankpage' );
323 case EditPage::AS_CONFLICT_DETECTED:
324 $this->dieUsageMsg( 'editconflict' );
326 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
327 case EditPage::AS_TEXTBOX_EMPTY:
328 $this->dieUsageMsg( 'emptynewsection' );
330 case EditPage::AS_SUCCESS_NEW_ARTICLE:
331 $r['new'] = '';
333 case EditPage::AS_SUCCESS_UPDATE:
334 $r['result'] = 'Success';
335 $r['pageid'] = intval( $titleObj->getArticleID() );
336 $r['title'] = $titleObj->getPrefixedText();
337 // HACK: We create a new Article object here because getRevIdFetched()
338 // refuses to be run twice, and because Title::getLatestRevId()
339 // won't fetch from the master unless we select for update, which we
340 // don't want to do.
341 $newArticle = new Article( $titleObj );
342 $newRevId = $newArticle->getRevIdFetched();
343 if ( $newRevId == $oldRevId ) {
344 $r['nochange'] = '';
345 } else {
346 $r['oldrevid'] = intval( $oldRevId );
347 $r['newrevid'] = intval( $newRevId );
348 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
349 $newArticle->getTimestamp() );
351 break;
353 case EditPage::AS_SUMMARY_NEEDED:
354 $this->dieUsageMsg( 'summaryrequired' );
356 case EditPage::AS_END:
357 // $status came from WikiPage::doEdit()
358 $errors = $status->getErrorsArray();
359 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
360 break;
361 default:
362 $this->dieUsageMsg( array( 'unknownerror', $status->value ) );
364 $apiResult->addValue( null, $this->getModuleName(), $r );
367 public function mustBePosted() {
368 return true;
371 public function isWriteMode() {
372 return true;
375 public function getDescription() {
376 return 'Create and edit pages.';
379 public function getPossibleErrors() {
380 global $wgMaxArticleSize;
382 return array_merge( parent::getPossibleErrors(), array(
383 array( 'missingtext' ),
384 array( 'invalidtitle', 'title' ),
385 array( 'createonly-exists' ),
386 array( 'nocreate-missing' ),
387 array( 'nosuchrevid', 'undo' ),
388 array( 'nosuchrevid', 'undoafter' ),
389 array( 'revwrongpage', 'id', 'text' ),
390 array( 'undo-failure' ),
391 array( 'hashcheckfailed' ),
392 array( 'hookaborted' ),
393 array( 'noimageredirect-anon' ),
394 array( 'noimageredirect-logged' ),
395 array( 'spamdetected', 'spam' ),
396 array( 'summaryrequired' ),
397 array( 'filtered' ),
398 array( 'blockedtext' ),
399 array( 'contenttoobig', $wgMaxArticleSize ),
400 array( 'noedit-anon' ),
401 array( 'noedit' ),
402 array( 'actionthrottledtext' ),
403 array( 'wasdeleted' ),
404 array( 'nocreate-loggedin' ),
405 array( 'blankpage' ),
406 array( 'editconflict' ),
407 array( 'emptynewsection' ),
408 array( 'unknownerror', 'retval' ),
409 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
410 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
411 array( 'customcssprotected' ),
412 array( 'customjsprotected' ),
413 ) );
416 public function getAllowedParams() {
417 return array(
418 'title' => array(
419 ApiBase::PARAM_TYPE => 'string',
420 ApiBase::PARAM_REQUIRED => true
422 'section' => null,
423 'text' => null,
424 'token' => null,
425 'summary' => null,
426 'minor' => false,
427 'notminor' => false,
428 'bot' => false,
429 'basetimestamp' => null,
430 'starttimestamp' => null,
431 'recreate' => false,
432 'createonly' => false,
433 'nocreate' => false,
434 'captchaword' => null,
435 'captchaid' => null,
436 'watch' => array(
437 ApiBase::PARAM_DFLT => false,
438 ApiBase::PARAM_DEPRECATED => true,
440 'unwatch' => array(
441 ApiBase::PARAM_DFLT => false,
442 ApiBase::PARAM_DEPRECATED => true,
444 'watchlist' => array(
445 ApiBase::PARAM_DFLT => 'preferences',
446 ApiBase::PARAM_TYPE => array(
447 'watch',
448 'unwatch',
449 'preferences',
450 'nochange'
453 'md5' => null,
454 'prependtext' => null,
455 'appendtext' => null,
456 'undo' => array(
457 ApiBase::PARAM_TYPE => 'integer'
459 'undoafter' => array(
460 ApiBase::PARAM_TYPE => 'integer'
462 'redirect' => array(
463 ApiBase::PARAM_TYPE => 'boolean',
464 ApiBase::PARAM_DFLT => false,
469 public function getParamDescription() {
470 $p = $this->getModulePrefix();
471 return array(
472 'title' => 'Page title',
473 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
474 'text' => 'Page content',
475 'token' => array( 'Edit token. You can get one of these through prop=info.',
476 'The token should always be sent as the last parameter, or at least, after the text parameter'
478 'summary' => 'Edit summary. Also section title when section=new',
479 'minor' => 'Minor edit',
480 'notminor' => 'Non-minor edit',
481 'bot' => 'Mark this edit as bot',
482 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
483 'Used to detect edit conflicts; leave unset to ignore conflicts.'
485 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
486 'Used to detect edit conflicts; leave unset to ignore conflicts'
488 'recreate' => 'Override any errors about the article having been deleted in the meantime',
489 'createonly' => 'Don\'t edit the page if it exists already',
490 'nocreate' => 'Throw an error if the page doesn\'t exist',
491 'watch' => 'Add the page to your watchlist',
492 'unwatch' => 'Remove the page from your watchlist',
493 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
494 'captchaid' => 'CAPTCHA ID from previous request',
495 'captchaword' => 'Answer to the CAPTCHA',
496 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
497 'If set, the edit won\'t be done unless the hash is correct' ),
498 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
499 'appendtext' => "Add this text to the end of the page. Overrides {$p}text",
500 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
501 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
502 'redirect' => 'Automatically resolve redirects',
506 public function needsToken() {
507 return true;
510 public function getTokenSalt() {
511 return '';
514 public function getExamples() {
515 return array(
516 'Edit a page (anonymous user):',
517 ' api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\',
518 'Prepend __NOTOC__ to a page (anonymous user):',
519 ' api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\',
520 'Undo r13579 through r13585 with autosummary (anonymous user):',
521 ' api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\',
525 public function getHelpUrls() {
526 return 'http://www.mediawiki.org/wiki/API:Edit';
529 public function getVersion() {
530 return __CLASS__ . ': $Id$';