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();
103 if ( $contentHandler->supportsDirectApiEditing() === false ) {
105 "Direct editing via API is not supported for content model $model used by $name",
110 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
111 $params['contentformat'] = $contentHandler->getDefaultFormat();
114 $contentFormat = $params['contentformat'];
116 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
118 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
119 " $model used by $name", 'badformat' );
122 if ( $params['createonly'] && $titleObj->exists() ) {
123 $this->dieUsageMsg( 'createonly-exists' );
125 if ( $params['nocreate'] && !$titleObj->exists() ) {
126 $this->dieUsageMsg( 'nocreate-missing' );
129 // Now let's check whether we're even allowed to do this
130 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
131 if ( !$titleObj->exists() ) {
132 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
134 if ( count( $errors ) ) {
135 if ( is_array( $errors[0] ) ) {
136 switch ( $errors[0][0] ) {
139 'You have been blocked from editing',
142 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) )
145 case 'autoblockedtext':
147 'Your IP address has been blocked automatically, because it was used by a blocked user',
150 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) )
154 $this->dieUsageMsg( $errors[0] );
157 $this->dieUsageMsg( $errors[0] );
161 $toMD5 = $params['text'];
162 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
163 $content = $pageObj->getContent();
166 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
167 # If this is a MediaWiki:x message, then load the messages
168 # and return the message value for x.
169 $text = $titleObj->getDefaultMessageText();
170 if ( $text === false ) {
175 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
176 } catch ( MWContentSerializationException
$ex ) {
177 $this->dieUsage( $ex->getMessage(), 'parseerror' );
182 # Otherwise, make a new empty content.
183 $content = $contentHandler->makeEmptyContent();
187 // @todo Add support for appending/prepending to the Content interface
189 if ( !( $content instanceof TextContent
) ) {
190 $mode = $contentHandler->getModelID();
191 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
194 if ( !is_null( $params['section'] ) ) {
195 if ( !$contentHandler->supportsSections() ) {
196 $modelName = $contentHandler->getModelID();
198 "Sections are not supported for this content model: $modelName.",
199 'sectionsnotsupported'
203 if ( $params['section'] == 'new' ) {
204 // DWIM if they're trying to prepend/append to a new section.
207 // Process the content for section edits
208 $section = $params['section'];
209 $content = $content->getSection( $section );
212 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
220 $text = $content->serialize( $contentFormat );
223 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
224 $toMD5 = $params['prependtext'] . $params['appendtext'];
227 if ( $params['undo'] > 0 ) {
228 if ( $params['undoafter'] > 0 ) {
229 if ( $params['undo'] < $params['undoafter'] ) {
230 list( $params['undo'], $params['undoafter'] ) =
231 array( $params['undoafter'], $params['undo'] );
233 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
235 $undoRev = Revision
::newFromId( $params['undo'] );
236 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
237 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
240 if ( $params['undoafter'] == 0 ) {
241 $undoafterRev = $undoRev->getPrevious();
243 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
244 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
247 if ( $undoRev->getPage() != $pageObj->getID() ) {
248 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
249 $titleObj->getPrefixedText() ) );
251 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
252 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
253 $titleObj->getPrefixedText() ) );
256 $newContent = $contentHandler->getUndoContent(
257 $pageObj->getRevision(),
262 if ( !$newContent ) {
263 $this->dieUsageMsg( 'undo-failure' );
266 $params['text'] = $newContent->serialize( $params['contentformat'] );
268 // If no summary was given and we only undid one rev,
269 // use an autosummary
270 if ( is_null( $params['summary'] ) &&
271 $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo']
273 $params['summary'] = wfMessage( 'undo-summary' )
274 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
278 // See if the MD5 hash checks out
279 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
280 $this->dieUsageMsg( 'hashcheckfailed' );
283 // EditPage wants to parse its stuff from a WebRequest
284 // That interface kind of sucks, but it's workable
285 $requestArray = array(
286 'wpTextbox1' => $params['text'],
287 'format' => $contentFormat,
288 'model' => $contentHandler->getModelID(),
289 'wpEditToken' => $params['token'],
290 'wpIgnoreBlankSummary' => true,
291 'wpIgnoreBlankArticle' => true,
292 'wpIgnoreSelfRedirect' => true,
293 'bot' => $params['bot'],
296 if ( !is_null( $params['summary'] ) ) {
297 $requestArray['wpSummary'] = $params['summary'];
300 if ( !is_null( $params['sectiontitle'] ) ) {
301 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
304 // TODO: Pass along information from 'undoafter' as well
305 if ( $params['undo'] > 0 ) {
306 $requestArray['wpUndidRevision'] = $params['undo'];
309 // Watch out for basetimestamp == '' or '0'
310 // It gets treated as NOW, almost certainly causing an edit conflict
311 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
312 $requestArray['wpEdittime'] = $params['basetimestamp'];
314 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
317 if ( $params['starttimestamp'] !== null ) {
318 $requestArray['wpStarttime'] = $params['starttimestamp'];
320 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
323 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
324 $requestArray['wpMinoredit'] = '';
327 if ( $params['recreate'] ) {
328 $requestArray['wpRecreate'] = '';
331 if ( !is_null( $params['section'] ) ) {
332 $section = $params['section'];
333 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
334 $this->dieUsage( "The section parameter must be a valid section id or 'new'",
337 $content = $pageObj->getContent();
338 if ( $section !== '0' && $section != 'new'
339 && ( !$content ||
!$content->getSection( $section ) )
341 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
343 $requestArray['wpSection'] = $params['section'];
345 $requestArray['wpSection'] = '';
348 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
350 // Deprecated parameters
351 if ( $params['watch'] ) {
352 $this->logFeatureUsage( 'action=edit&watch' );
354 } elseif ( $params['unwatch'] ) {
355 $this->logFeatureUsage( 'action=edit&unwatch' );
360 $requestArray['wpWatchthis'] = '';
364 if ( count( $params['tags'] ) ) {
365 if ( $user->isAllowed( 'applychangetags' ) ) {
366 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
368 $this->dieUsage( 'You don\'t have permission to set change tags.', 'taggingnotallowed' );
372 // Pass through anything else we might have been given, to support extensions
373 // This is kind of a hack but it's the best we can do to make extensions work
374 $requestArray +
= $this->getRequest()->getValues();
376 global $wgTitle, $wgRequest;
378 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
380 // Some functions depend on $wgTitle == $ep->mTitle
381 // TODO: Make them not or check if they still do
382 $wgTitle = $titleObj;
384 $articleContext = new RequestContext
;
385 $articleContext->setRequest( $req );
386 $articleContext->setWikiPage( $pageObj );
387 $articleContext->setUser( $this->getUser() );
389 /** @var $articleObject Article */
390 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
392 $ep = new EditPage( $articleObject );
394 $ep->setApiEditOverride( true );
395 $ep->setContextTitle( $titleObj );
396 $ep->importFormData( $req );
397 $content = $ep->textbox1
;
399 // The following is needed to give the hook the full content of the
400 // new revision rather than just the current section. (Bug 52077)
401 if ( !is_null( $params['section'] ) &&
402 $contentHandler->supportsSections() && $titleObj->exists()
404 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
405 // backwards compatibility with old forms/bots).
406 if ( $ep->sectiontitle
!== '' ) {
407 $sectionTitle = $ep->sectiontitle
;
409 $sectionTitle = $ep->summary
;
412 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
414 $fullContentObj = $articleObject->replaceSectionContent(
419 if ( $fullContentObj ) {
420 $content = $fullContentObj->serialize( $contentFormat );
422 // This most likely means we have an edit conflict which means that the edit
423 // wont succeed anyway.
424 $this->dieUsageMsg( 'editconflict' );
429 // Handle APIEditBeforeSave parameters
431 if ( !Hooks
::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
433 $r['result'] = 'Failure';
434 $apiResult->addValue( null, $this->getModuleName(), $r );
439 $this->dieUsageMsg( 'hookaborted' );
442 // Do the actual save
443 $oldRevId = $articleObject->getRevIdFetched();
445 // Fake $wgRequest for some hooks inside EditPage
446 // @todo FIXME: This interface SUCKS
447 $oldRequest = $wgRequest;
450 $status = $ep->attemptSave( $result );
451 $wgRequest = $oldRequest;
453 switch ( $status->value
) {
454 case EditPage
::AS_HOOK_ERROR
:
455 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
456 if ( isset( $status->apiHookResult
) ) {
457 $r = $status->apiHookResult
;
458 $r['result'] = 'Failure';
459 $apiResult->addValue( null, $this->getModuleName(), $r );
462 $this->dieUsageMsg( 'hookaborted' );
465 case EditPage
::AS_PARSE_ERROR
:
466 $this->dieUsage( $status->getMessage(), 'parseerror' );
468 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
469 $this->dieUsageMsg( 'noimageredirect-anon' );
471 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
472 $this->dieUsageMsg( 'noimageredirect-logged' );
474 case EditPage
::AS_SPAM_ERROR
:
475 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
477 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
479 'You have been blocked from editing',
482 array( 'blockinfo' => ApiQueryUserInfo
::getBlockInfo( $user->getBlock() ) )
485 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
486 case EditPage
::AS_CONTENT_TOO_BIG
:
487 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
489 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
490 $this->dieUsageMsg( 'noedit-anon' );
492 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
493 $this->dieUsageMsg( 'noedit' );
495 case EditPage
::AS_READ_ONLY_PAGE
:
496 $this->dieReadOnly();
498 case EditPage
::AS_RATE_LIMITED
:
499 $this->dieUsageMsg( 'actionthrottledtext' );
501 case EditPage
::AS_ARTICLE_WAS_DELETED
:
502 $this->dieUsageMsg( 'wasdeleted' );
504 case EditPage
::AS_NO_CREATE_PERMISSION
:
505 $this->dieUsageMsg( 'nocreate-loggedin' );
507 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
508 $this->dieUsageMsg( 'cantchangecontentmodel' );
510 case EditPage
::AS_BLANK_ARTICLE
:
511 $this->dieUsageMsg( 'blankpage' );
513 case EditPage
::AS_CONFLICT_DETECTED
:
514 $this->dieUsageMsg( 'editconflict' );
516 case EditPage
::AS_TEXTBOX_EMPTY
:
517 $this->dieUsageMsg( 'emptynewsection' );
519 case EditPage
::AS_CHANGE_TAG_ERROR
:
520 $this->dieStatus( $status );
522 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
526 case EditPage
::AS_SUCCESS_UPDATE
:
527 $r['result'] = 'Success';
528 $r['pageid'] = intval( $titleObj->getArticleID() );
529 $r['title'] = $titleObj->getPrefixedText();
530 $r['contentmodel'] = $articleObject->getContentModel();
531 $newRevId = $articleObject->getLatest();
532 if ( $newRevId == $oldRevId ) {
533 $r['nochange'] = true;
535 $r['oldrevid'] = intval( $oldRevId );
536 $r['newrevid'] = intval( $newRevId );
537 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
538 $pageObj->getTimestamp() );
542 case EditPage
::AS_SUMMARY_NEEDED
:
543 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
544 $this->dieUsageMsg( 'summaryrequired' );
546 case EditPage
::AS_END
:
548 // $status came from WikiPage::doEdit()
549 $errors = $status->getErrorsArray();
550 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
553 $apiResult->addValue( null, $this->getModuleName(), $r );
556 public function mustBePosted() {
560 public function isWriteMode() {
564 public function getAllowedParams() {
567 ApiBase
::PARAM_TYPE
=> 'string',
570 ApiBase
::PARAM_TYPE
=> 'integer',
573 'sectiontitle' => array(
574 ApiBase
::PARAM_TYPE
=> 'string',
577 ApiBase
::PARAM_TYPE
=> 'text',
581 ApiBase
::PARAM_TYPE
=> ChangeTags
::listExplicitlyDefinedTags(),
582 ApiBase
::PARAM_ISMULTI
=> true,
587 'basetimestamp' => array(
588 ApiBase
::PARAM_TYPE
=> 'timestamp',
590 'starttimestamp' => array(
591 ApiBase
::PARAM_TYPE
=> 'timestamp',
594 'createonly' => false,
597 ApiBase
::PARAM_DFLT
=> false,
598 ApiBase
::PARAM_DEPRECATED
=> true,
601 ApiBase
::PARAM_DFLT
=> false,
602 ApiBase
::PARAM_DEPRECATED
=> true,
604 'watchlist' => array(
605 ApiBase
::PARAM_DFLT
=> 'preferences',
606 ApiBase
::PARAM_TYPE
=> array(
614 'prependtext' => array(
615 ApiBase
::PARAM_TYPE
=> 'text',
617 'appendtext' => array(
618 ApiBase
::PARAM_TYPE
=> 'text',
621 ApiBase
::PARAM_TYPE
=> 'integer'
623 'undoafter' => array(
624 ApiBase
::PARAM_TYPE
=> 'integer'
627 ApiBase
::PARAM_TYPE
=> 'boolean',
628 ApiBase
::PARAM_DFLT
=> false,
630 'contentformat' => array(
631 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
633 'contentmodel' => array(
634 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
637 // Standard definition automatically inserted
638 ApiBase
::PARAM_HELP_MSG_APPEND
=> array( 'apihelp-edit-param-token' ),
643 public function needsToken() {
647 protected function getExamplesMessages() {
649 'action=edit&title=Test&summary=test%20summary&' .
650 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
651 => 'apihelp-edit-example-edit',
652 'action=edit&title=Test&summary=NOTOC&minor=&' .
653 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
654 => 'apihelp-edit-example-prepend',
655 'action=edit&title=Test&undo=13585&undoafter=13579&' .
656 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
657 => 'apihelp-edit-example-undo',
661 public function getHelpUrls() {
662 return 'https://www.mediawiki.org/wiki/API:Edit';