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
24 * A module that allows for editing and creating pages.
26 * Currently, this wraps around the EditPage class in an ugly way,
27 * EditPage.php should be rewritten to provide a cleaner interface,
28 * see T20654 if you're inspired to fix this.
32 class ApiEditPage
extends ApiBase
{
33 public function execute() {
34 $this->useTransactionalTimeLimit();
36 $user = $this->getUser();
37 $params = $this->extractRequestParams();
39 $this->requireAtLeastOneParameter( $params, 'text', 'appendtext', 'prependtext', 'undo' );
41 $pageObj = $this->getTitleOrPageId( $params );
42 $titleObj = $pageObj->getTitle();
43 $apiResult = $this->getResult();
45 if ( $params['redirect'] ) {
46 if ( $params['prependtext'] === null && $params['appendtext'] === null
47 && $params['section'] !== 'new'
49 $this->dieWithError( 'apierror-redirect-appendonly' );
51 if ( $titleObj->isRedirect() ) {
52 $oldTitle = $titleObj;
54 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
55 ->getContent( Revision
::FOR_THIS_USER
, $user )
57 // array_shift( $titles );
61 /** @var Title $newTitle */
62 foreach ( $titles as $id => $newTitle ) {
63 if ( !isset( $titles[$id - 1] ) ) {
64 $titles[$id - 1] = $oldTitle;
68 'from' => $titles[$id - 1]->getPrefixedText(),
69 'to' => $newTitle->getPrefixedText()
72 $titleObj = $newTitle;
75 ApiResult
::setIndexedTagName( $redirValues, 'r' );
76 $apiResult->addValue( null, 'redirects', $redirValues );
78 // Since the page changed, update $pageObj
79 $pageObj = WikiPage
::factory( $titleObj );
83 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
84 $contentHandler = $pageObj->getContentHandler();
86 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
88 $contentModel = $contentHandler->getModelID();
90 $name = $titleObj->getPrefixedDBkey();
91 $model = $contentHandler->getModelID();
93 if ( $params['undo'] > 0 ) {
95 } elseif ( $contentHandler->supportsDirectApiEditing() === false ) {
96 $this->dieWithError( [ 'apierror-no-direct-editing', $model, $name ] );
99 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
100 $contentFormat = $contentHandler->getDefaultFormat();
102 $contentFormat = $params['contentformat'];
105 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
106 $this->dieWithError( [ 'apierror-badformat', $contentFormat, $model, $name ] );
109 if ( $params['createonly'] && $titleObj->exists() ) {
110 $this->dieWithError( 'apierror-articleexists' );
112 if ( $params['nocreate'] && !$titleObj->exists() ) {
113 $this->dieWithError( 'apierror-missingtitle' );
116 // Now let's check whether we're even allowed to do this
117 $this->checkTitleUserPermissions(
119 $titleObj->exists() ?
'edit' : [ 'edit', 'create' ],
120 [ 'autoblock' => true ]
123 $toMD5 = $params['text'];
124 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
125 $content = $pageObj->getContent();
128 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
129 # If this is a MediaWiki:x message, then load the messages
130 # and return the message value for x.
131 $text = $titleObj->getDefaultMessageText();
132 if ( $text === false ) {
137 $content = ContentHandler
::makeContent( $text, $titleObj );
138 } catch ( MWContentSerializationException
$ex ) {
139 $this->dieWithException( $ex, [
140 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
145 # Otherwise, make a new empty content.
146 $content = $contentHandler->makeEmptyContent();
150 // @todo Add support for appending/prepending to the Content interface
152 if ( !( $content instanceof TextContent
) ) {
153 $modelName = $contentHandler->getModelID();
154 $this->dieWithError( [ 'apierror-appendnotsupported', $modelName ] );
157 if ( !is_null( $params['section'] ) ) {
158 if ( !$contentHandler->supportsSections() ) {
159 $modelName = $contentHandler->getModelID();
160 $this->dieWithError( [ 'apierror-sectionsnotsupported', $modelName ] );
163 if ( $params['section'] == 'new' ) {
164 // DWIM if they're trying to prepend/append to a new section.
167 // Process the content for section edits
168 $section = $params['section'];
169 $content = $content->getSection( $section );
172 $this->dieWithError( [ 'apierror-nosuchsection', wfEscapeWikiText( $section ) ] );
180 $text = $content->serialize( $contentFormat );
183 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
184 $toMD5 = $params['prependtext'] . $params['appendtext'];
187 if ( $params['undo'] > 0 ) {
188 if ( $params['undoafter'] > 0 ) {
189 if ( $params['undo'] < $params['undoafter'] ) {
190 list( $params['undo'], $params['undoafter'] ) =
191 [ $params['undoafter'], $params['undo'] ];
193 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
195 $undoRev = Revision
::newFromId( $params['undo'] );
196 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
197 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undo'] ] );
200 if ( $params['undoafter'] == 0 ) {
201 $undoafterRev = $undoRev->getPrevious();
203 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
204 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undoafter'] ] );
207 if ( $undoRev->getPage() != $pageObj->getId() ) {
208 $this->dieWithError( [ 'apierror-revwrongpage', $undoRev->getId(),
209 $titleObj->getPrefixedText() ] );
211 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
212 $this->dieWithError( [ 'apierror-revwrongpage', $undoafterRev->getId(),
213 $titleObj->getPrefixedText() ] );
216 $newContent = $contentHandler->getUndoContent(
217 $pageObj->getRevision(),
222 if ( !$newContent ) {
223 $this->dieWithError( 'undo-failure', 'undofailure' );
225 if ( empty( $params['contentmodel'] )
226 && empty( $params['contentformat'] )
228 // If we are reverting content model, the new content model
229 // might not support the current serialization format, in
230 // which case go back to the old serialization format,
231 // but only if the user hasn't specified a format/model
233 if ( !$newContent->isSupportedFormat( $contentFormat ) ) {
234 $contentFormat = $undoafterRev->getContentFormat();
236 // Override content model with model of undid revision.
237 $contentModel = $newContent->getModel();
239 $params['text'] = $newContent->serialize( $contentFormat );
240 // If no summary was given and we only undid one rev,
241 // use an autosummary
242 if ( is_null( $params['summary'] ) &&
243 $titleObj->getNextRevisionID( $undoafterRev->getId() ) == $params['undo']
245 $params['summary'] = wfMessage( 'undo-summary' )
246 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
250 // See if the MD5 hash checks out
251 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
252 $this->dieWithError( 'apierror-badmd5' );
255 // EditPage wants to parse its stuff from a WebRequest
256 // That interface kind of sucks, but it's workable
258 'wpTextbox1' => $params['text'],
259 'format' => $contentFormat,
260 'model' => $contentModel,
261 'wpEditToken' => $params['token'],
262 'wpIgnoreBlankSummary' => true,
263 'wpIgnoreBlankArticle' => true,
264 'wpIgnoreSelfRedirect' => true,
265 'bot' => $params['bot'],
266 'wpUnicodeCheck' => EditPage
::UNICODE_CHECK
,
269 if ( !is_null( $params['summary'] ) ) {
270 $requestArray['wpSummary'] = $params['summary'];
273 if ( !is_null( $params['sectiontitle'] ) ) {
274 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
277 // TODO: Pass along information from 'undoafter' as well
278 if ( $params['undo'] > 0 ) {
279 $requestArray['wpUndidRevision'] = $params['undo'];
282 // Watch out for basetimestamp == '' or '0'
283 // It gets treated as NOW, almost certainly causing an edit conflict
284 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
285 $requestArray['wpEdittime'] = $params['basetimestamp'];
287 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
290 if ( $params['starttimestamp'] !== null ) {
291 $requestArray['wpStarttime'] = $params['starttimestamp'];
293 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
296 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
297 $requestArray['wpMinoredit'] = '';
300 if ( $params['recreate'] ) {
301 $requestArray['wpRecreate'] = '';
304 if ( !is_null( $params['section'] ) ) {
305 $section = $params['section'];
306 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
307 $this->dieWithError( 'apierror-invalidsection' );
309 $content = $pageObj->getContent();
310 if ( $section !== '0' && $section != 'new'
311 && ( !$content ||
!$content->getSection( $section ) )
313 $this->dieWithError( [ 'apierror-nosuchsection', $section ] );
315 $requestArray['wpSection'] = $params['section'];
317 $requestArray['wpSection'] = '';
320 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
322 // Deprecated parameters
323 if ( $params['watch'] ) {
325 } elseif ( $params['unwatch'] ) {
330 $requestArray['wpWatchthis'] = '';
334 if ( $params['tags'] ) {
335 $tagStatus = ChangeTags
::canAddTagsAccompanyingChange( $params['tags'], $user );
336 if ( $tagStatus->isOK() ) {
337 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
339 $this->dieStatus( $tagStatus );
343 // Pass through anything else we might have been given, to support extensions
344 // This is kind of a hack but it's the best we can do to make extensions work
345 $requestArray +
= $this->getRequest()->getValues();
347 global $wgTitle, $wgRequest;
349 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
351 // Some functions depend on $wgTitle == $ep->mTitle
352 // TODO: Make them not or check if they still do
353 $wgTitle = $titleObj;
355 $articleContext = new RequestContext
;
356 $articleContext->setRequest( $req );
357 $articleContext->setWikiPage( $pageObj );
358 $articleContext->setUser( $this->getUser() );
360 /** @var Article $articleObject */
361 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
363 $ep = new EditPage( $articleObject );
365 $ep->setApiEditOverride( true );
366 $ep->setContextTitle( $titleObj );
367 $ep->importFormData( $req );
368 $content = $ep->textbox1
;
371 // Handle APIEditBeforeSave parameters
373 // Deprecated in favour of EditFilterMergedContent
374 if ( !Hooks
::run( 'APIEditBeforeSave', [ $ep, $content, &$r ], '1.28' ) ) {
376 $r['result'] = 'Failure';
377 $apiResult->addValue( null, $this->getModuleName(), $r );
382 $this->dieWithError( 'hookaborted' );
385 // Do the actual save
386 $oldRevId = $articleObject->getRevIdFetched();
388 // Fake $wgRequest for some hooks inside EditPage
389 // @todo FIXME: This interface SUCKS
390 $oldRequest = $wgRequest;
393 $status = $ep->attemptSave( $result );
394 $wgRequest = $oldRequest;
396 switch ( $status->value
) {
397 case EditPage
::AS_HOOK_ERROR
:
398 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
399 if ( isset( $status->apiHookResult
) ) {
400 $r = $status->apiHookResult
;
401 $r['result'] = 'Failure';
402 $apiResult->addValue( null, $this->getModuleName(), $r );
405 if ( !$status->getErrors() ) {
406 // This appears to be unreachable right now, because all
407 // code paths will set an error. Could change, though.
408 $status->fatal( 'hookaborted' ); //@codeCoverageIgnore
410 $this->dieStatus( $status );
412 // These two cases will normally have been caught earlier, and will
413 // only occur if something blocks the user between the earlier
414 // check and the check in EditPage (presumably a hook). It's not
415 // obvious that this is even possible.
416 // @codeCoverageIgnoreStart
417 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
418 $this->dieBlocked( $user->getBlock() );
420 case EditPage
::AS_READ_ONLY_PAGE
:
421 $this->dieReadOnly();
422 // @codeCoverageIgnoreEnd
424 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
428 case EditPage
::AS_SUCCESS_UPDATE
:
429 $r['result'] = 'Success';
430 $r['pageid'] = intval( $titleObj->getArticleID() );
431 $r['title'] = $titleObj->getPrefixedText();
432 $r['contentmodel'] = $articleObject->getContentModel();
433 $newRevId = $articleObject->getLatest();
434 if ( $newRevId == $oldRevId ) {
435 $r['nochange'] = true;
437 $r['oldrevid'] = intval( $oldRevId );
438 $r['newrevid'] = intval( $newRevId );
439 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
440 $pageObj->getTimestamp() );
445 if ( !$status->getErrors() ) {
446 // EditPage sometimes only sets the status code without setting
447 // any actual error messages. Supply defaults for those cases.
448 switch ( $status->value
) {
450 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
451 $status->fatal( 'apierror-noimageredirect-anon' );
453 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
454 $status->fatal( 'apierror-noimageredirect' );
456 case EditPage
::AS_CONTENT_TOO_BIG
:
457 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
458 $status->fatal( 'apierror-contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) );
460 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
461 $status->fatal( 'apierror-noedit-anon' );
463 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
464 $status->fatal( 'apierror-cantchangecontentmodel' );
466 case EditPage
::AS_ARTICLE_WAS_DELETED
:
467 $status->fatal( 'apierror-pagedeleted' );
469 case EditPage
::AS_CONFLICT_DETECTED
:
470 $status->fatal( 'editconflict' );
473 // Currently shouldn't be needed, but here in case
474 // hooks use them without setting appropriate
475 // errors on the status.
476 // @codeCoverageIgnoreStart
477 case EditPage
::AS_SPAM_ERROR
:
478 $status->fatal( 'apierror-spamdetected', $result['spam'] );
480 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
481 $status->fatal( 'apierror-noedit' );
483 case EditPage
::AS_RATE_LIMITED
:
484 $status->fatal( 'apierror-ratelimited' );
486 case EditPage
::AS_NO_CREATE_PERMISSION
:
487 $status->fatal( 'nocreate-loggedin' );
489 case EditPage
::AS_BLANK_ARTICLE
:
490 $status->fatal( 'apierror-emptypage' );
492 case EditPage
::AS_TEXTBOX_EMPTY
:
493 $status->fatal( 'apierror-emptynewsection' );
495 case EditPage
::AS_SUMMARY_NEEDED
:
496 $status->fatal( 'apierror-summaryrequired' );
499 wfWarn( __METHOD__
. ": Unknown EditPage code {$status->value} with no message" );
500 $status->fatal( 'apierror-unknownerror-editpage', $status->value
);
502 // @codeCoverageIgnoreEnd
505 $this->dieStatus( $status );
507 $apiResult->addValue( null, $this->getModuleName(), $r );
510 public function mustBePosted() {
514 public function isWriteMode() {
518 public function getAllowedParams() {
521 ApiBase
::PARAM_TYPE
=> 'string',
524 ApiBase
::PARAM_TYPE
=> 'integer',
528 ApiBase
::PARAM_TYPE
=> 'string',
531 ApiBase
::PARAM_TYPE
=> 'text',
535 ApiBase
::PARAM_TYPE
=> 'tags',
536 ApiBase
::PARAM_ISMULTI
=> true,
542 ApiBase
::PARAM_TYPE
=> 'timestamp',
544 'starttimestamp' => [
545 ApiBase
::PARAM_TYPE
=> 'timestamp',
548 'createonly' => false,
551 ApiBase
::PARAM_DFLT
=> false,
552 ApiBase
::PARAM_DEPRECATED
=> true,
555 ApiBase
::PARAM_DFLT
=> false,
556 ApiBase
::PARAM_DEPRECATED
=> true,
559 ApiBase
::PARAM_DFLT
=> 'preferences',
560 ApiBase
::PARAM_TYPE
=> [
569 ApiBase
::PARAM_TYPE
=> 'text',
572 ApiBase
::PARAM_TYPE
=> 'text',
575 ApiBase
::PARAM_TYPE
=> 'integer',
576 ApiBase
::PARAM_MIN
=> 0,
577 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
580 ApiBase
::PARAM_TYPE
=> 'integer',
581 ApiBase
::PARAM_MIN
=> 0,
582 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
585 ApiBase
::PARAM_TYPE
=> 'boolean',
586 ApiBase
::PARAM_DFLT
=> false,
589 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
592 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
595 // Standard definition automatically inserted
596 ApiBase
::PARAM_HELP_MSG_APPEND
=> [ 'apihelp-edit-param-token' ],
601 public function needsToken() {
605 protected function getExamplesMessages() {
607 'action=edit&title=Test&summary=test%20summary&' .
608 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
609 => 'apihelp-edit-example-edit',
610 'action=edit&title=Test&summary=NOTOC&minor=&' .
611 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
612 => 'apihelp-edit-example-prepend',
613 'action=edit&title=Test&undo=13585&undoafter=13579&' .
614 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
615 => 'apihelp-edit-example-undo',
619 public function getHelpUrls() {
620 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit';