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();
47 if ( is_null( $params['title'] ) )
48 $this->dieUsageMsg( array( 'missingparam', 'title' ) );
49 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
50 is_null( $params['prependtext'] ) &&
51 $params['undo'] == 0 )
52 $this->dieUsageMsg( array( 'missingtext' ) );
53 if ( is_null( $params['token'] ) )
54 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
55 if ( !$wgUser->matchEditToken( $params['token'] ) )
56 $this->dieUsageMsg( array( 'sessionfailure' ) );
58 $titleObj = Title
::newFromText( $params['title'] );
59 if ( !$titleObj ||
$titleObj->isExternal() )
60 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
62 // Some functions depend on $wgTitle == $ep->mTitle
66 if ( $params['createonly'] && $titleObj->exists() )
67 $this->dieUsageMsg( array( 'createonly-exists' ) );
68 if ( $params['nocreate'] && !$titleObj->exists() )
69 $this->dieUsageMsg( array( 'nocreate-missing' ) );
71 // Now let's check whether we're even allowed to do this
72 $errors = $titleObj->getUserPermissionsErrors( 'edit', $wgUser );
73 if ( !$titleObj->exists() )
74 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $wgUser ) );
75 if ( count( $errors ) )
76 $this->dieUsageMsg( $errors[0] );
78 $articleObj = new Article( $titleObj );
79 $toMD5 = $params['text'];
80 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
82 // For non-existent pages, Article::getContent()
83 // returns an interface message rather than ''
84 // We do want getContent()'s behavior for non-existent
85 // MediaWiki: pages, though
86 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI
)
89 $content = $articleObj->getContent();
91 if ( !is_null( $params['section'] ) )
93 // Process the content for section edits
95 $section = intval( $params['section'] );
96 $content = $wgParser->getSection( $content, $section, false );
97 if ( $content === false )
98 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
100 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
101 $toMD5 = $params['prependtext'] . $params['appendtext'];
104 if ( $params['undo'] > 0 )
106 if ( $params['undoafter'] > 0 )
108 if ( $params['undo'] < $params['undoafter'] )
109 list( $params['undo'], $params['undoafter'] ) =
110 array( $params['undoafter'], $params['undo'] );
111 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
113 $undoRev = Revision
::newFromID( $params['undo'] );
114 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) )
115 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
116 if ( $params['undoafter'] == 0 )
117 $undoafterRev = $undoRev->getPrevious();
118 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) )
119 $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() ) );
124 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
125 if ( $newtext === false )
126 $this->dieUsageMsg( array( 'undo-failure' ) );
127 $params['text'] = $newtext;
128 // If no summary was given and we only undid one rev,
129 // use an autosummary
130 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] )
131 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
134 # See if the MD5 hash checks out
135 if ( !is_null( $params['md5'] ) )
136 if ( 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' => ''
146 if ( !is_null( $params['summary'] ) )
147 $reqArr['wpSummary'] = $params['summary'];
148 # Watch out for basetimestamp == ''
149 # wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
150 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' )
151 $reqArr['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
153 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
154 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' )
155 $reqArr['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
158 $reqArr['wpStarttime'] = $reqArr['wpEdittime'];
159 if ( $params['minor'] ||
( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) )
160 $reqArr['wpMinoredit'] = '';
161 if ( $params['recreate'] )
162 $reqArr['wpRecreate'] = '';
163 if ( !is_null( $params['section'] ) )
165 $section = intval( $params['section'] );
166 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' )
167 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
168 $reqArr['wpSection'] = $params['section'];
171 $reqArr['wpSection'] = '';
173 // Handle watchlist settings
174 switch ( $params['watchlist'] )
183 if ( $titleObj->exists() )
184 $watch = $wgUser->getOption( 'watchdefault' ) ||
$titleObj->userIsWatching();
186 $watch = $wgUser->getOption( 'watchcreations' );
190 $watch = $titleObj->userIsWatching();
192 // Deprecated parameters
193 if ( $params['watch'] )
195 elseif ( $params['unwatch'] )
199 $reqArr['wpWatchthis'] = '';
201 $req = new FauxRequest( $reqArr, true );
202 $ep->importFormData( $req );
205 # Handle CAPTCHA parameters
207 if ( !is_null( $params['captchaid'] ) )
208 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
209 if ( !is_null( $params['captchaword'] ) )
210 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
212 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) )
216 $r['result'] = "Failure";
217 $this->getResult()->addValue( null, $this->getModuleName(), $r );
221 $this->dieUsageMsg( array( 'hookaborted' ) );
225 $oldRevId = $articleObj->getRevIdFetched();
227 # Fake $wgRequest for some hooks inside EditPage
228 # FIXME: This interface SUCKS
229 $oldRequest = $wgRequest;
232 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
233 $wgRequest = $oldRequest;
236 case EditPage
::AS_HOOK_ERROR
:
237 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
238 $this->dieUsageMsg( array( 'hookaborted' ) );
239 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
240 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
241 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
242 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
243 case EditPage
::AS_SPAM_ERROR
:
244 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
245 case EditPage
::AS_FILTERING
:
246 $this->dieUsageMsg( array( 'filtered' ) );
247 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
248 $this->dieUsageMsg( array( 'blockedtext' ) );
249 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
250 case EditPage
::AS_CONTENT_TOO_BIG
:
251 global $wgMaxArticleSize;
252 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
253 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
254 $this->dieUsageMsg( array( 'noedit-anon' ) );
255 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
256 $this->dieUsageMsg( array( 'noedit' ) );
257 case EditPage
::AS_READ_ONLY_PAGE
:
258 $this->dieReadOnly();
259 case EditPage
::AS_RATE_LIMITED
:
260 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
261 case EditPage
::AS_ARTICLE_WAS_DELETED
:
262 $this->dieUsageMsg( array( 'wasdeleted' ) );
263 case EditPage
::AS_NO_CREATE_PERMISSION
:
264 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
265 case EditPage
::AS_BLANK_ARTICLE
:
266 $this->dieUsageMsg( array( 'blankpage' ) );
267 case EditPage
::AS_CONFLICT_DETECTED
:
268 $this->dieUsageMsg( array( 'editconflict' ) );
269 # case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
270 case EditPage
::AS_TEXTBOX_EMPTY
:
271 $this->dieUsageMsg( array( 'emptynewsection' ) );
272 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
274 case EditPage
::AS_SUCCESS_UPDATE
:
275 $r['result'] = "Success";
276 $r['pageid'] = intval( $titleObj->getArticleID() );
277 $r['title'] = $titleObj->getPrefixedText();
278 # HACK: We create a new Article object here because getRevIdFetched()
279 # refuses to be run twice, and because Title::getLatestRevId()
280 # won't fetch from the master unless we select for update, which we
282 $newArticle = new Article( $titleObj );
283 $newRevId = $newArticle->getRevIdFetched();
284 if ( $newRevId == $oldRevId )
288 $r['oldrevid'] = intval( $oldRevId );
289 $r['newrevid'] = intval( $newRevId );
290 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
291 $newArticle->getTimestamp() );
294 case EditPage
::AS_END
:
295 # This usually means some kind of race condition
296 # or DB weirdness occurred. Fall through to throw an unknown
299 # This needs fixing higher up, as Article::doEdit should be
300 # used rather than Article::updateArticle, so that specific
301 # error conditions can be returned
303 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
305 $this->getResult()->addValue( null, $this->getModuleName(), $r );
308 public function mustBePosted() {
312 public function isWriteMode() {
316 protected function getDescription() {
317 return 'Create and edit pages.';
320 protected function getAllowedParams() {
330 'basetimestamp' => null,
331 'starttimestamp' => null,
333 'createonly' => false,
335 'captchaword' => null,
338 ApiBase
:: PARAM_DFLT
=> false,
339 ApiBase
:: PARAM_DEPRECATED
=> true,
342 ApiBase
:: PARAM_DFLT
=> false,
343 ApiBase
:: PARAM_DEPRECATED
=> true,
345 'watchlist' => array(
346 ApiBase
:: PARAM_DFLT
=> 'preferences',
347 ApiBase
:: PARAM_TYPE
=> array(
355 'prependtext' => null,
356 'appendtext' => null,
358 ApiBase
:: PARAM_TYPE
=> 'integer'
360 'undoafter' => array(
361 ApiBase
:: PARAM_TYPE
=> 'integer'
366 protected function getParamDescription() {
368 'title' => 'Page title',
369 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
370 'text' => 'Page content',
371 'token' => 'Edit token. You can get one of these through prop=info',
372 'summary' => 'Edit summary. Also section title when section=new',
373 'minor' => 'Minor edit',
374 'notminor' => 'Non-minor edit',
375 'bot' => 'Mark this edit as bot',
376 'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
377 'Used to detect edit conflicts; leave unset to ignore conflicts.'
379 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
380 'Used to detect edit conflicts; leave unset to ignore conflicts.'
382 'recreate' => 'Override any errors about the article having been deleted in the meantime',
383 'createonly' => 'Don\'t edit the page if it exists already',
384 'nocreate' => 'Throw an error if the page doesn\'t exist',
385 'watch' => 'Add the page to your watchlist',
386 'unwatch' => 'Remove the page from your watchlist',
387 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
388 'captchaid' => 'CAPTCHA ID from previous request',
389 'captchaword' => 'Answer to the CAPTCHA',
390 'md5' => array( 'The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated.',
391 'If set, the edit won\'t be done unless the hash is correct' ),
392 'prependtext' => 'Add this text to the beginning of the page. Overrides text.',
393 'appendtext' => 'Add this text to the end of the page. Overrides text',
394 'undo' => 'Undo this revision. Overrides text, prependtext and appendtext',
395 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
399 protected function getExamples() {
401 "Edit a page (anonymous user):",
402 " api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\",
403 "Prepend __NOTOC__ to a page (anonymous user):",
404 " api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\",
405 "Undo r13579 through r13585 with autosummary(anonymous user):",
406 " api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\",
410 public function getVersion() {
411 return __CLASS__
. ': $Id$';