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' ]
122 $toMD5 = $params['text'];
123 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
124 $content = $pageObj->getContent();
127 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
128 # If this is a MediaWiki:x message, then load the messages
129 # and return the message value for x.
130 $text = $titleObj->getDefaultMessageText();
131 if ( $text === false ) {
136 $content = ContentHandler
::makeContent( $text, $titleObj );
137 } catch ( MWContentSerializationException
$ex ) {
138 $this->dieWithException( $ex, [
139 'wrap' => ApiMessage
::create( 'apierror-contentserializationexception', 'parseerror' )
144 # Otherwise, make a new empty content.
145 $content = $contentHandler->makeEmptyContent();
149 // @todo Add support for appending/prepending to the Content interface
151 if ( !( $content instanceof TextContent
) ) {
152 $modelName = $contentHandler->getModelID();
153 $this->dieWithError( [ 'apierror-appendnotsupported', $modelName ] );
156 if ( !is_null( $params['section'] ) ) {
157 if ( !$contentHandler->supportsSections() ) {
158 $modelName = $contentHandler->getModelID();
159 $this->dieWithError( [ 'apierror-sectionsnotsupported', $modelName ] );
162 if ( $params['section'] == 'new' ) {
163 // DWIM if they're trying to prepend/append to a new section.
166 // Process the content for section edits
167 $section = $params['section'];
168 $content = $content->getSection( $section );
171 $this->dieWithError( [ 'apierror-nosuchsection', wfEscapeWikiText( $section ) ] );
179 $text = $content->serialize( $contentFormat );
182 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
183 $toMD5 = $params['prependtext'] . $params['appendtext'];
186 if ( $params['undo'] > 0 ) {
187 if ( $params['undoafter'] > 0 ) {
188 if ( $params['undo'] < $params['undoafter'] ) {
189 list( $params['undo'], $params['undoafter'] ) =
190 [ $params['undoafter'], $params['undo'] ];
192 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
194 $undoRev = Revision
::newFromId( $params['undo'] );
195 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
196 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undo'] ] );
199 if ( $params['undoafter'] == 0 ) {
200 $undoafterRev = $undoRev->getPrevious();
202 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
203 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undoafter'] ] );
206 if ( $undoRev->getPage() != $pageObj->getId() ) {
207 $this->dieWithError( [ 'apierror-revwrongpage', $undoRev->getId(),
208 $titleObj->getPrefixedText() ] );
210 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
211 $this->dieWithError( [ 'apierror-revwrongpage', $undoafterRev->getId(),
212 $titleObj->getPrefixedText() ] );
215 $newContent = $contentHandler->getUndoContent(
216 $pageObj->getRevision(),
221 if ( !$newContent ) {
222 $this->dieWithError( 'undo-failure', 'undofailure' );
224 if ( empty( $params['contentmodel'] )
225 && empty( $params['contentformat'] )
227 // If we are reverting content model, the new content model
228 // might not support the current serialization format, in
229 // which case go back to the old serialization format,
230 // but only if the user hasn't specified a format/model
232 if ( !$newContent->isSupportedFormat( $contentFormat ) ) {
233 $contentFormat = $undoafterRev->getContentFormat();
235 // Override content model with model of undid revision.
236 $contentModel = $newContent->getModel();
238 $params['text'] = $newContent->serialize( $contentFormat );
239 // If no summary was given and we only undid one rev,
240 // use an autosummary
241 if ( is_null( $params['summary'] ) &&
242 $titleObj->getNextRevisionID( $undoafterRev->getId() ) == $params['undo']
244 $params['summary'] = wfMessage( 'undo-summary' )
245 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
249 // See if the MD5 hash checks out
250 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
251 $this->dieWithError( 'apierror-badmd5' );
254 // EditPage wants to parse its stuff from a WebRequest
255 // That interface kind of sucks, but it's workable
257 'wpTextbox1' => $params['text'],
258 'format' => $contentFormat,
259 'model' => $contentModel,
260 'wpEditToken' => $params['token'],
261 'wpIgnoreBlankSummary' => true,
262 'wpIgnoreBlankArticle' => true,
263 'wpIgnoreSelfRedirect' => true,
264 'bot' => $params['bot'],
265 'wpUnicodeCheck' => EditPage
::UNICODE_CHECK
,
268 if ( !is_null( $params['summary'] ) ) {
269 $requestArray['wpSummary'] = $params['summary'];
272 if ( !is_null( $params['sectiontitle'] ) ) {
273 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
276 // TODO: Pass along information from 'undoafter' as well
277 if ( $params['undo'] > 0 ) {
278 $requestArray['wpUndidRevision'] = $params['undo'];
281 // Watch out for basetimestamp == '' or '0'
282 // It gets treated as NOW, almost certainly causing an edit conflict
283 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
284 $requestArray['wpEdittime'] = $params['basetimestamp'];
286 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
289 if ( $params['starttimestamp'] !== null ) {
290 $requestArray['wpStarttime'] = $params['starttimestamp'];
292 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
295 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
296 $requestArray['wpMinoredit'] = '';
299 if ( $params['recreate'] ) {
300 $requestArray['wpRecreate'] = '';
303 if ( !is_null( $params['section'] ) ) {
304 $section = $params['section'];
305 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
306 $this->dieWithError( 'apierror-invalidsection' );
308 $content = $pageObj->getContent();
309 if ( $section !== '0' && $section != 'new'
310 && ( !$content ||
!$content->getSection( $section ) )
312 $this->dieWithError( [ 'apierror-nosuchsection', $section ] );
314 $requestArray['wpSection'] = $params['section'];
316 $requestArray['wpSection'] = '';
319 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
321 // Deprecated parameters
322 if ( $params['watch'] ) {
324 } elseif ( $params['unwatch'] ) {
329 $requestArray['wpWatchthis'] = '';
333 if ( $params['tags'] ) {
334 $tagStatus = ChangeTags
::canAddTagsAccompanyingChange( $params['tags'], $user );
335 if ( $tagStatus->isOK() ) {
336 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
338 $this->dieStatus( $tagStatus );
342 // Pass through anything else we might have been given, to support extensions
343 // This is kind of a hack but it's the best we can do to make extensions work
344 $requestArray +
= $this->getRequest()->getValues();
346 global $wgTitle, $wgRequest;
348 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
350 // Some functions depend on $wgTitle == $ep->mTitle
351 // TODO: Make them not or check if they still do
352 $wgTitle = $titleObj;
354 $articleContext = new RequestContext
;
355 $articleContext->setRequest( $req );
356 $articleContext->setWikiPage( $pageObj );
357 $articleContext->setUser( $this->getUser() );
359 /** @var Article $articleObject */
360 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
362 $ep = new EditPage( $articleObject );
364 $ep->setApiEditOverride( true );
365 $ep->setContextTitle( $titleObj );
366 $ep->importFormData( $req );
367 $content = $ep->textbox1
;
370 // Handle APIEditBeforeSave parameters
372 // Deprecated in favour of EditFilterMergedContent
373 if ( !Hooks
::run( 'APIEditBeforeSave', [ $ep, $content, &$r ], '1.28' ) ) {
375 $r['result'] = 'Failure';
376 $apiResult->addValue( null, $this->getModuleName(), $r );
381 $this->dieWithError( 'hookaborted' );
384 // Do the actual save
385 $oldRevId = $articleObject->getRevIdFetched();
387 // Fake $wgRequest for some hooks inside EditPage
388 // @todo FIXME: This interface SUCKS
389 $oldRequest = $wgRequest;
392 $status = $ep->attemptSave( $result );
393 $wgRequest = $oldRequest;
395 switch ( $status->value
) {
396 case EditPage
::AS_HOOK_ERROR
:
397 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
398 if ( isset( $status->apiHookResult
) ) {
399 $r = $status->apiHookResult
;
400 $r['result'] = 'Failure';
401 $apiResult->addValue( null, $this->getModuleName(), $r );
404 if ( !$status->getErrors() ) {
405 // This appears to be unreachable right now, because all
406 // code paths will set an error. Could change, though.
407 $status->fatal( 'hookaborted' ); //@codeCoverageIgnore
409 $this->dieStatus( $status );
411 // These two cases will normally have been caught earlier, and will
412 // only occur if something blocks the user between the earlier
413 // check and the check in EditPage (presumably a hook). It's not
414 // obvious that this is even possible.
415 // @codeCoverageIgnoreStart
416 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
417 $this->dieBlocked( $user->getBlock() );
419 case EditPage
::AS_READ_ONLY_PAGE
:
420 $this->dieReadOnly();
421 // @codeCoverageIgnoreEnd
423 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
427 case EditPage
::AS_SUCCESS_UPDATE
:
428 $r['result'] = 'Success';
429 $r['pageid'] = intval( $titleObj->getArticleID() );
430 $r['title'] = $titleObj->getPrefixedText();
431 $r['contentmodel'] = $articleObject->getContentModel();
432 $newRevId = $articleObject->getLatest();
433 if ( $newRevId == $oldRevId ) {
434 $r['nochange'] = true;
436 $r['oldrevid'] = intval( $oldRevId );
437 $r['newrevid'] = intval( $newRevId );
438 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
439 $pageObj->getTimestamp() );
444 if ( !$status->getErrors() ) {
445 // EditPage sometimes only sets the status code without setting
446 // any actual error messages. Supply defaults for those cases.
447 switch ( $status->value
) {
449 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
450 $status->fatal( 'apierror-noimageredirect-anon' );
452 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
453 $status->fatal( 'apierror-noimageredirect' );
455 case EditPage
::AS_CONTENT_TOO_BIG
:
456 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
457 $status->fatal( 'apierror-contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) );
459 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
460 $status->fatal( 'apierror-noedit-anon' );
462 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
463 $status->fatal( 'apierror-cantchangecontentmodel' );
465 case EditPage
::AS_ARTICLE_WAS_DELETED
:
466 $status->fatal( 'apierror-pagedeleted' );
468 case EditPage
::AS_CONFLICT_DETECTED
:
469 $status->fatal( 'editconflict' );
472 // Currently shouldn't be needed, but here in case
473 // hooks use them without setting appropriate
474 // errors on the status.
475 // @codeCoverageIgnoreStart
476 case EditPage
::AS_SPAM_ERROR
:
477 $status->fatal( 'apierror-spamdetected', $result['spam'] );
479 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
480 $status->fatal( 'apierror-noedit' );
482 case EditPage
::AS_RATE_LIMITED
:
483 $status->fatal( 'apierror-ratelimited' );
485 case EditPage
::AS_NO_CREATE_PERMISSION
:
486 $status->fatal( 'nocreate-loggedin' );
488 case EditPage
::AS_BLANK_ARTICLE
:
489 $status->fatal( 'apierror-emptypage' );
491 case EditPage
::AS_TEXTBOX_EMPTY
:
492 $status->fatal( 'apierror-emptynewsection' );
494 case EditPage
::AS_SUMMARY_NEEDED
:
495 $status->fatal( 'apierror-summaryrequired' );
498 wfWarn( __METHOD__
. ": Unknown EditPage code {$status->value} with no message" );
499 $status->fatal( 'apierror-unknownerror-editpage', $status->value
);
501 // @codeCoverageIgnoreEnd
504 $this->dieStatus( $status );
506 $apiResult->addValue( null, $this->getModuleName(), $r );
509 public function mustBePosted() {
513 public function isWriteMode() {
517 public function getAllowedParams() {
520 ApiBase
::PARAM_TYPE
=> 'string',
523 ApiBase
::PARAM_TYPE
=> 'integer',
527 ApiBase
::PARAM_TYPE
=> 'string',
530 ApiBase
::PARAM_TYPE
=> 'text',
534 ApiBase
::PARAM_TYPE
=> 'tags',
535 ApiBase
::PARAM_ISMULTI
=> true,
541 ApiBase
::PARAM_TYPE
=> 'timestamp',
543 'starttimestamp' => [
544 ApiBase
::PARAM_TYPE
=> 'timestamp',
547 'createonly' => false,
550 ApiBase
::PARAM_DFLT
=> false,
551 ApiBase
::PARAM_DEPRECATED
=> true,
554 ApiBase
::PARAM_DFLT
=> false,
555 ApiBase
::PARAM_DEPRECATED
=> true,
558 ApiBase
::PARAM_DFLT
=> 'preferences',
559 ApiBase
::PARAM_TYPE
=> [
568 ApiBase
::PARAM_TYPE
=> 'text',
571 ApiBase
::PARAM_TYPE
=> 'text',
574 ApiBase
::PARAM_TYPE
=> 'integer',
575 ApiBase
::PARAM_MIN
=> 0,
576 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
579 ApiBase
::PARAM_TYPE
=> 'integer',
580 ApiBase
::PARAM_MIN
=> 0,
581 ApiBase
::PARAM_RANGE_ENFORCE
=> true,
584 ApiBase
::PARAM_TYPE
=> 'boolean',
585 ApiBase
::PARAM_DFLT
=> false,
588 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
591 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
594 // Standard definition automatically inserted
595 ApiBase
::PARAM_HELP_MSG_APPEND
=> [ 'apihelp-edit-param-token' ],
600 public function needsToken() {
604 protected function getExamplesMessages() {
606 'action=edit&title=Test&summary=test%20summary&' .
607 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
608 => 'apihelp-edit-example-edit',
609 'action=edit&title=Test&summary=NOTOC&minor=&' .
610 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
611 => 'apihelp-edit-example-prepend',
612 'action=edit&title=Test&undo=13585&undoafter=13579&' .
613 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
614 => 'apihelp-edit-example-undo',
618 public function getHelpUrls() {
619 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit';