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\Storage\RevisionRecord
;
26 * A module that allows for editing and creating pages.
28 * Currently, this wraps around the EditPage class in an ugly way,
29 * EditPage.php should be rewritten to provide a cleaner interface,
30 * see T20654 if you're inspired to fix this.
34 class ApiEditPage
extends ApiBase
{
35 public function execute() {
36 $this->useTransactionalTimeLimit();
38 $user = $this->getUser();
39 $params = $this->extractRequestParams();
41 $this->requireAtLeastOneParameter( $params, 'text', 'appendtext', 'prependtext', 'undo' );
43 $pageObj = $this->getTitleOrPageId( $params );
44 $titleObj = $pageObj->getTitle();
45 $apiResult = $this->getResult();
47 if ( $params['redirect'] ) {
48 if ( $params['prependtext'] === null && $params['appendtext'] === null
49 && $params['section'] !== 'new'
51 $this->dieWithError( 'apierror-redirect-appendonly' );
53 if ( $titleObj->isRedirect() ) {
54 $oldTitle = $titleObj;
56 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
57 ->getContent( RevisionRecord
::FOR_THIS_USER
, $user )
59 // array_shift( $titles );
63 /** @var Title $newTitle */
64 foreach ( $titles as $id => $newTitle ) {
65 if ( !isset( $titles[$id - 1] ) ) {
66 $titles[$id - 1] = $oldTitle;
70 'from' => $titles[$id - 1]->getPrefixedText(),
71 'to' => $newTitle->getPrefixedText()
74 $titleObj = $newTitle;
77 ApiResult
::setIndexedTagName( $redirValues, 'r' );
78 $apiResult->addValue( null, 'redirects', $redirValues );
80 // Since the page changed, update $pageObj
81 $pageObj = WikiPage
::factory( $titleObj );
85 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
86 $contentHandler = $pageObj->getContentHandler();
88 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
90 $contentModel = $contentHandler->getModelID();
92 $name = $titleObj->getPrefixedDBkey();
93 $model = $contentHandler->getModelID();
95 if ( $params['undo'] > 0 ) {
97 } elseif ( $contentHandler->supportsDirectApiEditing() === false ) {
98 $this->dieWithError( [ 'apierror-no-direct-editing', $model, $name ] );
101 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
102 $contentFormat = $contentHandler->getDefaultFormat();
104 $contentFormat = $params['contentformat'];
107 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
108 $this->dieWithError( [ 'apierror-badformat', $contentFormat, $model, $name ] );
111 if ( $params['createonly'] && $titleObj->exists() ) {
112 $this->dieWithError( 'apierror-articleexists' );
114 if ( $params['nocreate'] && !$titleObj->exists() ) {
115 $this->dieWithError( 'apierror-missingtitle' );
118 // Now let's check whether we're even allowed to do this
119 $this->checkTitleUserPermissions(
121 $titleObj->exists() ?
'edit' : [ 'edit', 'create' ],
122 [ 'autoblock' => true ]
125 $toMD5 = $params['text'];
126 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
127 $content = $pageObj->getContent();
130 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
131 # If this is a MediaWiki:x message, then load the messages
132 # and return the message value for x.
133 $text = $titleObj->getDefaultMessageText();
134 if ( $text === false ) {
139 $content = ContentHandler
::makeContent( $text, $titleObj );
140 } catch ( MWContentSerializationException
$ex ) {
141 $this->dieWithException( $ex, [
142 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
147 # Otherwise, make a new empty content.
148 $content = $contentHandler->makeEmptyContent();
152 // @todo Add support for appending/prepending to the Content interface
154 if ( !( $content instanceof TextContent
) ) {
155 $modelName = $contentHandler->getModelID();
156 $this->dieWithError( [ 'apierror-appendnotsupported', $modelName ] );
159 if ( !is_null( $params['section'] ) ) {
160 if ( !$contentHandler->supportsSections() ) {
161 $modelName = $contentHandler->getModelID();
162 $this->dieWithError( [ 'apierror-sectionsnotsupported', $modelName ] );
165 if ( $params['section'] == 'new' ) {
166 // DWIM if they're trying to prepend/append to a new section.
169 // Process the content for section edits
170 $section = $params['section'];
171 $content = $content->getSection( $section );
174 $this->dieWithError( [ 'apierror-nosuchsection', wfEscapeWikiText( $section ) ] );
182 $text = $content->serialize( $contentFormat );
185 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
186 $toMD5 = $params['prependtext'] . $params['appendtext'];
189 if ( $params['undo'] > 0 ) {
190 if ( $params['undoafter'] > 0 ) {
191 if ( $params['undo'] < $params['undoafter'] ) {
192 list( $params['undo'], $params['undoafter'] ) =
193 [ $params['undoafter'], $params['undo'] ];
195 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
197 $undoRev = Revision
::newFromId( $params['undo'] );
198 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
199 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undo'] ] );
202 if ( $params['undoafter'] == 0 ) {
203 $undoafterRev = $undoRev->getPrevious();
205 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( RevisionRecord
::DELETED_TEXT
) ) {
206 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undoafter'] ] );
209 if ( $undoRev->getPage() != $pageObj->getId() ) {
210 $this->dieWithError( [ 'apierror-revwrongpage', $undoRev->getId(),
211 $titleObj->getPrefixedText() ] );
213 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
214 $this->dieWithError( [ 'apierror-revwrongpage', $undoafterRev->getId(),
215 $titleObj->getPrefixedText() ] );
218 $newContent = $contentHandler->getUndoContent(
219 $pageObj->getRevision(),
224 if ( !$newContent ) {
225 $this->dieWithError( 'undo-failure', 'undofailure' );
227 if ( empty( $params['contentmodel'] )
228 && empty( $params['contentformat'] )
230 // If we are reverting content model, the new content model
231 // might not support the current serialization format, in
232 // which case go back to the old serialization format,
233 // but only if the user hasn't specified a format/model
235 if ( !$newContent->isSupportedFormat( $contentFormat ) ) {
236 $contentFormat = $undoafterRev->getContentFormat();
238 // Override content model with model of undid revision.
239 $contentModel = $newContent->getModel();
241 $params['text'] = $newContent->serialize( $contentFormat );
242 // If no summary was given and we only undid one rev,
243 // use an autosummary
244 if ( is_null( $params['summary'] ) &&
245 $titleObj->getNextRevisionID( $undoafterRev->getId() ) == $params['undo']
247 $params['summary'] = wfMessage( 'undo-summary' )
248 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
252 // See if the MD5 hash checks out
253 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
254 $this->dieWithError( 'apierror-badmd5' );
257 // EditPage wants to parse its stuff from a WebRequest
258 // That interface kind of sucks, but it's workable
260 'wpTextbox1' => $params['text'],
261 'format' => $contentFormat,
262 'model' => $contentModel,
263 'wpEditToken' => $params['token'],
264 'wpIgnoreBlankSummary' => true,
265 'wpIgnoreBlankArticle' => true,
266 'wpIgnoreSelfRedirect' => true,
267 'bot' => $params['bot'],
268 'wpUnicodeCheck' => EditPage
::UNICODE_CHECK
,
271 if ( !is_null( $params['summary'] ) ) {
272 $requestArray['wpSummary'] = $params['summary'];
275 if ( !is_null( $params['sectiontitle'] ) ) {
276 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
279 // TODO: Pass along information from 'undoafter' as well
280 if ( $params['undo'] > 0 ) {
281 $requestArray['wpUndidRevision'] = $params['undo'];
284 // Watch out for basetimestamp == '' or '0'
285 // It gets treated as NOW, almost certainly causing an edit conflict
286 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
287 $requestArray['wpEdittime'] = $params['basetimestamp'];
289 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
292 if ( $params['starttimestamp'] !== null ) {
293 $requestArray['wpStarttime'] = $params['starttimestamp'];
295 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
298 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
299 $requestArray['wpMinoredit'] = '';
302 if ( $params['recreate'] ) {
303 $requestArray['wpRecreate'] = '';
306 if ( !is_null( $params['section'] ) ) {
307 $section = $params['section'];
308 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
309 $this->dieWithError( 'apierror-invalidsection' );
311 $content = $pageObj->getContent();
312 if ( $section !== '0' && $section != 'new'
313 && ( !$content ||
!$content->getSection( $section ) )
315 $this->dieWithError( [ 'apierror-nosuchsection', $section ] );
317 $requestArray['wpSection'] = $params['section'];
319 $requestArray['wpSection'] = '';
322 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
324 // Deprecated parameters
325 if ( $params['watch'] ) {
327 } elseif ( $params['unwatch'] ) {
332 $requestArray['wpWatchthis'] = '';
336 if ( $params['tags'] ) {
337 $tagStatus = ChangeTags
::canAddTagsAccompanyingChange( $params['tags'], $user );
338 if ( $tagStatus->isOK() ) {
339 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
341 $this->dieStatus( $tagStatus );
345 // Pass through anything else we might have been given, to support extensions
346 // This is kind of a hack but it's the best we can do to make extensions work
347 $requestArray +
= $this->getRequest()->getValues();
349 global $wgTitle, $wgRequest;
351 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
353 // Some functions depend on $wgTitle == $ep->mTitle
354 // TODO: Make them not or check if they still do
355 $wgTitle = $titleObj;
357 $articleContext = new RequestContext
;
358 $articleContext->setRequest( $req );
359 $articleContext->setWikiPage( $pageObj );
360 $articleContext->setUser( $this->getUser() );
362 /** @var Article $articleObject */
363 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
365 $ep = new EditPage( $articleObject );
367 $ep->setApiEditOverride( true );
368 $ep->setContextTitle( $titleObj );
369 $ep->importFormData( $req );
370 $content = $ep->textbox1
;
372 // Do the actual save
373 $oldRevId = $articleObject->getRevIdFetched();
375 // Fake $wgRequest for some hooks inside EditPage
376 // @todo FIXME: This interface SUCKS
377 $oldRequest = $wgRequest;
380 $status = $ep->attemptSave( $result );
381 $wgRequest = $oldRequest;
383 switch ( $status->value
) {
384 case EditPage
::AS_HOOK_ERROR
:
385 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
386 if ( isset( $status->apiHookResult
) ) {
387 $r = $status->apiHookResult
;
388 $r['result'] = 'Failure';
389 $apiResult->addValue( null, $this->getModuleName(), $r );
392 if ( !$status->getErrors() ) {
393 // This appears to be unreachable right now, because all
394 // code paths will set an error. Could change, though.
395 $status->fatal( 'hookaborted' ); //@codeCoverageIgnore
397 $this->dieStatus( $status );
399 // These two cases will normally have been caught earlier, and will
400 // only occur if something blocks the user between the earlier
401 // check and the check in EditPage (presumably a hook). It's not
402 // obvious that this is even possible.
403 // @codeCoverageIgnoreStart
404 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
405 $this->dieBlocked( $user->getBlock() );
407 case EditPage
::AS_READ_ONLY_PAGE
:
408 $this->dieReadOnly();
409 // @codeCoverageIgnoreEnd
411 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
415 case EditPage
::AS_SUCCESS_UPDATE
:
416 $r['result'] = 'Success';
417 $r['pageid'] = (int)$titleObj->getArticleID();
418 $r['title'] = $titleObj->getPrefixedText();
419 $r['contentmodel'] = $articleObject->getContentModel();
420 $newRevId = $articleObject->getLatest();
421 if ( $newRevId == $oldRevId ) {
422 $r['nochange'] = true;
424 $r['oldrevid'] = (int)$oldRevId;
425 $r['newrevid'] = (int)$newRevId;
426 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
427 $pageObj->getTimestamp() );
432 if ( !$status->getErrors() ) {
433 // EditPage sometimes only sets the status code without setting
434 // any actual error messages. Supply defaults for those cases.
435 switch ( $status->value
) {
437 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
438 $status->fatal( 'apierror-noimageredirect-anon' );
440 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
441 $status->fatal( 'apierror-noimageredirect' );
443 case EditPage
::AS_CONTENT_TOO_BIG
:
444 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
445 $status->fatal( 'apierror-contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) );
447 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
448 $status->fatal( 'apierror-noedit-anon' );
450 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
451 $status->fatal( 'apierror-cantchangecontentmodel' );
453 case EditPage
::AS_ARTICLE_WAS_DELETED
:
454 $status->fatal( 'apierror-pagedeleted' );
456 case EditPage
::AS_CONFLICT_DETECTED
:
457 $status->fatal( 'editconflict' );
460 // Currently shouldn't be needed, but here in case
461 // hooks use them without setting appropriate
462 // errors on the status.
463 // @codeCoverageIgnoreStart
464 case EditPage
::AS_SPAM_ERROR
:
465 $status->fatal( 'apierror-spamdetected', $result['spam'] );
467 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
468 $status->fatal( 'apierror-noedit' );
470 case EditPage
::AS_RATE_LIMITED
:
471 $status->fatal( 'apierror-ratelimited' );
473 case EditPage
::AS_NO_CREATE_PERMISSION
:
474 $status->fatal( 'nocreate-loggedin' );
476 case EditPage
::AS_BLANK_ARTICLE
:
477 $status->fatal( 'apierror-emptypage' );
479 case EditPage
::AS_TEXTBOX_EMPTY
:
480 $status->fatal( 'apierror-emptynewsection' );
482 case EditPage
::AS_SUMMARY_NEEDED
:
483 $status->fatal( 'apierror-summaryrequired' );
486 wfWarn( __METHOD__
. ": Unknown EditPage code {$status->value} with no message" );
487 $status->fatal( 'apierror-unknownerror-editpage', $status->value
);
489 // @codeCoverageIgnoreEnd
492 $this->dieStatus( $status );
494 $apiResult->addValue( null, $this->getModuleName(), $r );
497 public function mustBePosted() {
501 public function isWriteMode() {
505 public function getAllowedParams() {
508 ApiBase
::PARAM_TYPE
=> 'string',
511 ApiBase
::PARAM_TYPE
=> 'integer',
515 ApiBase
::PARAM_TYPE
=> 'string',
518 ApiBase
::PARAM_TYPE
=> 'text',
522 ApiBase
::PARAM_TYPE
=> 'tags',
523 ApiBase
::PARAM_ISMULTI
=> true,
529 ApiBase
::PARAM_TYPE
=> 'timestamp',
531 'starttimestamp' => [
532 ApiBase
::PARAM_TYPE
=> 'timestamp',
535 'createonly' => false,
538 ApiBase
::PARAM_DFLT
=> false,
539 ApiBase
::PARAM_DEPRECATED
=> true,
542 ApiBase
::PARAM_DFLT
=> false,
543 ApiBase
::PARAM_DEPRECATED
=> true,
546 ApiBase
::PARAM_DFLT
=> 'preferences',
547 ApiBase
::PARAM_TYPE
=> [
556 ApiBase
::PARAM_TYPE
=> 'text',
559 ApiBase
::PARAM_TYPE
=> 'text',
562 ApiBase
::PARAM_TYPE
=> 'integer',
563 ApiBase
::PARAM_MIN
=> 0,
564 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
567 ApiBase
::PARAM_TYPE
=> 'integer',
568 ApiBase
::PARAM_MIN
=> 0,
569 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
572 ApiBase
::PARAM_TYPE
=> 'boolean',
573 ApiBase
::PARAM_DFLT
=> false,
576 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
579 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
582 // Standard definition automatically inserted
583 ApiBase
::PARAM_HELP_MSG_APPEND
=> [ 'apihelp-edit-param-token' ],
588 public function needsToken() {
592 protected function getExamplesMessages() {
594 'action=edit&title=Test&summary=test%20summary&' .
595 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
596 => 'apihelp-edit-example-edit',
597 'action=edit&title=Test&summary=NOTOC&minor=&' .
598 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
599 => 'apihelp-edit-example-prepend',
600 'action=edit&title=Test&undo=13585&undoafter=13579&' .
601 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
602 => 'apihelp-edit-example-undo',
606 public function getHelpUrls() {
607 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit';