* (bug 27376) when using ApiBase::PARAM_TYPE => 'integer' without a min or max value...
[mediawiki.git] / includes / api / ApiEditPage.php
blobe7797476bf7d12940339c30425a4a0fa9c97d252
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 global $wgUser;
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( array( 'missingtext' ) );
56 $titleObj = Title::newFromText( $params['title'] );
57 if ( !$titleObj || $titleObj->isExternal() ) {
58 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
61 if ( $params['redirect'] ) {
62 if ( $titleObj->isRedirect() ) {
63 $oldTitle = $titleObj;
65 $titles = Title::newFromRedirectArray( Revision::newFromTitle( $oldTitle )->getText( Revision::FOR_THIS_USER ) );
66 // array_shift( $titles );
68 $this->getResult()->addValue( null, 'foo', $titles );
71 $redirValues = array();
72 foreach ( $titles as $id => $newTitle ) {
74 if ( !isset( $titles[ $id - 1 ] ) ) {
75 $titles[ $id - 1 ] = $oldTitle;
78 $redirValues[] = array(
79 'from' => $titles[ $id - 1 ]->getPrefixedText(),
80 'to' => $newTitle->getPrefixedText()
83 $titleObj = $newTitle;
86 $this->getResult()->setIndexedTagName( $redirValues, 'r' );
87 $this->getResult()->addValue( null, 'redirects', $redirValues );
92 // Some functions depend on $wgTitle == $ep->mTitle
93 global $wgTitle;
94 $wgTitle = $titleObj;
96 if ( $params['createonly'] && $titleObj->exists() ) {
97 $this->dieUsageMsg( array( 'createonly-exists' ) );
99 if ( $params['nocreate'] && !$titleObj->exists() ) {
100 $this->dieUsageMsg( array( 'nocreate-missing' ) );
103 // Now let's check whether we're even allowed to do this
104 $errors = $titleObj->getUserPermissionsErrors( 'edit', $wgUser );
105 if ( !$titleObj->exists() ) {
106 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $wgUser ) );
108 if ( count( $errors ) ) {
109 $this->dieUsageMsg( $errors[0] );
112 $articleObj = new Article( $titleObj );
113 $toMD5 = $params['text'];
114 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
116 // For non-existent pages, Article::getContent()
117 // returns an interface message rather than ''
118 // We do want getContent()'s behavior for non-existent
119 // MediaWiki: pages, though
120 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI ) {
121 $content = '';
122 } else {
123 $content = $articleObj->getContent();
126 if ( !is_null( $params['section'] ) ) {
127 // Process the content for section edits
128 global $wgParser;
129 $section = intval( $params['section'] );
130 $content = $wgParser->getSection( $content, $section, false );
131 if ( $content === false ) {
132 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
135 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
136 $toMD5 = $params['prependtext'] . $params['appendtext'];
139 if ( $params['undo'] > 0 ) {
140 if ( $params['undoafter'] > 0 ) {
141 if ( $params['undo'] < $params['undoafter'] ) {
142 list( $params['undo'], $params['undoafter'] ) =
143 array( $params['undoafter'], $params['undo'] );
145 $undoafterRev = Revision::newFromID( $params['undoafter'] );
147 $undoRev = Revision::newFromID( $params['undo'] );
148 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
149 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
152 if ( $params['undoafter'] == 0 ) {
153 $undoafterRev = $undoRev->getPrevious();
155 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
156 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
159 if ( $undoRev->getPage() != $articleObj->getID() ) {
160 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
162 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
163 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
166 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
167 if ( $newtext === false ) {
168 $this->dieUsageMsg( array( 'undo-failure' ) );
170 $params['text'] = $newtext;
171 // If no summary was given and we only undid one rev,
172 // use an autosummary
173 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
174 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
178 // See if the MD5 hash checks out
179 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
180 $this->dieUsageMsg( array( 'hashcheckfailed' ) );
183 $ep = new EditPage( $articleObj );
184 $ep->setContextTitle( $titleObj );
186 // EditPage wants to parse its stuff from a WebRequest
187 // That interface kind of sucks, but it's workable
188 $reqArr = array(
189 'wpTextbox1' => $params['text'],
190 'wpEditToken' => $params['token'],
191 'wpIgnoreBlankSummary' => ''
194 if ( !is_null( $params['summary'] ) ) {
195 $reqArr['wpSummary'] = $params['summary'];
198 // Watch out for basetimestamp == ''
199 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
200 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
201 $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
202 } else {
203 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
206 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
207 $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
208 } else {
209 $reqArr['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
212 if ( $params['minor'] || ( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) ) {
213 $reqArr['wpMinoredit'] = '';
216 if ( $params['recreate'] ) {
217 $reqArr['wpRecreate'] = '';
220 if ( !is_null( $params['section'] ) ) {
221 $section = intval( $params['section'] );
222 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
223 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
225 $reqArr['wpSection'] = $params['section'];
226 } else {
227 $reqArr['wpSection'] = '';
230 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
232 // Deprecated parameters
233 if ( $params['watch'] ) {
234 $watch = true;
235 } elseif ( $params['unwatch'] ) {
236 $watch = false;
239 if ( $watch ) {
240 $reqArr['wpWatchthis'] = '';
243 $req = new FauxRequest( $reqArr, true );
244 $ep->importFormData( $req );
246 // Run hooks
247 // Handle CAPTCHA parameters
248 global $wgRequest;
249 if ( !is_null( $params['captchaid'] ) ) {
250 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
252 if ( !is_null( $params['captchaword'] ) ) {
253 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
256 $r = array();
257 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
258 if ( count( $r ) ) {
259 $r['result'] = 'Failure';
260 $this->getResult()->addValue( null, $this->getModuleName(), $r );
261 return;
262 } else {
263 $this->dieUsageMsg( array( 'hookaborted' ) );
267 // Do the actual save
268 $oldRevId = $articleObj->getRevIdFetched();
269 $result = null;
270 // Fake $wgRequest for some hooks inside EditPage
271 // FIXME: This interface SUCKS
272 $oldRequest = $wgRequest;
273 $wgRequest = $req;
275 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
276 $wgRequest = $oldRequest;
277 global $wgMaxArticleSize;
279 switch( $retval ) {
280 case EditPage::AS_HOOK_ERROR:
281 case EditPage::AS_HOOK_ERROR_EXPECTED:
282 $this->dieUsageMsg( array( 'hookaborted' ) );
284 case EditPage::AS_IMAGE_REDIRECT_ANON:
285 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
287 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
288 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
290 case EditPage::AS_SPAM_ERROR:
291 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
293 case EditPage::AS_FILTERING:
294 $this->dieUsageMsg( array( 'filtered' ) );
296 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
297 $this->dieUsageMsg( array( 'blockedtext' ) );
299 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
300 case EditPage::AS_CONTENT_TOO_BIG:
301 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
303 case EditPage::AS_READ_ONLY_PAGE_ANON:
304 $this->dieUsageMsg( array( 'noedit-anon' ) );
306 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
307 $this->dieUsageMsg( array( 'noedit' ) );
309 case EditPage::AS_READ_ONLY_PAGE:
310 $this->dieReadOnly();
312 case EditPage::AS_RATE_LIMITED:
313 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
315 case EditPage::AS_ARTICLE_WAS_DELETED:
316 $this->dieUsageMsg( array( 'wasdeleted' ) );
318 case EditPage::AS_NO_CREATE_PERMISSION:
319 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
321 case EditPage::AS_BLANK_ARTICLE:
322 $this->dieUsageMsg( array( 'blankpage' ) );
324 case EditPage::AS_CONFLICT_DETECTED:
325 $this->dieUsageMsg( array( 'editconflict' ) );
327 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
328 case EditPage::AS_TEXTBOX_EMPTY:
329 $this->dieUsageMsg( array( 'emptynewsection' ) );
331 case EditPage::AS_SUCCESS_NEW_ARTICLE:
332 $r['new'] = '';
334 case EditPage::AS_SUCCESS_UPDATE:
335 $r['result'] = 'Success';
336 $r['pageid'] = intval( $titleObj->getArticleID() );
337 $r['title'] = $titleObj->getPrefixedText();
338 // HACK: We create a new Article object here because getRevIdFetched()
339 // refuses to be run twice, and because Title::getLatestRevId()
340 // won't fetch from the master unless we select for update, which we
341 // don't want to do.
342 $newArticle = new Article( $titleObj );
343 $newRevId = $newArticle->getRevIdFetched();
344 if ( $newRevId == $oldRevId ) {
345 $r['nochange'] = '';
346 } else {
347 $r['oldrevid'] = intval( $oldRevId );
348 $r['newrevid'] = intval( $newRevId );
349 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
350 $newArticle->getTimestamp() );
352 break;
354 case EditPage::AS_SUMMARY_NEEDED:
355 $this->dieUsageMsg( array( 'summaryrequired' ) );
357 case EditPage::AS_END:
358 // This usually means some kind of race condition
359 // or DB weirdness occurred. Fall through to throw an unknown
360 // error.
362 // This needs fixing higher up, as Article::doEdit should be
363 // used rather than Article::updateArticle, so that specific
364 // error conditions can be returned
365 default:
366 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
368 $this->getResult()->addValue( null, $this->getModuleName(), $r );
371 public function mustBePosted() {
372 return true;
375 public function isWriteMode() {
376 return true;
379 protected function getDescription() {
380 return 'Create and edit pages.';
383 public function getPossibleErrors() {
384 global $wgMaxArticleSize;
386 return array_merge( parent::getPossibleErrors(), array(
387 array( 'missingtext' ),
388 array( 'invalidtitle', 'title' ),
389 array( 'createonly-exists' ),
390 array( 'nocreate-missing' ),
391 array( 'nosuchrevid', 'undo' ),
392 array( 'nosuchrevid', 'undoafter' ),
393 array( 'revwrongpage', 'id', 'text' ),
394 array( 'undo-failure' ),
395 array( 'hashcheckfailed' ),
396 array( 'hookaborted' ),
397 array( 'noimageredirect-anon' ),
398 array( 'noimageredirect-logged' ),
399 array( 'spamdetected', 'spam' ),
400 array( 'summaryrequired' ),
401 array( 'filtered' ),
402 array( 'blockedtext' ),
403 array( 'contenttoobig', $wgMaxArticleSize ),
404 array( 'noedit-anon' ),
405 array( 'noedit' ),
406 array( 'actionthrottledtext' ),
407 array( 'wasdeleted' ),
408 array( 'nocreate-loggedin' ),
409 array( 'blankpage' ),
410 array( 'editconflict' ),
411 array( 'emptynewsection' ),
412 array( 'unknownerror', 'retval' ),
413 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
414 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
415 ) );
418 protected function getAllowedParams() {
419 return array(
420 'title' => array(
421 ApiBase::PARAM_TYPE => 'string',
422 ApiBase::PARAM_REQUIRED => true
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,
442 'unwatch' => array(
443 ApiBase::PARAM_DFLT => false,
444 ApiBase::PARAM_DEPRECATED => true,
446 'watchlist' => array(
447 ApiBase::PARAM_DFLT => 'preferences',
448 ApiBase::PARAM_TYPE => array(
449 'watch',
450 'unwatch',
451 'preferences',
452 'nochange'
455 'md5' => null,
456 'prependtext' => null,
457 'appendtext' => null,
458 'undo' => array(
459 ApiBase::PARAM_TYPE => 'integer'
461 'undoafter' => array(
462 ApiBase::PARAM_TYPE => 'integer'
464 'redirect' => array(
465 ApiBase::PARAM_TYPE => 'boolean',
466 ApiBase::PARAM_DFLT => false,
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' => 'Edit token. You can get one of these through prop=info',
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 (gotten 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 protected 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 getVersion() {
526 return __CLASS__ . ': $Id$';