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
28 * A module that allows for editing and creating pages.
30 * Currently, this wraps around the EditPage class in an ugly way,
31 * EditPage.php should be rewritten to provide a cleaner interface
34 class ApiEditPage
extends ApiBase
{
36 public function __construct( $query, $moduleName ) {
37 parent
::__construct( $query, $moduleName );
40 public function execute() {
41 $user = $this->getUser();
42 $params = $this->extractRequestParams();
44 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
45 is_null( $params['prependtext'] ) &&
46 $params['undo'] == 0 )
48 $this->dieUsageMsg( 'missingtext' );
51 $titleObj = Title
::newFromText( $params['title'] );
52 if ( !$titleObj ||
$titleObj->isExternal() ) {
53 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
56 $apiResult = $this->getResult();
58 if ( $params['redirect'] ) {
59 if ( $titleObj->isRedirect() ) {
60 $oldTitle = $titleObj;
62 $titles = Title
::newFromRedirectArray( Revision
::newFromTitle( $oldTitle )->getText( Revision
::FOR_THIS_USER
) );
63 // array_shift( $titles );
65 $redirValues = array();
66 foreach ( $titles as $id => $newTitle ) {
68 if ( !isset( $titles[ $id - 1 ] ) ) {
69 $titles[ $id - 1 ] = $oldTitle;
72 $redirValues[] = array(
73 'from' => $titles[ $id - 1 ]->getPrefixedText(),
74 'to' => $newTitle->getPrefixedText()
77 $titleObj = $newTitle;
80 $apiResult->setIndexedTagName( $redirValues, 'r' );
81 $apiResult->addValue( null, 'redirects', $redirValues );
85 if ( $params['createonly'] && $titleObj->exists() ) {
86 $this->dieUsageMsg( 'createonly-exists' );
88 if ( $params['nocreate'] && !$titleObj->exists() ) {
89 $this->dieUsageMsg( 'nocreate-missing' );
92 // Now let's check whether we're even allowed to do this
93 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
94 if ( !$titleObj->exists() ) {
95 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
97 if ( count( $errors ) ) {
98 $this->dieUsageMsg( $errors[0] );
101 $articleObj = Article
::newFromTitle( $titleObj, $this->getContext() );
103 $toMD5 = $params['text'];
104 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
106 // For non-existent pages, Article::getContent()
107 // returns an interface message rather than ''
108 // We do want getContent()'s behavior for non-existent
109 // MediaWiki: pages, though
110 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI
) {
114 $content = $articleObj->getContentObject();
115 $text = $content->getNativeData();
118 if ( !is_null( $params['section'] ) ) {
119 // Process the content for section edits
120 $section = intval( $params['section'] );
121 $text = $content->getSection( $section, false );
122 if ( $text === false ||
$text === null ) {
123 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
126 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
127 $toMD5 = $params['prependtext'] . $params['appendtext'];
130 if ( $params['undo'] > 0 ) {
131 if ( $params['undoafter'] > 0 ) {
132 if ( $params['undo'] < $params['undoafter'] ) {
133 list( $params['undo'], $params['undoafter'] ) =
134 array( $params['undoafter'], $params['undo'] );
136 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
138 $undoRev = Revision
::newFromID( $params['undo'] );
139 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
140 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
143 if ( $params['undoafter'] == 0 ) {
144 $undoafterRev = $undoRev->getPrevious();
146 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
147 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
150 if ( $undoRev->getPage() != $articleObj->getID() ) {
151 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
153 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
154 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
157 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
158 if ( $newtext === false ) {
159 $this->dieUsageMsg( 'undo-failure' );
161 $params['text'] = $newtext;
162 // If no summary was given and we only undid one rev,
163 // use an autosummary
164 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
165 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
169 // See if the MD5 hash checks out
170 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
171 $this->dieUsageMsg( 'hashcheckfailed' );
174 // EditPage wants to parse its stuff from a WebRequest
175 // That interface kind of sucks, but it's workable
176 $requestArray = array(
177 'wpTextbox1' => $params['text'],
178 'wpEditToken' => $params['token'],
179 'wpIgnoreBlankSummary' => ''
182 if ( !is_null( $params['summary'] ) ) {
183 $requestArray['wpSummary'] = $params['summary'];
186 if ( !is_null( $params['sectiontitle'] ) ) {
187 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
190 // Watch out for basetimestamp == ''
191 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
192 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
193 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
195 $requestArray['wpEdittime'] = $articleObj->getTimestamp();
198 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
199 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
201 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
204 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
205 $requestArray['wpMinoredit'] = '';
208 if ( $params['recreate'] ) {
209 $requestArray['wpRecreate'] = '';
212 if ( !is_null( $params['section'] ) ) {
213 $section = intval( $params['section'] );
214 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
215 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
217 $requestArray['wpSection'] = $params['section'];
219 $requestArray['wpSection'] = '';
222 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
224 // Deprecated parameters
225 if ( $params['watch'] ) {
227 } elseif ( $params['unwatch'] ) {
232 $requestArray['wpWatchthis'] = '';
235 global $wgTitle, $wgRequest;
237 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
239 // Some functions depend on $wgTitle == $ep->mTitle
240 // TODO: Make them not or check if they still do
241 $wgTitle = $titleObj;
243 $handler = ContentHandler
::getForTitle( $titleObj );
244 $ep = $handler->createEditPage( $articleObj );
246 $ep->setContextTitle( $titleObj );
247 $ep->importFormData( $req );
250 // Handle APIEditBeforeSave parameters
252 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
254 $r['result'] = 'Failure';
255 $apiResult->addValue( null, $this->getModuleName(), $r );
258 $this->dieUsageMsg( 'hookaborted' );
262 // Do the actual save
263 $oldRevId = $articleObj->getRevIdFetched();
265 // Fake $wgRequest for some hooks inside EditPage
266 // @todo FIXME: This interface SUCKS
267 $oldRequest = $wgRequest;
270 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
271 $wgRequest = $oldRequest;
272 global $wgMaxArticleSize;
274 switch( $status->value
) {
275 case EditPage
::AS_HOOK_ERROR
:
276 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
277 $this->dieUsageMsg( 'hookaborted' );
279 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
280 $this->dieUsageMsg( 'noimageredirect-anon' );
282 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
283 $this->dieUsageMsg( 'noimageredirect-logged' );
285 case EditPage
::AS_SPAM_ERROR
:
286 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
288 case EditPage
::AS_FILTERING
:
289 $this->dieUsageMsg( 'filtered' );
291 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
292 $this->dieUsageMsg( 'blockedtext' );
294 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
295 case EditPage
::AS_CONTENT_TOO_BIG
:
296 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
298 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
299 $this->dieUsageMsg( 'noedit-anon' );
301 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
302 $this->dieUsageMsg( 'noedit' );
304 case EditPage
::AS_READ_ONLY_PAGE
:
305 $this->dieReadOnly();
307 case EditPage
::AS_RATE_LIMITED
:
308 $this->dieUsageMsg( 'actionthrottledtext' );
310 case EditPage
::AS_ARTICLE_WAS_DELETED
:
311 $this->dieUsageMsg( 'wasdeleted' );
313 case EditPage
::AS_NO_CREATE_PERMISSION
:
314 $this->dieUsageMsg( 'nocreate-loggedin' );
316 case EditPage
::AS_BLANK_ARTICLE
:
317 $this->dieUsageMsg( 'blankpage' );
319 case EditPage
::AS_CONFLICT_DETECTED
:
320 $this->dieUsageMsg( 'editconflict' );
322 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
323 case EditPage
::AS_TEXTBOX_EMPTY
:
324 $this->dieUsageMsg( 'emptynewsection' );
326 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
329 case EditPage
::AS_SUCCESS_UPDATE
:
330 $r['result'] = 'Success';
331 $r['pageid'] = intval( $titleObj->getArticleID() );
332 $r['title'] = $titleObj->getPrefixedText();
333 $newRevId = $articleObj->getLatest();
334 if ( $newRevId == $oldRevId ) {
337 $r['oldrevid'] = intval( $oldRevId );
338 $r['newrevid'] = intval( $newRevId );
339 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
340 $articleObj->getTimestamp() );
344 case EditPage
::AS_SUMMARY_NEEDED
:
345 $this->dieUsageMsg( 'summaryrequired' );
347 case EditPage
::AS_END
:
348 // $status came from WikiPage::doEdit()
349 $errors = $status->getErrorsArray();
350 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
353 if ( is_string( $status->value
) && strlen( $status->value
) ) {
354 $this->dieUsage( "An unknown return value was returned by Editpage. The code returned was \"{$status->value}\"" , $status->value
);
356 $this->dieUsageMsg( array( 'unknownerror', $status->value
) );
359 $apiResult->addValue( null, $this->getModuleName(), $r );
362 public function mustBePosted() {
366 public function isWriteMode() {
370 public function getDescription() {
371 return 'Create and edit pages.';
374 public function getPossibleErrors() {
375 global $wgMaxArticleSize;
377 return array_merge( parent
::getPossibleErrors(), array(
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' ),
391 array( 'summaryrequired' ),
393 array( 'blockedtext' ),
394 array( 'contenttoobig', $wgMaxArticleSize ),
395 array( 'noedit-anon' ),
397 array( 'actionthrottledtext' ),
398 array( 'wasdeleted' ),
399 array( 'nocreate-loggedin' ),
400 array( 'blankpage' ),
401 array( 'editconflict' ),
402 array( 'emptynewsection' ),
403 array( 'unknownerror', 'retval' ),
404 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
405 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
406 array( 'customcssprotected' ),
407 array( 'customjsprotected' ),
411 public function getAllowedParams() {
414 ApiBase
::PARAM_TYPE
=> 'string',
415 ApiBase
::PARAM_REQUIRED
=> true
418 'sectiontitle' => array(
419 ApiBase
::PARAM_TYPE
=> 'string',
420 ApiBase
::PARAM_REQUIRED
=> false,
428 'basetimestamp' => null,
429 'starttimestamp' => null,
431 'createonly' => false,
434 ApiBase
::PARAM_DFLT
=> false,
435 ApiBase
::PARAM_DEPRECATED
=> true,
438 ApiBase
::PARAM_DFLT
=> false,
439 ApiBase
::PARAM_DEPRECATED
=> true,
441 'watchlist' => array(
442 ApiBase
::PARAM_DFLT
=> 'preferences',
443 ApiBase
::PARAM_TYPE
=> array(
451 'prependtext' => null,
452 'appendtext' => null,
454 ApiBase
::PARAM_TYPE
=> 'integer'
456 'undoafter' => array(
457 ApiBase
::PARAM_TYPE
=> 'integer'
460 ApiBase
::PARAM_TYPE
=> 'boolean',
461 ApiBase
::PARAM_DFLT
=> false,
466 public function getParamDescription() {
467 $p = $this->getModulePrefix();
469 'title' => 'Page title',
470 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
471 'sectiontitle' => 'The title for a new section',
472 'text' => 'Page content',
473 'token' => array( 'Edit token. You can get one of these through prop=info.',
474 'The token should always be sent as the last parameter, or at least, after the text parameter'
476 'summary' => 'Edit summary. Also section title when section=new',
477 'minor' => 'Minor edit',
478 'notminor' => 'Non-minor edit',
479 'bot' => 'Mark this edit as bot',
480 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
481 'Used to detect edit conflicts; leave unset to ignore conflicts.'
483 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
484 'Used to detect edit conflicts; leave unset to ignore conflicts'
486 'recreate' => 'Override any errors about the article having been deleted in the meantime',
487 'createonly' => 'Don\'t edit the page if it exists already',
488 'nocreate' => 'Throw an error if the page doesn\'t exist',
489 'watch' => 'Add the page to your watchlist',
490 'unwatch' => 'Remove the page from your watchlist',
491 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
492 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
493 'If set, the edit won\'t be done unless the hash is correct' ),
494 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
495 'appendtext' => "Add this text to the end of the page. Overrides {$p}text",
496 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
497 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
498 'redirect' => 'Automatically resolve redirects',
502 public function needsToken() {
506 public function getTokenSalt() {
510 public function getExamples() {
513 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
514 => 'Edit a page (anonymous user)',
516 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
517 => 'Prepend __NOTOC__ to a page (anonymous user)',
518 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
519 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
523 public function getHelpUrls() {
524 return 'https://www.mediawiki.org/wiki/API:Edit';
527 public function getVersion() {
528 return __CLASS__
. ': $Id$';