4 * Created on August 16, 2007
6 * API for MediaWiki 1.8+
8 * Copyright © 2007 Iker Labarga <Firstname><Lastname>@gmail.com
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.
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.
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
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( "ApiBase.php" );
32 * A module that allows for editing and creating pages.
34 * Currently, this wraps around the EditPage class in an ugly way,
35 * EditPage.php should be rewritten to provide a cleaner interface
38 class ApiEditPage
extends ApiBase
{
40 public function __construct( $query, $moduleName ) {
41 parent
::__construct( $query, $moduleName );
44 public function execute() {
46 $params = $this->extractRequestParams();
48 if ( is_null( $params['title'] ) ) {
49 $this->dieUsageMsg( array( 'missingparam', 'title' ) );
52 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
53 is_null( $params['prependtext'] ) &&
54 $params['undo'] == 0 )
56 $this->dieUsageMsg( array( 'missingtext' ) );
59 $titleObj = Title
::newFromText( $params['title'] );
60 if ( !$titleObj ||
$titleObj->isExternal() ) {
61 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
64 // Some functions depend on $wgTitle == $ep->mTitle
68 if ( $params['createonly'] && $titleObj->exists() ) {
69 $this->dieUsageMsg( array( 'createonly-exists' ) );
71 if ( $params['nocreate'] && !$titleObj->exists() ) {
72 $this->dieUsageMsg( array( 'nocreate-missing' ) );
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 ) );
80 if ( count( $errors ) ) {
81 $this->dieUsageMsg( $errors[0] );
84 $articleObj = new Article( $titleObj );
85 $toMD5 = $params['text'];
86 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
88 // For non-existent pages, Article::getContent()
89 // returns an interface message rather than ''
90 // We do want getContent()'s behavior for non-existent
91 // MediaWiki: pages, though
92 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI
) {
95 $content = $articleObj->getContent();
98 if ( !is_null( $params['section'] ) ) {
99 // Process the content for section edits
101 $section = intval( $params['section'] );
102 $content = $wgParser->getSection( $content, $section, false );
103 if ( $content === false ) {
104 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
107 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
108 $toMD5 = $params['prependtext'] . $params['appendtext'];
111 if ( $params['undo'] > 0 ) {
112 if ( $params['undoafter'] > 0 ) {
113 if ( $params['undo'] < $params['undoafter'] ) {
114 list( $params['undo'], $params['undoafter'] ) =
115 array( $params['undoafter'], $params['undo'] );
117 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
119 $undoRev = Revision
::newFromID( $params['undo'] );
120 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) )
122 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
125 if ( $params['undoafter'] == 0 ) {
126 $undoafterRev = $undoRev->getPrevious();
128 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) )
130 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
133 if ( $undoRev->getPage() != $articleObj->getID() ) {
134 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
136 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
137 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
140 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
141 if ( $newtext === false ) {
142 $this->dieUsageMsg( array( 'undo-failure' ) );
144 $params['text'] = $newtext;
145 // If no summary was given and we only undid one rev,
146 // use an autosummary
147 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] )
149 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
153 // See if the MD5 hash checks out
154 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
155 $this->dieUsageMsg( array( 'hashcheckfailed' ) );
158 $ep = new EditPage( $articleObj );
159 // EditPage wants to parse its stuff from a WebRequest
160 // That interface kind of sucks, but it's workable
162 'wpTextbox1' => $params['text'],
163 'wpEditToken' => $params['token'],
164 'wpIgnoreBlankSummary' => ''
167 if ( !is_null( $params['summary'] ) ) {
168 $reqArr['wpSummary'] = $params['summary'];
171 // Watch out for basetimestamp == ''
172 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
173 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' )
175 $reqArr['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
177 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
180 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' )
182 $reqArr['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
184 $reqArr['wpStarttime'] = $reqArr['wpEdittime']; // Fake wpStartime
187 if ( $params['minor'] ||
( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) )
189 $reqArr['wpMinoredit'] = '';
192 if ( $params['recreate'] ) {
193 $reqArr['wpRecreate'] = '';
196 if ( !is_null( $params['section'] ) ) {
197 $section = intval( $params['section'] );
198 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' )
200 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
202 $reqArr['wpSection'] = $params['section'];
204 $reqArr['wpSection'] = '';
207 // Handle watchlist settings
208 switch ( $params['watchlist'] ) {
216 if ( $titleObj->exists() ) {
217 $watch = $wgUser->getOption( 'watchdefault' ) ||
$titleObj->userIsWatching();
219 $watch = $wgUser->getOption( 'watchcreations' );
224 $watch = $titleObj->userIsWatching();
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 ) ) )
254 $r['result'] = 'Failure';
255 $this->getResult()->addValue( null, $this->getModuleName(), $r );
258 $this->dieUsageMsg( array( 'hookaborted' ) );
262 // Do the actual save
263 $oldRevId = $articleObj->getRevIdFetched();
265 // Fake $wgRequest for some hooks inside EditPage
266 // FIXME: This interface SUCKS
267 $oldRequest = $wgRequest;
270 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
271 $wgRequest = $oldRequest;
273 case EditPage
::AS_HOOK_ERROR
:
274 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
275 $this->dieUsageMsg( array( 'hookaborted' ) );
277 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
278 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
280 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
281 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
283 case EditPage
::AS_SPAM_ERROR
:
284 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
286 case EditPage
::AS_FILTERING
:
287 $this->dieUsageMsg( array( 'filtered' ) );
289 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
290 $this->dieUsageMsg( array( 'blockedtext' ) );
292 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
293 case EditPage
::AS_CONTENT_TOO_BIG
:
294 global $wgMaxArticleSize;
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
:
327 case EditPage
::AS_SUCCESS_UPDATE
:
328 $r['result'] = 'Success';
329 $r['pageid'] = intval( $titleObj->getArticleID() );
330 $r['title'] = $titleObj->getPrefixedText();
331 // HACK: We create a new Article object here because getRevIdFetched()
332 // refuses to be run twice, and because Title::getLatestRevId()
333 // won't fetch from the master unless we select for update, which we
335 $newArticle = new Article( $titleObj );
336 $newRevId = $newArticle->getRevIdFetched();
337 if ( $newRevId == $oldRevId ) {
340 $r['oldrevid'] = intval( $oldRevId );
341 $r['newrevid'] = intval( $newRevId );
342 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
343 $newArticle->getTimestamp() );
347 case EditPage
::AS_END
:
348 // This usually means some kind of race condition
349 // or DB weirdness occurred. Fall through to throw an unknown
352 // This needs fixing higher up, as Article::doEdit should be
353 // used rather than Article::updateArticle, so that specific
354 // error conditions can be returned
356 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
358 $this->getResult()->addValue( null, $this->getModuleName(), $r );
361 public function mustBePosted() {
365 public function isWriteMode() {
369 protected function getDescription() {
370 return 'Create and edit pages.';
373 public function getPossibleErrors() {
374 global $wgMaxArticleSize;
376 return array_merge( parent
::getPossibleErrors(), array(
377 array( 'missingparam', 'title' ),
378 array( 'missingtext' ),
379 array( 'invalidtitle', 'title' ),
380 array( 'createonly-exists' ),
381 array( 'nocreate-missing' ),
382 array( 'nosuchrevid', 'undo' ),
383 array( 'nosuchrevid', 'undoafter' ),
384 array( 'revwrongpage', 'id', 'text' ),
385 array( 'undo-failure' ),
386 array( 'hashcheckfailed' ),
387 array( 'hookaborted' ),
388 array( 'noimageredirect-anon' ),
389 array( 'noimageredirect-logged' ),
390 array( 'spamdetected', 'spam' ),
392 array( 'blockedtext' ),
393 array( 'contenttoobig', $wgMaxArticleSize ),
394 array( 'noedit-anon' ),
396 array( 'actionthrottledtext' ),
397 array( 'wasdeleted' ),
398 array( 'nocreate-loggedin' ),
399 array( 'blankpage' ),
400 array( 'editconflict' ),
401 array( 'emptynewsection' ),
402 array( 'unknownerror', 'retval' ),
403 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
404 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
408 protected function getAllowedParams() {
418 'basetimestamp' => null,
419 'starttimestamp' => null,
421 'createonly' => false,
423 'captchaword' => null,
426 ApiBase
::PARAM_DFLT
=> false,
427 ApiBase
::PARAM_DEPRECATED
=> true,
430 ApiBase
::PARAM_DFLT
=> false,
431 ApiBase
::PARAM_DEPRECATED
=> true,
433 'watchlist' => array(
434 ApiBase
::PARAM_DFLT
=> 'preferences',
435 ApiBase
::PARAM_TYPE
=> array(
443 'prependtext' => null,
444 'appendtext' => null,
446 ApiBase
::PARAM_TYPE
=> 'integer'
448 'undoafter' => array(
449 ApiBase
::PARAM_TYPE
=> 'integer'
454 protected function getParamDescription() {
456 'title' => 'Page title',
457 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
458 'text' => 'Page content',
459 'token' => 'Edit token. You can get one of these through prop=info',
460 'summary' => 'Edit summary. Also section title when section=new',
461 'minor' => 'Minor edit',
462 'notminor' => 'Non-minor edit',
463 'bot' => 'Mark this edit as bot',
464 'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
465 'Used to detect edit conflicts; leave unset to ignore conflicts.'
467 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
468 'Used to detect edit conflicts; leave unset to ignore conflicts.'
470 'recreate' => 'Override any errors about the article having been deleted in the meantime',
471 'createonly' => 'Don\'t edit the page if it exists already',
472 'nocreate' => 'Throw an error if the page doesn\'t exist',
473 'watch' => 'Add the page to your watchlist',
474 'unwatch' => 'Remove the page from your watchlist',
475 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
476 'captchaid' => 'CAPTCHA ID from previous request',
477 'captchaword' => 'Answer to the CAPTCHA',
478 'md5' => array( 'The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated.',
479 'If set, the edit won\'t be done unless the hash is correct' ),
480 'prependtext' => 'Add this text to the beginning of the page. Overrides text.',
481 'appendtext' => 'Add this text to the end of the page. Overrides text',
482 'undo' => 'Undo this revision. Overrides text, prependtext and appendtext',
483 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
487 public function getTokenSalt() {
491 protected function getExamples() {
493 'Edit a page (anonymous user):',
494 ' api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\',
495 'Prepend __NOTOC__ to a page (anonymous user):',
496 ' api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\',
497 'Undo r13579 through r13585 with autosummary (anonymous user):',
498 ' api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\',
502 public function getVersion() {
503 return __CLASS__
. ': $Id$';