3 * API for MediaWiki 1.8+
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
27 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiBase.php" );
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
39 class ApiEditPage extends ApiBase {
41 public function __construct( $query, $moduleName ) {
42 parent::__construct( $query, $moduleName );
45 public function execute() {
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 ) );
67 $redirValues = array();
68 foreach ( $titles as $id => $newTitle ) {
70 if( !isset( $titles[ $id - 1 ] ) ) {
71 $titles[ $id - 1 ] = $oldTitle;
74 $redirValues[] = array(
75 'from' => $titles[ $id - 1 ]->getPrefixedText(),
76 'to' => $newTitle->getPrefixedText()
79 $titleObj = $newTitle;
82 $this->getResult()->setIndexedTagName( $redirValues, 'r' );
83 $this->getResult()->addValue( null, 'redirects', $redirValues );
88 // Some functions depend on $wgTitle == $ep->mTitle
92 if ( $params['createonly'] && $titleObj->exists() ) {
93 $this->dieUsageMsg( array( 'createonly-exists' ) );
95 if ( $params['nocreate'] && !$titleObj->exists() ) {
96 $this->dieUsageMsg( array( 'nocreate-missing' ) );
99 // Now let's check whether we're even allowed to do this
100 $errors = $titleObj->getUserPermissionsErrors( 'edit', $wgUser );
101 if ( !$titleObj->exists() ) {
102 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $wgUser ) );
104 if ( count( $errors ) ) {
105 $this->dieUsageMsg( $errors[0] );
108 $articleObj = new Article( $titleObj );
109 $toMD5 = $params['text'];
110 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
112 // For non-existent pages, Article::getContent()
113 // returns an interface message rather than ''
114 // We do want getContent()'s behavior for non-existent
115 // MediaWiki: pages, though
116 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI ) {
119 $content = $articleObj->getContent();
122 if ( !is_null( $params['section'] ) ) {
123 // Process the content for section edits
125 $section = intval( $params['section'] );
126 $content = $wgParser->getSection( $content, $section, false );
127 if ( $content === false ) {
128 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
131 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
132 $toMD5 = $params['prependtext'] . $params['appendtext'];
135 if ( $params['undo'] > 0 ) {
136 if ( $params['undoafter'] > 0 ) {
137 if ( $params['undo'] < $params['undoafter'] ) {
138 list( $params['undo'], $params['undoafter'] ) =
139 array( $params['undoafter'], $params['undo'] );
141 $undoafterRev = Revision::newFromID( $params['undoafter'] );
143 $undoRev = Revision::newFromID( $params['undo'] );
144 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
145 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
148 if ( $params['undoafter'] == 0 ) {
149 $undoafterRev = $undoRev->getPrevious();
151 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
152 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
155 if ( $undoRev->getPage() != $articleObj->getID() ) {
156 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
158 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
159 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
162 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
163 if ( $newtext === false ) {
164 $this->dieUsageMsg( array( 'undo-failure' ) );
166 $params['text'] = $newtext;
167 // If no summary was given and we only undid one rev,
168 // use an autosummary
169 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
170 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
174 // See if the MD5 hash checks out
175 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
176 $this->dieUsageMsg( array( 'hashcheckfailed' ) );
179 $ep = new EditPage( $articleObj );
180 // EditPage wants to parse its stuff from a WebRequest
181 // That interface kind of sucks, but it's workable
183 'wpTextbox1' => $params['text'],
184 'wpEditToken' => $params['token'],
185 'wpIgnoreBlankSummary' => ''
188 if ( !is_null( $params['summary'] ) ) {
189 $reqArr['wpSummary'] = $params['summary'];
192 // Watch out for basetimestamp == ''
193 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
194 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
195 $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
197 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
200 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
201 $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
203 $reqArr['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
206 if ( $params['minor'] || ( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) ) {
207 $reqArr['wpMinoredit'] = '';
210 if ( $params['recreate'] ) {
211 $reqArr['wpRecreate'] = '';
214 if ( !is_null( $params['section'] ) ) {
215 $section = intval( $params['section'] );
216 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
217 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
219 $reqArr['wpSection'] = $params['section'];
221 $reqArr['wpSection'] = '';
224 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
226 // Deprecated parameters
227 if ( $params['watch'] ) {
229 } elseif ( $params['unwatch'] ) {
234 $reqArr['wpWatchthis'] = '';
237 $req = new FauxRequest( $reqArr, true );
238 $ep->importFormData( $req );
241 // Handle CAPTCHA parameters
243 if ( !is_null( $params['captchaid'] ) ) {
244 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
246 if ( !is_null( $params['captchaword'] ) ) {
247 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
251 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
253 $r['result'] = 'Failure';
254 $this->getResult()->addValue( null, $this->getModuleName(), $r );
257 $this->dieUsageMsg( array( 'hookaborted' ) );
261 // Do the actual save
262 $oldRevId = $articleObj->getRevIdFetched();
264 // Fake $wgRequest for some hooks inside EditPage
265 // FIXME: This interface SUCKS
266 $oldRequest = $wgRequest;
269 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
270 $wgRequest = $oldRequest;
271 global $wgMaxArticleSize;
274 case EditPage::AS_HOOK_ERROR:
275 case EditPage::AS_HOOK_ERROR_EXPECTED:
276 $this->dieUsageMsg( array( 'hookaborted' ) );
278 case EditPage::AS_IMAGE_REDIRECT_ANON:
279 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
281 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
282 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
284 case EditPage::AS_SPAM_ERROR:
285 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
287 case EditPage::AS_FILTERING:
288 $this->dieUsageMsg( array( 'filtered' ) );
290 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
291 $this->dieUsageMsg( array( 'blockedtext' ) );
293 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
294 case EditPage::AS_CONTENT_TOO_BIG:
295 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
297 case EditPage::AS_READ_ONLY_PAGE_ANON:
298 $this->dieUsageMsg( array( 'noedit-anon' ) );
300 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
301 $this->dieUsageMsg( array( 'noedit' ) );
303 case EditPage::AS_READ_ONLY_PAGE:
304 $this->dieReadOnly();
306 case EditPage::AS_RATE_LIMITED:
307 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
309 case EditPage::AS_ARTICLE_WAS_DELETED:
310 $this->dieUsageMsg( array( 'wasdeleted' ) );
312 case EditPage::AS_NO_CREATE_PERMISSION:
313 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
315 case EditPage::AS_BLANK_ARTICLE:
316 $this->dieUsageMsg( array( 'blankpage' ) );
318 case EditPage::AS_CONFLICT_DETECTED:
319 $this->dieUsageMsg( array( 'editconflict' ) );
321 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
322 case EditPage::AS_TEXTBOX_EMPTY:
323 $this->dieUsageMsg( array( 'emptynewsection' ) );
325 case EditPage::AS_SUCCESS_NEW_ARTICLE:
328 case EditPage::AS_SUCCESS_UPDATE:
329 $r['result'] = 'Success';
330 $r['pageid'] = intval( $titleObj->getArticleID() );
331 $r['title'] = $titleObj->getPrefixedText();
332 // HACK: We create a new Article object here because getRevIdFetched()
333 // refuses to be run twice, and because Title::getLatestRevId()
334 // won't fetch from the master unless we select for update, which we
336 $newArticle = new Article( $titleObj );
337 $newRevId = $newArticle->getRevIdFetched();
338 if ( $newRevId == $oldRevId ) {
341 $r['oldrevid'] = intval( $oldRevId );
342 $r['newrevid'] = intval( $newRevId );
343 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
344 $newArticle->getTimestamp() );
348 case EditPage::AS_SUMMARY_NEEDED:
349 $this->dieUsageMsg( array( 'summaryrequired' ) );
351 case EditPage::AS_END:
352 // This usually means some kind of race condition
353 // or DB weirdness occurred. Fall through to throw an unknown
356 // This needs fixing higher up, as Article::doEdit should be
357 // used rather than Article::updateArticle, so that specific
358 // error conditions can be returned
360 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
362 $this->getResult()->addValue( null, $this->getModuleName(), $r );
365 public function mustBePosted() {
369 public function isWriteMode() {
373 protected function getDescription() {
374 return 'Create and edit pages.';
377 public function getPossibleErrors() {
378 global $wgMaxArticleSize;
380 return array_merge( parent::getPossibleErrors(), array(
381 array( 'missingtext' ),
382 array( 'invalidtitle', 'title' ),
383 array( 'createonly-exists' ),
384 array( 'nocreate-missing' ),
385 array( 'nosuchrevid', 'undo' ),
386 array( 'nosuchrevid', 'undoafter' ),
387 array( 'revwrongpage', 'id', 'text' ),
388 array( 'undo-failure' ),
389 array( 'hashcheckfailed' ),
390 array( 'hookaborted' ),
391 array( 'noimageredirect-anon' ),
392 array( 'noimageredirect-logged' ),
393 array( 'spamdetected', 'spam' ),
394 array( 'summaryrequired' ),
396 array( 'blockedtext' ),
397 array( 'contenttoobig', $wgMaxArticleSize ),
398 array( 'noedit-anon' ),
400 array( 'actionthrottledtext' ),
401 array( 'wasdeleted' ),
402 array( 'nocreate-loggedin' ),
403 array( 'blankpage' ),
404 array( 'editconflict' ),
405 array( 'emptynewsection' ),
406 array( 'unknownerror', 'retval' ),
407 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
408 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
412 protected function getAllowedParams() {
415 ApiBase::PARAM_TYPE => 'string',
416 ApiBase::PARAM_REQUIRED => true
425 'basetimestamp' => null,
426 'starttimestamp' => null,
428 'createonly' => false,
430 'captchaword' => null,
433 ApiBase::PARAM_DFLT => false,
434 ApiBase::PARAM_DEPRECATED => true,
437 ApiBase::PARAM_DFLT => false,
438 ApiBase::PARAM_DEPRECATED => true,
440 'watchlist' => array(
441 ApiBase::PARAM_DFLT => 'preferences',
442 ApiBase::PARAM_TYPE => array(
450 'prependtext' => null,
451 'appendtext' => null,
453 ApiBase::PARAM_TYPE => 'integer'
455 'undoafter' => array(
456 ApiBase::PARAM_TYPE => 'integer'
459 ApiBase::PARAM_TYPE => 'boolean',
460 ApiBase::PARAM_DFLT => false,
465 protected function getParamDescription() {
466 $p = $this->getModulePrefix();
468 'title' => 'Page title',
469 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
470 'text' => 'Page content',
471 'token' => 'Edit token. You can get one of these through prop=info',
472 'summary' => 'Edit summary. Also section title when section=new',
473 'minor' => 'Minor edit',
474 'notminor' => 'Non-minor edit',
475 'bot' => 'Mark this edit as bot',
476 'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
477 'Used to detect edit conflicts; leave unset to ignore conflicts.'
479 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
480 'Used to detect edit conflicts; leave unset to ignore conflicts'
482 'recreate' => 'Override any errors about the article having been deleted in the meantime',
483 'createonly' => 'Don\'t edit the page if it exists already',
484 'nocreate' => 'Throw an error if the page doesn\'t exist',
485 'watch' => 'Add the page to your watchlist',
486 'unwatch' => 'Remove the page from your watchlist',
487 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
488 'captchaid' => 'CAPTCHA ID from previous request',
489 'captchaword' => 'Answer to the CAPTCHA',
490 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
491 'If set, the edit won\'t be done unless the hash is correct' ),
492 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
493 'appendtext' => "Add this text to the end of the page. Overrides {$p}text",
494 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
495 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
496 'redirect' => 'Automatically resolve redirects',
500 public function needsToken() {
504 public function getTokenSalt() {
508 protected function getExamples() {
510 'Edit a page (anonymous user):',
511 ' api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\',
512 'Prepend __NOTOC__ to a page (anonymous user):',
513 ' api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\',
514 'Undo r13579 through r13585 with autosummary (anonymous user):',
515 ' api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\',
519 public function getVersion() {
520 return __CLASS__ . ': $Id: ApiEditPage.php 90492 2011-06-20 22:39:10Z reedy $';