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,
32 * see T20654 if you're inspired to fix this.
36 class ApiEditPage
extends ApiBase
{
37 public function execute() {
38 $this->useTransactionalTimeLimit();
40 $user = $this->getUser();
41 $params = $this->extractRequestParams();
43 $this->requireAtLeastOneParameter( $params, 'text', 'appendtext', 'prependtext', 'undo' );
45 $pageObj = $this->getTitleOrPageId( $params );
46 $titleObj = $pageObj->getTitle();
47 $apiResult = $this->getResult();
49 if ( $params['redirect'] ) {
50 if ( $params['prependtext'] === null && $params['appendtext'] === null
51 && $params['section'] !== 'new'
53 $this->dieWithError( 'apierror-redirect-appendonly' );
55 if ( $titleObj->isRedirect() ) {
56 $oldTitle = $titleObj;
58 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
59 ->getContent( Revision
::FOR_THIS_USER
, $user )
61 // array_shift( $titles );
65 /** @var $newTitle Title */
66 foreach ( $titles as $id => $newTitle ) {
68 if ( !isset( $titles[$id - 1] ) ) {
69 $titles[$id - 1] = $oldTitle;
73 'from' => $titles[$id - 1]->getPrefixedText(),
74 'to' => $newTitle->getPrefixedText()
77 $titleObj = $newTitle;
80 ApiResult
::setIndexedTagName( $redirValues, 'r' );
81 $apiResult->addValue( null, 'redirects', $redirValues );
83 // Since the page changed, update $pageObj
84 $pageObj = WikiPage
::factory( $titleObj );
88 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
89 $contentHandler = $pageObj->getContentHandler();
91 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
93 $contentModel = $contentHandler->getModelID();
95 $name = $titleObj->getPrefixedDBkey();
96 $model = $contentHandler->getModelID();
98 if ( $params['undo'] > 0 ) {
100 } elseif ( $contentHandler->supportsDirectApiEditing() === false ) {
101 $this->dieWithError( [ 'apierror-no-direct-editing', $model, $name ] );
104 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
105 $contentFormat = $contentHandler->getDefaultFormat();
107 $contentFormat = $params['contentformat'];
110 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
111 $this->dieWithError( [ 'apierror-badformat', $contentFormat, $model, $name ] );
114 if ( $params['createonly'] && $titleObj->exists() ) {
115 $this->dieWithError( 'apierror-articleexists' );
117 if ( $params['nocreate'] && !$titleObj->exists() ) {
118 $this->dieWithError( 'apierror-missingtitle' );
121 // Now let's check whether we're even allowed to do this
122 $this->checkTitleUserPermissions(
124 $titleObj->exists() ?
'edit' : [ 'edit', 'create' ]
127 $toMD5 = $params['text'];
128 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
129 $content = $pageObj->getContent();
132 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
133 # If this is a MediaWiki:x message, then load the messages
134 # and return the message value for x.
135 $text = $titleObj->getDefaultMessageText();
136 if ( $text === false ) {
141 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
142 } catch ( MWContentSerializationException
$ex ) {
143 // @todo: Internationalize MWContentSerializationException
145 [ 'apierror-contentserializationexception', wfEscapeWikiText( $ex->getMessage() ) ],
151 # Otherwise, make a new empty content.
152 $content = $contentHandler->makeEmptyContent();
156 // @todo Add support for appending/prepending to the Content interface
158 if ( !( $content instanceof TextContent
) ) {
159 $modelName = $contentHandler->getModelID();
160 $this->dieWithError( [ 'apierror-appendnotsupported', $modelName ] );
163 if ( !is_null( $params['section'] ) ) {
164 if ( !$contentHandler->supportsSections() ) {
165 $modelName = $contentHandler->getModelID();
166 $this->dieWithError( [ 'apierror-sectionsnotsupported', $modelName ] );
169 if ( $params['section'] == 'new' ) {
170 // DWIM if they're trying to prepend/append to a new section.
173 // Process the content for section edits
174 $section = $params['section'];
175 $content = $content->getSection( $section );
178 $this->dieWithError( [ 'apierror-nosuchsection', wfEscapeWikiText( $section ) ] );
186 $text = $content->serialize( $contentFormat );
189 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
190 $toMD5 = $params['prependtext'] . $params['appendtext'];
193 if ( $params['undo'] > 0 ) {
194 if ( $params['undoafter'] > 0 ) {
195 if ( $params['undo'] < $params['undoafter'] ) {
196 list( $params['undo'], $params['undoafter'] ) =
197 [ $params['undoafter'], $params['undo'] ];
199 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
201 $undoRev = Revision
::newFromId( $params['undo'] );
202 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
203 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undo'] ] );
206 if ( $params['undoafter'] == 0 ) {
207 $undoafterRev = $undoRev->getPrevious();
209 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
210 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undoafter'] ] );
213 if ( $undoRev->getPage() != $pageObj->getId() ) {
214 $this->dieWithError( [ 'apierror-revwrongpage', $undoRev->getId(),
215 $titleObj->getPrefixedText() ] );
217 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
218 $this->dieWithError( [ 'apierror-revwrongpage', $undoafterRev->getId(),
219 $titleObj->getPrefixedText() ] );
222 $newContent = $contentHandler->getUndoContent(
223 $pageObj->getRevision(),
228 if ( !$newContent ) {
229 $this->dieWithError( 'undo-failure', 'undofailure' );
231 if ( empty( $params['contentmodel'] )
232 && empty( $params['contentformat'] )
234 // If we are reverting content model, the new content model
235 // might not support the current serialization format, in
236 // which case go back to the old serialization format,
237 // but only if the user hasn't specified a format/model
239 if ( !$newContent->isSupportedFormat( $contentFormat ) ) {
240 $contentFormat = $undoafterRev->getContentFormat();
242 // Override content model with model of undid revision.
243 $contentModel = $newContent->getModel();
245 $params['text'] = $newContent->serialize( $contentFormat );
246 // If no summary was given and we only undid one rev,
247 // use an autosummary
248 if ( is_null( $params['summary'] ) &&
249 $titleObj->getNextRevisionID( $undoafterRev->getId() ) == $params['undo']
251 $params['summary'] = wfMessage( 'undo-summary' )
252 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
256 // See if the MD5 hash checks out
257 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
258 $this->dieWithError( 'apierror-badmd5' );
261 // EditPage wants to parse its stuff from a WebRequest
262 // That interface kind of sucks, but it's workable
264 'wpTextbox1' => $params['text'],
265 'format' => $contentFormat,
266 'model' => $contentModel,
267 'wpEditToken' => $params['token'],
268 'wpIgnoreBlankSummary' => true,
269 'wpIgnoreBlankArticle' => true,
270 'wpIgnoreSelfRedirect' => true,
271 'bot' => $params['bot'],
274 if ( !is_null( $params['summary'] ) ) {
275 $requestArray['wpSummary'] = $params['summary'];
278 if ( !is_null( $params['sectiontitle'] ) ) {
279 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
282 // TODO: Pass along information from 'undoafter' as well
283 if ( $params['undo'] > 0 ) {
284 $requestArray['wpUndidRevision'] = $params['undo'];
287 // Watch out for basetimestamp == '' or '0'
288 // It gets treated as NOW, almost certainly causing an edit conflict
289 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
290 $requestArray['wpEdittime'] = $params['basetimestamp'];
292 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
295 if ( $params['starttimestamp'] !== null ) {
296 $requestArray['wpStarttime'] = $params['starttimestamp'];
298 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
301 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
302 $requestArray['wpMinoredit'] = '';
305 if ( $params['recreate'] ) {
306 $requestArray['wpRecreate'] = '';
309 if ( !is_null( $params['section'] ) ) {
310 $section = $params['section'];
311 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
312 $this->dieWithError( 'apierror-invalidsection' );
314 $content = $pageObj->getContent();
315 if ( $section !== '0' && $section != 'new'
316 && ( !$content ||
!$content->getSection( $section ) )
318 $this->dieWithError( [ 'apierror-nosuchsection', $section ] );
320 $requestArray['wpSection'] = $params['section'];
322 $requestArray['wpSection'] = '';
325 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
327 // Deprecated parameters
328 if ( $params['watch'] ) {
330 } elseif ( $params['unwatch'] ) {
335 $requestArray['wpWatchthis'] = '';
339 if ( count( $params['tags'] ) ) {
340 $tagStatus = ChangeTags
::canAddTagsAccompanyingChange( $params['tags'], $user );
341 if ( $tagStatus->isOK() ) {
342 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
344 $this->dieStatus( $tagStatus );
348 // Pass through anything else we might have been given, to support extensions
349 // This is kind of a hack but it's the best we can do to make extensions work
350 $requestArray +
= $this->getRequest()->getValues();
352 global $wgTitle, $wgRequest;
354 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
356 // Some functions depend on $wgTitle == $ep->mTitle
357 // TODO: Make them not or check if they still do
358 $wgTitle = $titleObj;
360 $articleContext = new RequestContext
;
361 $articleContext->setRequest( $req );
362 $articleContext->setWikiPage( $pageObj );
363 $articleContext->setUser( $this->getUser() );
365 /** @var $articleObject Article */
366 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
368 $ep = new EditPage( $articleObject );
370 $ep->setApiEditOverride( true );
371 $ep->setContextTitle( $titleObj );
372 $ep->importFormData( $req );
373 $content = $ep->textbox1
;
376 // Handle APIEditBeforeSave parameters
378 // Deprecated in favour of EditFilterMergedContent
379 if ( !Hooks
::run( 'APIEditBeforeSave', [ $ep, $content, &$r ], '1.28' ) ) {
381 $r['result'] = 'Failure';
382 $apiResult->addValue( null, $this->getModuleName(), $r );
387 $this->dieWithError( 'hookaborted' );
390 // Do the actual save
391 $oldRevId = $articleObject->getRevIdFetched();
393 // Fake $wgRequest for some hooks inside EditPage
394 // @todo FIXME: This interface SUCKS
395 $oldRequest = $wgRequest;
398 $status = $ep->attemptSave( $result );
399 $wgRequest = $oldRequest;
401 switch ( $status->value
) {
402 case EditPage
::AS_HOOK_ERROR
:
403 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
404 if ( isset( $status->apiHookResult
) ) {
405 $r = $status->apiHookResult
;
406 $r['result'] = 'Failure';
407 $apiResult->addValue( null, $this->getModuleName(), $r );
410 if ( !$status->getErrors() ) {
411 $status->fatal( 'hookaborted' );
413 $this->dieStatus( $status );
415 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
419 [ 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) ]
422 case EditPage
::AS_READ_ONLY_PAGE
:
423 $this->dieReadOnly();
425 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
429 case EditPage
::AS_SUCCESS_UPDATE
:
430 $r['result'] = 'Success';
431 $r['pageid'] = intval( $titleObj->getArticleID() );
432 $r['title'] = $titleObj->getPrefixedText();
433 $r['contentmodel'] = $articleObject->getContentModel();
434 $newRevId = $articleObject->getLatest();
435 if ( $newRevId == $oldRevId ) {
436 $r['nochange'] = true;
438 $r['oldrevid'] = intval( $oldRevId );
439 $r['newrevid'] = intval( $newRevId );
440 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
441 $pageObj->getTimestamp() );
446 // EditPage sometimes only sets the status code without setting
447 // any actual error messages. Supply defaults for those cases.
448 $maxArticleSize = $this->getConfig()->get( 'MaxArticleSize' );
451 EditPage
::AS_IMAGE_REDIRECT_ANON
=> [ 'apierror-noimageredirect-anon' ],
452 EditPage
::AS_IMAGE_REDIRECT_LOGGED
=> [ 'apierror-noimageredirect-logged' ],
453 EditPage
::AS_CONTENT_TOO_BIG
=> [ 'apierror-contenttoobig', $maxArticleSize ],
454 EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
=> [ 'apierror-contenttoobig', $maxArticleSize ],
455 EditPage
::AS_READ_ONLY_PAGE_ANON
=> [ 'apierror-noedit-anon' ],
456 EditPage
::AS_NO_CHANGE_CONTENT_MODEL
=> [ 'apierror-cantchangecontentmodel' ],
457 EditPage
::AS_ARTICLE_WAS_DELETED
=> [ 'apierror-pagedeleted' ],
458 EditPage
::AS_CONFLICT_DETECTED
=> [ 'editconflict' ],
460 // Currently shouldn't be needed
461 EditPage
::AS_SPAM_ERROR
=> [ 'apierror-spamdetected', wfEscapeWikiText( $result['spam'] ) ],
462 EditPage
::AS_READ_ONLY_PAGE_LOGGED
=> [ 'apierror-noedit' ],
463 EditPage
::AS_RATE_LIMITED
=> [ 'apierror-ratelimited' ],
464 EditPage
::AS_NO_CREATE_PERMISSION
=> [ 'nocreate-loggedin' ],
465 EditPage
::AS_BLANK_ARTICLE
=> [ 'apierror-emptypage' ],
466 EditPage
::AS_TEXTBOX_EMPTY
=> [ 'apierror-emptynewsection' ],
467 EditPage
::AS_SUMMARY_NEEDED
=> [ 'apierror-summaryrequired' ],
469 if ( !$status->getErrors() ) {
470 if ( isset( $defaultMessages[$status->value
] ) ) {
471 call_user_func_array( [ $status, 'fatal' ], $defaultMessages[$status->value
] );
473 wfWarn( __METHOD__
. ": Unknown EditPage code {$status->value} with no message" );
474 $status->fatal( 'apierror-unknownerror-editpage', $status->value
);
477 $this->dieStatus( $status );
480 $apiResult->addValue( null, $this->getModuleName(), $r );
483 public function mustBePosted() {
487 public function isWriteMode() {
491 public function getAllowedParams() {
494 ApiBase
::PARAM_TYPE
=> 'string',
497 ApiBase
::PARAM_TYPE
=> 'integer',
501 ApiBase
::PARAM_TYPE
=> 'string',
504 ApiBase
::PARAM_TYPE
=> 'text',
508 ApiBase
::PARAM_TYPE
=> 'tags',
509 ApiBase
::PARAM_ISMULTI
=> true,
515 ApiBase
::PARAM_TYPE
=> 'timestamp',
517 'starttimestamp' => [
518 ApiBase
::PARAM_TYPE
=> 'timestamp',
521 'createonly' => false,
524 ApiBase
::PARAM_DFLT
=> false,
525 ApiBase
::PARAM_DEPRECATED
=> true,
528 ApiBase
::PARAM_DFLT
=> false,
529 ApiBase
::PARAM_DEPRECATED
=> true,
532 ApiBase
::PARAM_DFLT
=> 'preferences',
533 ApiBase
::PARAM_TYPE
=> [
542 ApiBase
::PARAM_TYPE
=> 'text',
545 ApiBase
::PARAM_TYPE
=> 'text',
548 ApiBase
::PARAM_TYPE
=> 'integer'
551 ApiBase
::PARAM_TYPE
=> 'integer'
554 ApiBase
::PARAM_TYPE
=> 'boolean',
555 ApiBase
::PARAM_DFLT
=> false,
558 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
561 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
564 // Standard definition automatically inserted
565 ApiBase
::PARAM_HELP_MSG_APPEND
=> [ 'apihelp-edit-param-token' ],
570 public function needsToken() {
574 protected function getExamplesMessages() {
576 'action=edit&title=Test&summary=test%20summary&' .
577 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
578 => 'apihelp-edit-example-edit',
579 'action=edit&title=Test&summary=NOTOC&minor=&' .
580 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
581 => 'apihelp-edit-example-prepend',
582 'action=edit&title=Test&undo=13585&undoafter=13579&' .
583 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
584 => 'apihelp-edit-example-undo',
588 public function getHelpUrls() {
589 return 'https://www.mediawiki.org/wiki/API:Edit';