5 * Created on August 16, 2007
7 * Copyright © 2007 Iker Labarga "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * A module that allows for editing and creating pages.
30 * Currently, this wraps around the EditPage class in an ugly way,
31 * EditPage.php should be rewritten to provide a cleaner interface,
32 * see T20654 if you're inspired to fix this.
36 class ApiEditPage
extends ApiBase
{
37 public function execute() {
38 $this->useTransactionalTimeLimit();
40 $user = $this->getUser();
41 $params = $this->extractRequestParams();
43 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
44 is_null( $params['prependtext'] ) &&
47 $this->dieUsageMsg( 'missingtext' );
50 $pageObj = $this->getTitleOrPageId( $params );
51 $titleObj = $pageObj->getTitle();
52 $apiResult = $this->getResult();
54 if ( $params['redirect'] ) {
55 if ( $params['prependtext'] === null && $params['appendtext'] === null
56 && $params['section'] !== 'new'
58 $this->dieUsage( 'You have attempted to edit using the "redirect"-following'
59 . ' mode, which must be used in conjuction with section=new, prependtext'
60 . ', or appendtext.', 'redirect-appendonly' );
62 if ( $titleObj->isRedirect() ) {
63 $oldTitle = $titleObj;
65 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
66 ->getContent( Revision
::FOR_THIS_USER
, $user )
68 // array_shift( $titles );
70 $redirValues = array();
72 /** @var $newTitle Title */
73 foreach ( $titles as $id => $newTitle ) {
75 if ( !isset( $titles[$id - 1] ) ) {
76 $titles[$id - 1] = $oldTitle;
79 $redirValues[] = array(
80 'from' => $titles[$id - 1]->getPrefixedText(),
81 'to' => $newTitle->getPrefixedText()
84 $titleObj = $newTitle;
87 ApiResult
::setIndexedTagName( $redirValues, 'r' );
88 $apiResult->addValue( null, 'redirects', $redirValues );
90 // Since the page changed, update $pageObj
91 $pageObj = WikiPage
::factory( $titleObj );
95 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
96 $contentHandler = $pageObj->getContentHandler();
98 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
101 $name = $titleObj->getPrefixedDBkey();
102 $model = $contentHandler->getModelID();
104 if ( $params['undo'] > 0 ) {
105 // allow undo via api
106 } elseif ( $contentHandler->supportsDirectApiEditing() === false ) {
108 "Direct editing via API is not supported for content model $model used by $name",
113 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
114 $params['contentformat'] = $contentHandler->getDefaultFormat();
117 $contentFormat = $params['contentformat'];
119 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
121 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
122 " $model used by $name", 'badformat' );
125 if ( $params['createonly'] && $titleObj->exists() ) {
126 $this->dieUsageMsg( 'createonly-exists' );
128 if ( $params['nocreate'] && !$titleObj->exists() ) {
129 $this->dieUsageMsg( 'nocreate-missing' );
132 // Now let's check whether we're even allowed to do this
133 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
134 if ( !$titleObj->exists() ) {
135 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
137 if ( count( $errors ) ) {
138 if ( is_array( $errors[0] ) ) {
139 switch ( $errors[0][0] ) {
142 'You have been blocked from editing',
145 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) )
148 case 'autoblockedtext':
150 'Your IP address has been blocked automatically, because it was used by a blocked user',
153 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) )
157 $this->dieUsageMsg( $errors[0] );
160 $this->dieUsageMsg( $errors[0] );
164 $toMD5 = $params['text'];
165 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
166 $content = $pageObj->getContent();
169 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
170 # If this is a MediaWiki:x message, then load the messages
171 # and return the message value for x.
172 $text = $titleObj->getDefaultMessageText();
173 if ( $text === false ) {
178 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
179 } catch ( MWContentSerializationException
$ex ) {
180 $this->dieUsage( $ex->getMessage(), 'parseerror' );
185 # Otherwise, make a new empty content.
186 $content = $contentHandler->makeEmptyContent();
190 // @todo Add support for appending/prepending to the Content interface
192 if ( !( $content instanceof TextContent
) ) {
193 $mode = $contentHandler->getModelID();
194 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
197 if ( !is_null( $params['section'] ) ) {
198 if ( !$contentHandler->supportsSections() ) {
199 $modelName = $contentHandler->getModelID();
201 "Sections are not supported for this content model: $modelName.",
202 'sectionsnotsupported'
206 if ( $params['section'] == 'new' ) {
207 // DWIM if they're trying to prepend/append to a new section.
210 // Process the content for section edits
211 $section = $params['section'];
212 $content = $content->getSection( $section );
215 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
223 $text = $content->serialize( $contentFormat );
226 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
227 $toMD5 = $params['prependtext'] . $params['appendtext'];
230 if ( $params['undo'] > 0 ) {
231 if ( $params['undoafter'] > 0 ) {
232 if ( $params['undo'] < $params['undoafter'] ) {
233 list( $params['undo'], $params['undoafter'] ) =
234 array( $params['undoafter'], $params['undo'] );
236 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
238 $undoRev = Revision
::newFromId( $params['undo'] );
239 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
240 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
243 if ( $params['undoafter'] == 0 ) {
244 $undoafterRev = $undoRev->getPrevious();
246 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
247 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
250 if ( $undoRev->getPage() != $pageObj->getId() ) {
251 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getId(),
252 $titleObj->getPrefixedText() ) );
254 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
255 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getId(),
256 $titleObj->getPrefixedText() ) );
259 $newContent = $contentHandler->getUndoContent(
260 $pageObj->getRevision(),
265 if ( !$newContent ) {
266 $this->dieUsageMsg( 'undo-failure' );
269 $params['text'] = $newContent->serialize( $params['contentformat'] );
271 // If no summary was given and we only undid one rev,
272 // use an autosummary
273 if ( is_null( $params['summary'] ) &&
274 $titleObj->getNextRevisionID( $undoafterRev->getId() ) == $params['undo']
276 $params['summary'] = wfMessage( 'undo-summary' )
277 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
281 // See if the MD5 hash checks out
282 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
283 $this->dieUsageMsg( 'hashcheckfailed' );
286 // EditPage wants to parse its stuff from a WebRequest
287 // That interface kind of sucks, but it's workable
288 $requestArray = array(
289 'wpTextbox1' => $params['text'],
290 'format' => $contentFormat,
291 'model' => $contentHandler->getModelID(),
292 'wpEditToken' => $params['token'],
293 'wpIgnoreBlankSummary' => true,
294 'wpIgnoreBlankArticle' => true,
295 'wpIgnoreSelfRedirect' => true,
296 'bot' => $params['bot'],
299 if ( !is_null( $params['summary'] ) ) {
300 $requestArray['wpSummary'] = $params['summary'];
303 if ( !is_null( $params['sectiontitle'] ) ) {
304 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
307 // TODO: Pass along information from 'undoafter' as well
308 if ( $params['undo'] > 0 ) {
309 $requestArray['wpUndidRevision'] = $params['undo'];
312 // Watch out for basetimestamp == '' or '0'
313 // It gets treated as NOW, almost certainly causing an edit conflict
314 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
315 $requestArray['wpEdittime'] = $params['basetimestamp'];
317 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
320 if ( $params['starttimestamp'] !== null ) {
321 $requestArray['wpStarttime'] = $params['starttimestamp'];
323 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
326 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
327 $requestArray['wpMinoredit'] = '';
330 if ( $params['recreate'] ) {
331 $requestArray['wpRecreate'] = '';
334 if ( !is_null( $params['section'] ) ) {
335 $section = $params['section'];
336 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
337 $this->dieUsage( "The section parameter must be a valid section id or 'new'",
340 $content = $pageObj->getContent();
341 if ( $section !== '0' && $section != 'new'
342 && ( !$content ||
!$content->getSection( $section ) )
344 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
346 $requestArray['wpSection'] = $params['section'];
348 $requestArray['wpSection'] = '';
351 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
353 // Deprecated parameters
354 if ( $params['watch'] ) {
356 } elseif ( $params['unwatch'] ) {
361 $requestArray['wpWatchthis'] = '';
365 if ( count( $params['tags'] ) ) {
366 if ( $user->isAllowed( 'applychangetags' ) ) {
367 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
369 $this->dieUsage( 'You don\'t have permission to set change tags.', 'taggingnotallowed' );
373 // Pass through anything else we might have been given, to support extensions
374 // This is kind of a hack but it's the best we can do to make extensions work
375 $requestArray +
= $this->getRequest()->getValues();
377 global $wgTitle, $wgRequest;
379 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
381 // Some functions depend on $wgTitle == $ep->mTitle
382 // TODO: Make them not or check if they still do
383 $wgTitle = $titleObj;
385 $articleContext = new RequestContext
;
386 $articleContext->setRequest( $req );
387 $articleContext->setWikiPage( $pageObj );
388 $articleContext->setUser( $this->getUser() );
390 /** @var $articleObject Article */
391 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
393 $ep = new EditPage( $articleObject );
395 $ep->setApiEditOverride( true );
396 $ep->setContextTitle( $titleObj );
397 $ep->importFormData( $req );
398 $content = $ep->textbox1
;
400 // The following is needed to give the hook the full content of the
401 // new revision rather than just the current section. (Bug 52077)
402 if ( !is_null( $params['section'] ) &&
403 $contentHandler->supportsSections() && $titleObj->exists()
405 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
406 // backwards compatibility with old forms/bots).
407 if ( $ep->sectiontitle
!== '' ) {
408 $sectionTitle = $ep->sectiontitle
;
410 $sectionTitle = $ep->summary
;
413 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
415 $fullContentObj = $articleObject->replaceSectionContent(
420 if ( $fullContentObj ) {
421 $content = $fullContentObj->serialize( $contentFormat );
423 // This most likely means we have an edit conflict which means that the edit
424 // wont succeed anyway.
425 $this->dieUsageMsg( 'editconflict' );
430 // Handle APIEditBeforeSave parameters
432 if ( !Hooks
::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
434 $r['result'] = 'Failure';
435 $apiResult->addValue( null, $this->getModuleName(), $r );
440 $this->dieUsageMsg( 'hookaborted' );
443 // Do the actual save
444 $oldRevId = $articleObject->getRevIdFetched();
446 // Fake $wgRequest for some hooks inside EditPage
447 // @todo FIXME: This interface SUCKS
448 $oldRequest = $wgRequest;
451 $status = $ep->attemptSave( $result );
452 $wgRequest = $oldRequest;
454 switch ( $status->value
) {
455 case EditPage
::AS_HOOK_ERROR
:
456 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
457 if ( isset( $status->apiHookResult
) ) {
458 $r = $status->apiHookResult
;
459 $r['result'] = 'Failure';
460 $apiResult->addValue( null, $this->getModuleName(), $r );
463 $this->dieUsageMsg( 'hookaborted' );
466 case EditPage
::AS_PARSE_ERROR
:
467 $this->dieUsage( $status->getMessage(), 'parseerror' );
469 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
470 $this->dieUsageMsg( 'noimageredirect-anon' );
472 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
473 $this->dieUsageMsg( 'noimageredirect-logged' );
475 case EditPage
::AS_SPAM_ERROR
:
476 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
478 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
480 'You have been blocked from editing',
483 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) )
486 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
487 case EditPage
::AS_CONTENT_TOO_BIG
:
488 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
490 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
491 $this->dieUsageMsg( 'noedit-anon' );
493 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
494 $this->dieUsageMsg( 'noedit' );
496 case EditPage
::AS_READ_ONLY_PAGE
:
497 $this->dieReadOnly();
499 case EditPage
::AS_RATE_LIMITED
:
500 $this->dieUsageMsg( 'actionthrottledtext' );
502 case EditPage
::AS_ARTICLE_WAS_DELETED
:
503 $this->dieUsageMsg( 'wasdeleted' );
505 case EditPage
::AS_NO_CREATE_PERMISSION
:
506 $this->dieUsageMsg( 'nocreate-loggedin' );
508 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
509 $this->dieUsageMsg( 'cantchangecontentmodel' );
511 case EditPage
::AS_BLANK_ARTICLE
:
512 $this->dieUsageMsg( 'blankpage' );
514 case EditPage
::AS_CONFLICT_DETECTED
:
515 $this->dieUsageMsg( 'editconflict' );
517 case EditPage
::AS_TEXTBOX_EMPTY
:
518 $this->dieUsageMsg( 'emptynewsection' );
520 case EditPage
::AS_CHANGE_TAG_ERROR
:
521 $this->dieStatus( $status );
523 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
527 case EditPage
::AS_SUCCESS_UPDATE
:
528 $r['result'] = 'Success';
529 $r['pageid'] = intval( $titleObj->getArticleID() );
530 $r['title'] = $titleObj->getPrefixedText();
531 $r['contentmodel'] = $articleObject->getContentModel();
532 $newRevId = $articleObject->getLatest();
533 if ( $newRevId == $oldRevId ) {
534 $r['nochange'] = true;
536 $r['oldrevid'] = intval( $oldRevId );
537 $r['newrevid'] = intval( $newRevId );
538 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
539 $pageObj->getTimestamp() );
543 case EditPage
::AS_SUMMARY_NEEDED
:
544 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
545 $this->dieUsageMsg( 'summaryrequired' );
547 case EditPage
::AS_END
:
549 // $status came from WikiPage::doEdit()
550 $errors = $status->getErrorsArray();
551 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
554 $apiResult->addValue( null, $this->getModuleName(), $r );
557 public function mustBePosted() {
561 public function isWriteMode() {
565 public function getAllowedParams() {
568 ApiBase
::PARAM_TYPE
=> 'string',
571 ApiBase
::PARAM_TYPE
=> 'integer',
574 'sectiontitle' => array(
575 ApiBase
::PARAM_TYPE
=> 'string',
578 ApiBase
::PARAM_TYPE
=> 'text',
582 ApiBase
::PARAM_TYPE
=> ChangeTags
::listExplicitlyDefinedTags(),
583 ApiBase
::PARAM_ISMULTI
=> true,
588 'basetimestamp' => array(
589 ApiBase
::PARAM_TYPE
=> 'timestamp',
591 'starttimestamp' => array(
592 ApiBase
::PARAM_TYPE
=> 'timestamp',
595 'createonly' => false,
598 ApiBase
::PARAM_DFLT
=> false,
599 ApiBase
::PARAM_DEPRECATED
=> true,
602 ApiBase
::PARAM_DFLT
=> false,
603 ApiBase
::PARAM_DEPRECATED
=> true,
605 'watchlist' => array(
606 ApiBase
::PARAM_DFLT
=> 'preferences',
607 ApiBase
::PARAM_TYPE
=> array(
615 'prependtext' => array(
616 ApiBase
::PARAM_TYPE
=> 'text',
618 'appendtext' => array(
619 ApiBase
::PARAM_TYPE
=> 'text',
622 ApiBase
::PARAM_TYPE
=> 'integer'
624 'undoafter' => array(
625 ApiBase
::PARAM_TYPE
=> 'integer'
628 ApiBase
::PARAM_TYPE
=> 'boolean',
629 ApiBase
::PARAM_DFLT
=> false,
631 'contentformat' => array(
632 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
634 'contentmodel' => array(
635 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
638 // Standard definition automatically inserted
639 ApiBase
::PARAM_HELP_MSG_APPEND
=> array( 'apihelp-edit-param-token' ),
644 public function needsToken() {
648 protected function getExamplesMessages() {
650 'action=edit&title=Test&summary=test%20summary&' .
651 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
652 => 'apihelp-edit-example-edit',
653 'action=edit&title=Test&summary=NOTOC&minor=&' .
654 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
655 => 'apihelp-edit-example-prepend',
656 'action=edit&title=Test&undo=13585&undoafter=13579&' .
657 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
658 => 'apihelp-edit-example-undo',
662 public function getHelpUrls() {
663 return 'https://www.mediawiki.org/wiki/API:Edit';