3 * Copyright © 2007 Iker Labarga "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use MediaWiki\MediaWikiServices
;
24 use MediaWiki\Revision\RevisionRecord
;
27 * A module that allows for editing and creating pages.
29 * Currently, this wraps around the EditPage class in an ugly way,
30 * EditPage.php should be rewritten to provide a cleaner interface,
31 * see T20654 if you're inspired to fix this.
35 class ApiEditPage
extends ApiBase
{
36 public function execute() {
37 $this->useTransactionalTimeLimit();
39 $user = $this->getUser();
40 $params = $this->extractRequestParams();
42 $this->requireAtLeastOneParameter( $params, 'text', 'appendtext', 'prependtext', 'undo' );
44 $pageObj = $this->getTitleOrPageId( $params );
45 $titleObj = $pageObj->getTitle();
46 $apiResult = $this->getResult();
48 if ( $params['redirect'] ) {
49 if ( $params['prependtext'] === null && $params['appendtext'] === null
50 && $params['section'] !== 'new'
52 $this->dieWithError( 'apierror-redirect-appendonly' );
54 if ( $titleObj->isRedirect() ) {
55 $oldTitle = $titleObj;
57 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
58 ->getContent( RevisionRecord
::FOR_THIS_USER
, $user )
60 // array_shift( $titles );
64 /** @var Title $newTitle */
65 foreach ( $titles as $id => $newTitle ) {
66 $titles[$id - 1] = $titles[$id - 1] ??
$oldTitle;
69 'from' => $titles[$id - 1]->getPrefixedText(),
70 'to' => $newTitle->getPrefixedText()
73 $titleObj = $newTitle;
75 // T239428: Check whether the new title is valid
76 if ( $titleObj->isExternal() ||
!$titleObj->canExist() ) {
77 $redirValues[count( $redirValues ) - 1]['to'] = $titleObj->getFullText();
80 'apierror-edit-invalidredirect',
81 Message
::plaintextParam( $oldTitle->getPrefixedText() ),
82 Message
::plaintextParam( $titleObj->getFullText() ),
84 'edit-invalidredirect',
85 [ 'redirects' => $redirValues ]
90 ApiResult
::setIndexedTagName( $redirValues, 'r' );
91 $apiResult->addValue( null, 'redirects', $redirValues );
93 // Since the page changed, update $pageObj
94 $pageObj = WikiPage
::factory( $titleObj );
98 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
99 $contentHandler = $pageObj->getContentHandler();
101 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
103 $contentModel = $contentHandler->getModelID();
105 $name = $titleObj->getPrefixedDBkey();
106 $model = $contentHandler->getModelID();
108 if ( $params['undo'] > 0 ) {
109 // allow undo via api
110 } elseif ( $contentHandler->supportsDirectApiEditing() === false ) {
111 $this->dieWithError( [ 'apierror-no-direct-editing', $model, $name ] );
114 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
115 $contentFormat = $contentHandler->getDefaultFormat();
117 $contentFormat = $params['contentformat'];
120 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
121 $this->dieWithError( [ 'apierror-badformat', $contentFormat, $model, $name ] );
124 if ( $params['createonly'] && $titleObj->exists() ) {
125 $this->dieWithError( 'apierror-articleexists' );
127 if ( $params['nocreate'] && !$titleObj->exists() ) {
128 $this->dieWithError( 'apierror-missingtitle' );
131 // Now let's check whether we're even allowed to do this
132 $this->checkTitleUserPermissions(
134 $titleObj->exists() ?
'edit' : [ 'edit', 'create' ],
135 [ 'autoblock' => true ]
138 $toMD5 = $params['text'];
139 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
140 $content = $pageObj->getContent();
143 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
144 # If this is a MediaWiki:x message, then load the messages
145 # and return the message value for x.
146 $text = $titleObj->getDefaultMessageText();
147 if ( $text === false ) {
152 $content = ContentHandler
::makeContent( $text, $titleObj );
153 } catch ( MWContentSerializationException
$ex ) {
154 $this->dieWithException( $ex, [
155 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
160 # Otherwise, make a new empty content.
161 $content = $contentHandler->makeEmptyContent();
165 // @todo Add support for appending/prepending to the Content interface
167 if ( !( $content instanceof TextContent
) ) {
168 $modelName = $contentHandler->getModelID();
169 $this->dieWithError( [ 'apierror-appendnotsupported', $modelName ] );
172 if ( !is_null( $params['section'] ) ) {
173 if ( !$contentHandler->supportsSections() ) {
174 $modelName = $contentHandler->getModelID();
175 $this->dieWithError( [ 'apierror-sectionsnotsupported', $modelName ] );
178 if ( $params['section'] == 'new' ) {
179 // DWIM if they're trying to prepend/append to a new section.
182 // Process the content for section edits
183 $section = $params['section'];
184 $content = $content->getSection( $section );
187 $this->dieWithError( [ 'apierror-nosuchsection', wfEscapeWikiText( $section ) ] );
195 $text = $content->serialize( $contentFormat );
198 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
199 $toMD5 = $params['prependtext'] . $params['appendtext'];
202 if ( $params['undo'] > 0 ) {
203 if ( $params['undoafter'] > 0 ) {
204 if ( $params['undo'] < $params['undoafter'] ) {
205 list( $params['undo'], $params['undoafter'] ) =
206 [ $params['undoafter'], $params['undo'] ];
208 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
210 $undoRev = Revision
::newFromId( $params['undo'] );
211 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
212 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undo'] ] );
215 if ( $params['undoafter'] == 0 ) {
216 $undoafterRev = $undoRev->getPrevious();
218 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
219 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undoafter'] ] );
222 if ( $undoRev->getPage() != $pageObj->getId() ) {
223 $this->dieWithError( [ 'apierror-revwrongpage', $undoRev->getId(),
224 $titleObj->getPrefixedText() ] );
226 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
227 $this->dieWithError( [ 'apierror-revwrongpage', $undoafterRev->getId(),
228 $titleObj->getPrefixedText() ] );
231 $newContent = $contentHandler->getUndoContent(
232 $pageObj->getRevision(),
237 if ( !$newContent ) {
238 $this->dieWithError( 'undo-failure', 'undofailure' );
240 if ( empty( $params['contentmodel'] )
241 && empty( $params['contentformat'] )
243 // If we are reverting content model, the new content model
244 // might not support the current serialization format, in
245 // which case go back to the old serialization format,
246 // but only if the user hasn't specified a format/model
248 if ( !$newContent->isSupportedFormat( $contentFormat ) ) {
249 $contentFormat = $undoafterRev->getContentFormat();
251 // Override content model with model of undid revision.
252 $contentModel = $newContent->getModel();
254 $params['text'] = $newContent->serialize( $contentFormat );
255 // If no summary was given and we only undid one rev,
256 // use an autosummary
258 if ( is_null( $params['summary'] ) ) {
259 $nextRev = MediaWikiServices
::getInstance()->getRevisionLookup()
260 ->getNextRevision( $undoafterRev->getRevisionRecord() );
261 if ( $nextRev && $nextRev->getId() == $params['undo'] ) {
262 $params['summary'] = wfMessage( 'undo-summary' )
263 ->params( $params['undo'], $undoRev->getUserText() )
264 ->inContentLanguage()->text();
269 // See if the MD5 hash checks out
270 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
271 $this->dieWithError( 'apierror-badmd5' );
274 // EditPage wants to parse its stuff from a WebRequest
275 // That interface kind of sucks, but it's workable
277 'wpTextbox1' => $params['text'],
278 'format' => $contentFormat,
279 'model' => $contentModel,
280 'wpEditToken' => $params['token'],
281 'wpIgnoreBlankSummary' => true,
282 'wpIgnoreBlankArticle' => true,
283 'wpIgnoreSelfRedirect' => true,
284 'bot' => $params['bot'],
285 'wpUnicodeCheck' => EditPage
::UNICODE_CHECK
,
288 if ( !is_null( $params['summary'] ) ) {
289 $requestArray['wpSummary'] = $params['summary'];
292 if ( !is_null( $params['sectiontitle'] ) ) {
293 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
296 // TODO: Pass along information from 'undoafter' as well
297 if ( $params['undo'] > 0 ) {
298 $requestArray['wpUndidRevision'] = $params['undo'];
301 // Watch out for basetimestamp == '' or '0'
302 // It gets treated as NOW, almost certainly causing an edit conflict
303 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
304 $requestArray['wpEdittime'] = $params['basetimestamp'];
306 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
309 if ( $params['starttimestamp'] !== null ) {
310 $requestArray['wpStarttime'] = $params['starttimestamp'];
312 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
315 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
316 $requestArray['wpMinoredit'] = '';
319 if ( $params['recreate'] ) {
320 $requestArray['wpRecreate'] = '';
323 if ( !is_null( $params['section'] ) ) {
324 $section = $params['section'];
325 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
326 $this->dieWithError( 'apierror-invalidsection' );
328 $content = $pageObj->getContent();
329 if ( $section !== '0' && $section != 'new'
330 && ( !$content ||
!$content->getSection( $section ) )
332 $this->dieWithError( [ 'apierror-nosuchsection', $section ] );
334 $requestArray['wpSection'] = $params['section'];
336 $requestArray['wpSection'] = '';
339 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
341 // Deprecated parameters
342 if ( $params['watch'] ) {
344 } elseif ( $params['unwatch'] ) {
349 $requestArray['wpWatchthis'] = '';
353 if ( $params['tags'] ) {
354 $tagStatus = ChangeTags
::canAddTagsAccompanyingChange( $params['tags'], $user );
355 if ( $tagStatus->isOK() ) {
356 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
358 $this->dieStatus( $tagStatus );
362 // Pass through anything else we might have been given, to support extensions
363 // This is kind of a hack but it's the best we can do to make extensions work
364 $requestArray +
= $this->getRequest()->getValues();
366 global $wgTitle, $wgRequest;
368 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
370 // Some functions depend on $wgTitle == $ep->mTitle
371 // TODO: Make them not or check if they still do
372 $wgTitle = $titleObj;
374 $articleContext = new RequestContext
;
375 $articleContext->setRequest( $req );
376 $articleContext->setWikiPage( $pageObj );
377 $articleContext->setUser( $this->getUser() );
379 /** @var Article $articleObject */
380 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
382 $ep = new EditPage( $articleObject );
384 $ep->setApiEditOverride( true );
385 $ep->setContextTitle( $titleObj );
386 $ep->importFormData( $req );
387 $content = $ep->textbox1
;
389 // Do the actual save
390 $oldRevId = $articleObject->getRevIdFetched();
392 // Fake $wgRequest for some hooks inside EditPage
393 // @todo FIXME: This interface SUCKS
394 $oldRequest = $wgRequest;
397 $status = $ep->attemptSave( $result );
398 $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 // This appears to be unreachable right now, because all
412 // code paths will set an error. Could change, though.
413 $status->fatal( 'hookaborted' ); //@codeCoverageIgnore
415 $this->dieStatus( $status );
417 // These two cases will normally have been caught earlier, and will
418 // only occur if something blocks the user between the earlier
419 // check and the check in EditPage (presumably a hook). It's not
420 // obvious that this is even possible.
421 // @codeCoverageIgnoreStart
422 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
423 $this->dieBlocked( $user->getBlock() );
425 case EditPage
::AS_READ_ONLY_PAGE
:
426 $this->dieReadOnly();
427 // @codeCoverageIgnoreEnd
429 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
433 case EditPage
::AS_SUCCESS_UPDATE
:
434 $r['result'] = 'Success';
435 $r['pageid'] = (int)$titleObj->getArticleID();
436 $r['title'] = $titleObj->getPrefixedText();
437 $r['contentmodel'] = $articleObject->getContentModel();
438 $newRevId = $articleObject->getLatest();
439 if ( $newRevId == $oldRevId ) {
440 $r['nochange'] = true;
442 $r['oldrevid'] = (int)$oldRevId;
443 $r['newrevid'] = (int)$newRevId;
444 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
445 $pageObj->getTimestamp() );
450 if ( !$status->getErrors() ) {
451 // EditPage sometimes only sets the status code without setting
452 // any actual error messages. Supply defaults for those cases.
453 switch ( $status->value
) {
455 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
456 $status->fatal( 'apierror-noimageredirect-anon' );
458 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
459 $status->fatal( 'apierror-noimageredirect' );
461 case EditPage
::AS_CONTENT_TOO_BIG
:
462 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
463 $status->fatal( 'apierror-contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) );
465 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
466 $status->fatal( 'apierror-noedit-anon' );
468 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
469 $status->fatal( 'apierror-cantchangecontentmodel' );
471 case EditPage
::AS_ARTICLE_WAS_DELETED
:
472 $status->fatal( 'apierror-pagedeleted' );
474 case EditPage
::AS_CONFLICT_DETECTED
:
475 $status->fatal( 'editconflict' );
478 // Currently shouldn't be needed, but here in case
479 // hooks use them without setting appropriate
480 // errors on the status.
481 // @codeCoverageIgnoreStart
482 case EditPage
::AS_SPAM_ERROR
:
483 $status->fatal( 'apierror-spamdetected', $result['spam'] );
485 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
486 $status->fatal( 'apierror-noedit' );
488 case EditPage
::AS_RATE_LIMITED
:
489 $status->fatal( 'apierror-ratelimited' );
491 case EditPage
::AS_NO_CREATE_PERMISSION
:
492 $status->fatal( 'nocreate-loggedin' );
494 case EditPage
::AS_BLANK_ARTICLE
:
495 $status->fatal( 'apierror-emptypage' );
497 case EditPage
::AS_TEXTBOX_EMPTY
:
498 $status->fatal( 'apierror-emptynewsection' );
500 case EditPage
::AS_SUMMARY_NEEDED
:
501 $status->fatal( 'apierror-summaryrequired' );
504 wfWarn( __METHOD__
. ": Unknown EditPage code {$status->value} with no message" );
505 $status->fatal( 'apierror-unknownerror-editpage', $status->value
);
507 // @codeCoverageIgnoreEnd
510 $this->dieStatus( $status );
512 $apiResult->addValue( null, $this->getModuleName(), $r );
515 public function mustBePosted() {
519 public function isWriteMode() {
523 public function getAllowedParams() {
526 ApiBase
::PARAM_TYPE
=> 'string',
529 ApiBase
::PARAM_TYPE
=> 'integer',
533 ApiBase
::PARAM_TYPE
=> 'string',
536 ApiBase
::PARAM_TYPE
=> 'text',
540 ApiBase
::PARAM_TYPE
=> 'tags',
541 ApiBase
::PARAM_ISMULTI
=> true,
547 ApiBase
::PARAM_TYPE
=> 'timestamp',
549 'starttimestamp' => [
550 ApiBase
::PARAM_TYPE
=> 'timestamp',
553 'createonly' => false,
556 ApiBase
::PARAM_DFLT
=> false,
557 ApiBase
::PARAM_DEPRECATED
=> true,
560 ApiBase
::PARAM_DFLT
=> false,
561 ApiBase
::PARAM_DEPRECATED
=> true,
564 ApiBase
::PARAM_DFLT
=> 'preferences',
565 ApiBase
::PARAM_TYPE
=> [
574 ApiBase
::PARAM_TYPE
=> 'text',
577 ApiBase
::PARAM_TYPE
=> 'text',
580 ApiBase
::PARAM_TYPE
=> 'integer',
581 ApiBase
::PARAM_MIN
=> 0,
582 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
585 ApiBase
::PARAM_TYPE
=> 'integer',
586 ApiBase
::PARAM_MIN
=> 0,
587 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
590 ApiBase
::PARAM_TYPE
=> 'boolean',
591 ApiBase
::PARAM_DFLT
=> false,
594 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
597 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
600 // Standard definition automatically inserted
601 ApiBase
::PARAM_HELP_MSG_APPEND
=> [ 'apihelp-edit-param-token' ],
606 public function needsToken() {
610 protected function getExamplesMessages() {
612 'action=edit&title=Test&summary=test%20summary&' .
613 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
614 => 'apihelp-edit-example-edit',
615 'action=edit&title=Test&summary=NOTOC&minor=&' .
616 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
617 => 'apihelp-edit-example-prepend',
618 'action=edit&title=Test&undo=13585&undoafter=13579&' .
619 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
620 => 'apihelp-edit-example-undo',
624 public function getHelpUrls() {
625 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit';