4 * Created on August 16, 2007
6 * API for MediaWiki 1.8+
8 * Copyright (C) 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' ) );
51 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
52 is_null( $params['prependtext'] ) &&
53 $params['undo'] == 0 )
54 $this->dieUsageMsg( array( 'missingtext' ) );
56 $titleObj = Title
::newFromText( $params['title'] );
57 if ( !$titleObj ||
$titleObj->isExternal() )
58 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
60 // Some functions depend on $wgTitle == $ep->mTitle
64 if ( $params['createonly'] && $titleObj->exists() )
65 $this->dieUsageMsg( array( 'createonly-exists' ) );
66 if ( $params['nocreate'] && !$titleObj->exists() )
67 $this->dieUsageMsg( array( 'nocreate-missing' ) );
69 // Now let's check whether we're even allowed to do this
70 $errors = $titleObj->getUserPermissionsErrors( 'edit', $wgUser );
71 if ( !$titleObj->exists() )
72 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $wgUser ) );
73 if ( count( $errors ) )
74 $this->dieUsageMsg( $errors[0] );
76 $articleObj = new Article( $titleObj );
77 $toMD5 = $params['text'];
78 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
80 // For non-existent pages, Article::getContent()
81 // returns an interface message rather than ''
82 // We do want getContent()'s behavior for non-existent
83 // MediaWiki: pages, though
84 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI
)
87 $content = $articleObj->getContent();
89 if ( !is_null( $params['section'] ) )
91 // Process the content for section edits
93 $section = intval( $params['section'] );
94 $content = $wgParser->getSection( $content, $section, false );
95 if ( $content === false )
96 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
98 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
99 $toMD5 = $params['prependtext'] . $params['appendtext'];
102 if ( $params['undo'] > 0 )
104 if ( $params['undoafter'] > 0 )
106 if ( $params['undo'] < $params['undoafter'] )
107 list( $params['undo'], $params['undoafter'] ) =
108 array( $params['undoafter'], $params['undo'] );
109 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
111 $undoRev = Revision
::newFromID( $params['undo'] );
112 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) )
113 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
115 if ( $params['undoafter'] == 0 )
116 $undoafterRev = $undoRev->getPrevious();
117 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) )
118 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
120 if ( $undoRev->getPage() != $articleObj->getID() )
121 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
122 if ( $undoafterRev->getPage() != $articleObj->getID() )
123 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
125 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
126 if ( $newtext === false )
127 $this->dieUsageMsg( array( 'undo-failure' ) );
128 $params['text'] = $newtext;
129 // If no summary was given and we only undid one rev,
130 // use an autosummary
131 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] )
132 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
135 // See if the MD5 hash checks out
136 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] )
137 $this->dieUsageMsg( array( 'hashcheckfailed' ) );
139 $ep = new EditPage( $articleObj );
140 // EditPage wants to parse its stuff from a WebRequest
141 // That interface kind of sucks, but it's workable
142 $reqArr = array( 'wpTextbox1' => $params['text'],
143 'wpEditToken' => $params['token'],
144 'wpIgnoreBlankSummary' => ''
147 if ( !is_null( $params['summary'] ) )
148 $reqArr['wpSummary'] = $params['summary'];
150 // Watch out for basetimestamp == ''
151 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
152 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' )
153 $reqArr['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
155 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
157 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' )
158 $reqArr['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
160 $reqArr['wpStarttime'] = $reqArr['wpEdittime']; // Fake wpStartime
162 if ( $params['minor'] ||
( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) )
163 $reqArr['wpMinoredit'] = '';
165 if ( $params['recreate'] )
166 $reqArr['wpRecreate'] = '';
168 if ( !is_null( $params['section'] ) )
170 $section = intval( $params['section'] );
171 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' )
172 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
173 $reqArr['wpSection'] = $params['section'];
176 $reqArr['wpSection'] = '';
178 // Handle watchlist settings
179 switch ( $params['watchlist'] )
188 if ( $titleObj->exists() )
189 $watch = $wgUser->getOption( 'watchdefault' ) ||
$titleObj->userIsWatching();
191 $watch = $wgUser->getOption( 'watchcreations' );
195 $watch = $titleObj->userIsWatching();
197 // Deprecated parameters
198 if ( $params['watch'] )
200 elseif ( $params['unwatch'] )
204 $reqArr['wpWatchthis'] = '';
206 $req = new FauxRequest( $reqArr, true );
207 $ep->importFormData( $req );
210 // Handle CAPTCHA parameters
212 if ( !is_null( $params['captchaid'] ) )
213 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
214 if ( !is_null( $params['captchaword'] ) )
215 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
218 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) )
222 $r['result'] = "Failure";
223 $this->getResult()->addValue( null, $this->getModuleName(), $r );
227 $this->dieUsageMsg( array( 'hookaborted' ) );
230 // Do the actual save
231 $oldRevId = $articleObj->getRevIdFetched();
233 // Fake $wgRequest for some hooks inside EditPage
234 // FIXME: This interface SUCKS
235 $oldRequest = $wgRequest;
238 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
239 $wgRequest = $oldRequest;
242 case EditPage
::AS_HOOK_ERROR
:
243 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
244 $this->dieUsageMsg( array( 'hookaborted' ) );
246 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
247 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
249 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
250 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
252 case EditPage
::AS_SPAM_ERROR
:
253 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
255 case EditPage
::AS_FILTERING
:
256 $this->dieUsageMsg( array( 'filtered' ) );
258 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
259 $this->dieUsageMsg( array( 'blockedtext' ) );
261 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
262 case EditPage
::AS_CONTENT_TOO_BIG
:
263 global $wgMaxArticleSize;
264 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
266 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
267 $this->dieUsageMsg( array( 'noedit-anon' ) );
269 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
270 $this->dieUsageMsg( array( 'noedit' ) );
272 case EditPage
::AS_READ_ONLY_PAGE
:
273 $this->dieReadOnly();
275 case EditPage
::AS_RATE_LIMITED
:
276 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
278 case EditPage
::AS_ARTICLE_WAS_DELETED
:
279 $this->dieUsageMsg( array( 'wasdeleted' ) );
281 case EditPage
::AS_NO_CREATE_PERMISSION
:
282 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
284 case EditPage
::AS_BLANK_ARTICLE
:
285 $this->dieUsageMsg( array( 'blankpage' ) );
287 case EditPage
::AS_CONFLICT_DETECTED
:
288 $this->dieUsageMsg( array( 'editconflict' ) );
290 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
291 case EditPage
::AS_TEXTBOX_EMPTY
:
292 $this->dieUsageMsg( array( 'emptynewsection' ) );
294 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
296 case EditPage
::AS_SUCCESS_UPDATE
:
297 $r['result'] = "Success";
298 $r['pageid'] = intval( $titleObj->getArticleID() );
299 $r['title'] = $titleObj->getPrefixedText();
300 // HACK: We create a new Article object here because getRevIdFetched()
301 // refuses to be run twice, and because Title::getLatestRevId()
302 // won't fetch from the master unless we select for update, which we
304 $newArticle = new Article( $titleObj );
305 $newRevId = $newArticle->getRevIdFetched();
306 if ( $newRevId == $oldRevId )
310 $r['oldrevid'] = intval( $oldRevId );
311 $r['newrevid'] = intval( $newRevId );
312 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
313 $newArticle->getTimestamp() );
317 case EditPage
::AS_END
:
318 // This usually means some kind of race condition
319 // or DB weirdness occurred. Fall through to throw an unknown
322 // This needs fixing higher up, as Article::doEdit should be
323 // used rather than Article::updateArticle, so that specific
324 // error conditions can be returned
326 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
328 $this->getResult()->addValue( null, $this->getModuleName(), $r );
331 public function mustBePosted() {
335 public function isWriteMode() {
339 protected function getDescription() {
340 return 'Create and edit pages.';
343 public function getPossibleErrors() {
344 global $wgMaxArticleSize;
346 return array_merge( parent
::getPossibleErrors(), array(
347 array( 'missingparam', 'title' ),
348 array( 'missingtext' ),
349 array( 'invalidtitle', 'title' ),
350 array( 'createonly-exists' ),
351 array( 'nocreate-missing' ),
352 array( 'nosuchrevid', 'undo' ),
353 array( 'nosuchrevid', 'undoafter' ),
354 array( 'revwrongpage', 'id', 'text' ),
355 array( 'undo-failure' ),
356 array( 'hashcheckfailed' ),
357 array( 'hookaborted' ),
358 array( 'noimageredirect-anon' ),
359 array( 'noimageredirect-logged' ),
360 array( 'spamdetected', 'spam' ),
362 array( 'blockedtext' ),
363 array( 'contenttoobig', $wgMaxArticleSize ),
364 array( 'noedit-anon' ),
366 array( 'actionthrottledtext' ),
367 array( 'wasdeleted' ),
368 array( 'nocreate-loggedin' ),
369 array( 'blankpage' ),
370 array( 'editconflict' ),
371 array( 'emptynewsection' ),
372 array( 'unknownerror', 'retval' ),
373 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
374 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
378 protected function getAllowedParams() {
388 'basetimestamp' => null,
389 'starttimestamp' => null,
391 'createonly' => false,
393 'captchaword' => null,
396 ApiBase
:: PARAM_DFLT
=> false,
397 ApiBase
:: PARAM_DEPRECATED
=> true,
400 ApiBase
:: PARAM_DFLT
=> false,
401 ApiBase
:: PARAM_DEPRECATED
=> true,
403 'watchlist' => array(
404 ApiBase
:: PARAM_DFLT
=> 'preferences',
405 ApiBase
:: PARAM_TYPE
=> array(
413 'prependtext' => null,
414 'appendtext' => null,
416 ApiBase
:: PARAM_TYPE
=> 'integer'
418 'undoafter' => array(
419 ApiBase
:: PARAM_TYPE
=> 'integer'
424 protected function getParamDescription() {
426 'title' => 'Page title',
427 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
428 'text' => 'Page content',
429 'token' => 'Edit token. You can get one of these through prop=info',
430 'summary' => 'Edit summary. Also section title when section=new',
431 'minor' => 'Minor edit',
432 'notminor' => 'Non-minor edit',
433 'bot' => 'Mark this edit as bot',
434 'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
435 'Used to detect edit conflicts; leave unset to ignore conflicts.'
437 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
438 'Used to detect edit conflicts; leave unset to ignore conflicts.'
440 'recreate' => 'Override any errors about the article having been deleted in the meantime',
441 'createonly' => 'Don\'t edit the page if it exists already',
442 'nocreate' => 'Throw an error if the page doesn\'t exist',
443 'watch' => 'Add the page to your watchlist',
444 'unwatch' => 'Remove the page from your watchlist',
445 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
446 'captchaid' => 'CAPTCHA ID from previous request',
447 'captchaword' => 'Answer to the CAPTCHA',
448 'md5' => array( 'The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated.',
449 'If set, the edit won\'t be done unless the hash is correct' ),
450 'prependtext' => 'Add this text to the beginning of the page. Overrides text.',
451 'appendtext' => 'Add this text to the end of the page. Overrides text',
452 'undo' => 'Undo this revision. Overrides text, prependtext and appendtext',
453 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
457 public function getTokenSalt() {
461 protected function getExamples() {
463 "Edit a page (anonymous user):",
464 " api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\",
465 "Prepend __NOTOC__ to a page (anonymous user):",
466 " api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\",
467 "Undo r13579 through r13585 with autosummary(anonymous user):",
468 " api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\",
472 public function getVersion() {
473 return __CLASS__
. ': $Id$';