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;
76 ApiResult
::setIndexedTagName( $redirValues, 'r' );
77 $apiResult->addValue( null, 'redirects', $redirValues );
79 // Since the page changed, update $pageObj
80 $pageObj = WikiPage
::factory( $titleObj );
84 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
85 $contentHandler = $pageObj->getContentHandler();
87 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
89 $contentModel = $contentHandler->getModelID();
91 $name = $titleObj->getPrefixedDBkey();
92 $model = $contentHandler->getModelID();
94 if ( $params['undo'] > 0 ) {
96 } elseif ( $contentHandler->supportsDirectApiEditing() === false ) {
97 $this->dieWithError( [ 'apierror-no-direct-editing', $model, $name ] );
100 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
101 $contentFormat = $contentHandler->getDefaultFormat();
103 $contentFormat = $params['contentformat'];
106 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
107 $this->dieWithError( [ 'apierror-badformat', $contentFormat, $model, $name ] );
110 if ( $params['createonly'] && $titleObj->exists() ) {
111 $this->dieWithError( 'apierror-articleexists' );
113 if ( $params['nocreate'] && !$titleObj->exists() ) {
114 $this->dieWithError( 'apierror-missingtitle' );
117 // Now let's check whether we're even allowed to do this
118 $this->checkTitleUserPermissions(
120 $titleObj->exists() ?
'edit' : [ 'edit', 'create' ],
121 [ 'autoblock' => true ]
124 $toMD5 = $params['text'];
125 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
126 $content = $pageObj->getContent();
129 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
130 # If this is a MediaWiki:x message, then load the messages
131 # and return the message value for x.
132 $text = $titleObj->getDefaultMessageText();
133 if ( $text === false ) {
138 $content = ContentHandler
::makeContent( $text, $titleObj );
139 } catch ( MWContentSerializationException
$ex ) {
140 $this->dieWithException( $ex, [
141 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
146 # Otherwise, make a new empty content.
147 $content = $contentHandler->makeEmptyContent();
151 // @todo Add support for appending/prepending to the Content interface
153 if ( !( $content instanceof TextContent
) ) {
154 $modelName = $contentHandler->getModelID();
155 $this->dieWithError( [ 'apierror-appendnotsupported', $modelName ] );
158 if ( !is_null( $params['section'] ) ) {
159 if ( !$contentHandler->supportsSections() ) {
160 $modelName = $contentHandler->getModelID();
161 $this->dieWithError( [ 'apierror-sectionsnotsupported', $modelName ] );
164 if ( $params['section'] == 'new' ) {
165 // DWIM if they're trying to prepend/append to a new section.
168 // Process the content for section edits
169 $section = $params['section'];
170 $content = $content->getSection( $section );
173 $this->dieWithError( [ 'apierror-nosuchsection', wfEscapeWikiText( $section ) ] );
181 $text = $content->serialize( $contentFormat );
184 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
185 $toMD5 = $params['prependtext'] . $params['appendtext'];
188 if ( $params['undo'] > 0 ) {
189 if ( $params['undoafter'] > 0 ) {
190 if ( $params['undo'] < $params['undoafter'] ) {
191 list( $params['undo'], $params['undoafter'] ) =
192 [ $params['undoafter'], $params['undo'] ];
194 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
196 $undoRev = Revision
::newFromId( $params['undo'] );
197 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
198 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undo'] ] );
201 if ( $params['undoafter'] == 0 ) {
202 $undoafterRev = $undoRev->getPrevious();
204 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
205 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undoafter'] ] );
208 if ( $undoRev->getPage() != $pageObj->getId() ) {
209 $this->dieWithError( [ 'apierror-revwrongpage', $undoRev->getId(),
210 $titleObj->getPrefixedText() ] );
212 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
213 $this->dieWithError( [ 'apierror-revwrongpage', $undoafterRev->getId(),
214 $titleObj->getPrefixedText() ] );
217 $newContent = $contentHandler->getUndoContent(
218 $pageObj->getRevision(),
223 if ( !$newContent ) {
224 $this->dieWithError( 'undo-failure', 'undofailure' );
226 if ( empty( $params['contentmodel'] )
227 && empty( $params['contentformat'] )
229 // If we are reverting content model, the new content model
230 // might not support the current serialization format, in
231 // which case go back to the old serialization format,
232 // but only if the user hasn't specified a format/model
234 if ( !$newContent->isSupportedFormat( $contentFormat ) ) {
235 $contentFormat = $undoafterRev->getContentFormat();
237 // Override content model with model of undid revision.
238 $contentModel = $newContent->getModel();
240 $params['text'] = $newContent->serialize( $contentFormat );
241 // If no summary was given and we only undid one rev,
242 // use an autosummary
244 if ( is_null( $params['summary'] ) ) {
245 $nextRev = MediaWikiServices
::getInstance()->getRevisionLookup()
246 ->getNextRevision( $undoafterRev->getRevisionRecord() );
247 if ( $nextRev && $nextRev->getId() == $params['undo'] ) {
248 $params['summary'] = wfMessage( 'undo-summary' )
249 ->params( $params['undo'], $undoRev->getUserText() )
250 ->inContentLanguage()->text();
255 // See if the MD5 hash checks out
256 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
257 $this->dieWithError( 'apierror-badmd5' );
260 // EditPage wants to parse its stuff from a WebRequest
261 // That interface kind of sucks, but it's workable
263 'wpTextbox1' => $params['text'],
264 'format' => $contentFormat,
265 'model' => $contentModel,
266 'wpEditToken' => $params['token'],
267 'wpIgnoreBlankSummary' => true,
268 'wpIgnoreBlankArticle' => true,
269 'wpIgnoreSelfRedirect' => true,
270 'bot' => $params['bot'],
271 'wpUnicodeCheck' => EditPage
::UNICODE_CHECK
,
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 ( $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 Article $articleObject */
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
;
375 // Do the actual save
376 $oldRevId = $articleObject->getRevIdFetched();
378 // Fake $wgRequest for some hooks inside EditPage
379 // @todo FIXME: This interface SUCKS
380 $oldRequest = $wgRequest;
383 $status = $ep->attemptSave( $result );
384 $wgRequest = $oldRequest;
387 switch ( $status->value
) {
388 case EditPage
::AS_HOOK_ERROR
:
389 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
390 if ( isset( $status->apiHookResult
) ) {
391 $r = $status->apiHookResult
;
392 $r['result'] = 'Failure';
393 $apiResult->addValue( null, $this->getModuleName(), $r );
396 if ( !$status->getErrors() ) {
397 // This appears to be unreachable right now, because all
398 // code paths will set an error. Could change, though.
399 $status->fatal( 'hookaborted' ); //@codeCoverageIgnore
401 $this->dieStatus( $status );
403 // These two cases will normally have been caught earlier, and will
404 // only occur if something blocks the user between the earlier
405 // check and the check in EditPage (presumably a hook). It's not
406 // obvious that this is even possible.
407 // @codeCoverageIgnoreStart
408 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
409 $this->dieBlocked( $user->getBlock() );
411 case EditPage
::AS_READ_ONLY_PAGE
:
412 $this->dieReadOnly();
413 // @codeCoverageIgnoreEnd
415 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
419 case EditPage
::AS_SUCCESS_UPDATE
:
420 $r['result'] = 'Success';
421 $r['pageid'] = (int)$titleObj->getArticleID();
422 $r['title'] = $titleObj->getPrefixedText();
423 $r['contentmodel'] = $articleObject->getContentModel();
424 $newRevId = $articleObject->getLatest();
425 if ( $newRevId == $oldRevId ) {
426 $r['nochange'] = true;
428 $r['oldrevid'] = (int)$oldRevId;
429 $r['newrevid'] = (int)$newRevId;
430 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
431 $pageObj->getTimestamp() );
436 if ( !$status->getErrors() ) {
437 // EditPage sometimes only sets the status code without setting
438 // any actual error messages. Supply defaults for those cases.
439 switch ( $status->value
) {
441 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
442 $status->fatal( 'apierror-noimageredirect-anon' );
444 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
445 $status->fatal( 'apierror-noimageredirect' );
447 case EditPage
::AS_CONTENT_TOO_BIG
:
448 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
449 $status->fatal( 'apierror-contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) );
451 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
452 $status->fatal( 'apierror-noedit-anon' );
454 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
455 $status->fatal( 'apierror-cantchangecontentmodel' );
457 case EditPage
::AS_ARTICLE_WAS_DELETED
:
458 $status->fatal( 'apierror-pagedeleted' );
460 case EditPage
::AS_CONFLICT_DETECTED
:
461 $status->fatal( 'editconflict' );
464 // Currently shouldn't be needed, but here in case
465 // hooks use them without setting appropriate
466 // errors on the status.
467 // @codeCoverageIgnoreStart
468 case EditPage
::AS_SPAM_ERROR
:
469 $status->fatal( 'apierror-spamdetected', $result['spam'] );
471 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
472 $status->fatal( 'apierror-noedit' );
474 case EditPage
::AS_RATE_LIMITED
:
475 $status->fatal( 'apierror-ratelimited' );
477 case EditPage
::AS_NO_CREATE_PERMISSION
:
478 $status->fatal( 'nocreate-loggedin' );
480 case EditPage
::AS_BLANK_ARTICLE
:
481 $status->fatal( 'apierror-emptypage' );
483 case EditPage
::AS_TEXTBOX_EMPTY
:
484 $status->fatal( 'apierror-emptynewsection' );
486 case EditPage
::AS_SUMMARY_NEEDED
:
487 $status->fatal( 'apierror-summaryrequired' );
490 wfWarn( __METHOD__
. ": Unknown EditPage code {$status->value} with no message" );
491 $status->fatal( 'apierror-unknownerror-editpage', $status->value
);
493 // @codeCoverageIgnoreEnd
496 $this->dieStatus( $status );
498 $apiResult->addValue( null, $this->getModuleName(), $r );
501 public function mustBePosted() {
505 public function isWriteMode() {
509 public function getAllowedParams() {
512 ApiBase
::PARAM_TYPE
=> 'string',
515 ApiBase
::PARAM_TYPE
=> 'integer',
519 ApiBase
::PARAM_TYPE
=> 'string',
522 ApiBase
::PARAM_TYPE
=> 'text',
526 ApiBase
::PARAM_TYPE
=> 'tags',
527 ApiBase
::PARAM_ISMULTI
=> true,
533 ApiBase
::PARAM_TYPE
=> 'timestamp',
535 'starttimestamp' => [
536 ApiBase
::PARAM_TYPE
=> 'timestamp',
539 'createonly' => false,
542 ApiBase
::PARAM_DFLT
=> false,
543 ApiBase
::PARAM_DEPRECATED
=> true,
546 ApiBase
::PARAM_DFLT
=> false,
547 ApiBase
::PARAM_DEPRECATED
=> true,
550 ApiBase
::PARAM_DFLT
=> 'preferences',
551 ApiBase
::PARAM_TYPE
=> [
560 ApiBase
::PARAM_TYPE
=> 'text',
563 ApiBase
::PARAM_TYPE
=> 'text',
566 ApiBase
::PARAM_TYPE
=> 'integer',
567 ApiBase
::PARAM_MIN
=> 0,
568 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
571 ApiBase
::PARAM_TYPE
=> 'integer',
572 ApiBase
::PARAM_MIN
=> 0,
573 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
576 ApiBase
::PARAM_TYPE
=> 'boolean',
577 ApiBase
::PARAM_DFLT
=> false,
580 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
583 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
586 // Standard definition automatically inserted
587 ApiBase
::PARAM_HELP_MSG_APPEND
=> [ 'apihelp-edit-param-token' ],
592 public function needsToken() {
596 protected function getExamplesMessages() {
598 'action=edit&title=Test&summary=test%20summary&' .
599 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
600 => 'apihelp-edit-example-edit',
601 'action=edit&title=Test&summary=NOTOC&minor=&' .
602 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
603 => 'apihelp-edit-example-prepend',
604 'action=edit&title=Test&undo=13585&undoafter=13579&' .
605 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
606 => 'apihelp-edit-example-undo',
610 public function getHelpUrls() {
611 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit';