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 $user = $this->getUser();
39 $params = $this->extractRequestParams();
41 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
42 is_null( $params['prependtext'] ) &&
45 $this->dieUsageMsg( 'missingtext' );
48 $pageObj = $this->getTitleOrPageId( $params );
49 $titleObj = $pageObj->getTitle();
50 $apiResult = $this->getResult();
52 if ( $params['redirect'] ) {
53 if ( $params['prependtext'] === null && $params['appendtext'] === null
54 && $params['section'] !== 'new'
56 $this->dieUsage( 'You have attempted to edit using the "redirect"-following'
57 . ' mode, which must be used in conjuction with section=new, prependtext'
58 . ', or appendtext.', 'redirect-appendonly' );
60 if ( $titleObj->isRedirect() ) {
61 $oldTitle = $titleObj;
63 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
64 ->getContent( Revision
::FOR_THIS_USER
, $user )
66 // array_shift( $titles );
68 $redirValues = array();
70 /** @var $newTitle Title */
71 foreach ( $titles as $id => $newTitle ) {
73 if ( !isset( $titles[$id - 1] ) ) {
74 $titles[$id - 1] = $oldTitle;
77 $redirValues[] = array(
78 'from' => $titles[$id - 1]->getPrefixedText(),
79 'to' => $newTitle->getPrefixedText()
82 $titleObj = $newTitle;
85 ApiResult
::setIndexedTagName( $redirValues, 'r' );
86 $apiResult->addValue( null, 'redirects', $redirValues );
88 // Since the page changed, update $pageObj
89 $pageObj = WikiPage
::factory( $titleObj );
93 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
94 $contentHandler = $pageObj->getContentHandler();
96 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
99 if ( $contentHandler->supportsDirectApiEditing() === false ) {
101 'Direct editing via API is not supported for this content type.',
106 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
107 $params['contentformat'] = $contentHandler->getDefaultFormat();
110 $contentFormat = $params['contentformat'];
112 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
113 $name = $titleObj->getPrefixedDBkey();
114 $model = $contentHandler->getModelID();
116 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
117 " $model used by $name", 'badformat' );
120 if ( $params['createonly'] && $titleObj->exists() ) {
121 $this->dieUsageMsg( 'createonly-exists' );
123 if ( $params['nocreate'] && !$titleObj->exists() ) {
124 $this->dieUsageMsg( 'nocreate-missing' );
127 // Now let's check whether we're even allowed to do this
128 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
129 if ( !$titleObj->exists() ) {
130 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
132 if ( count( $errors ) ) {
133 $this->dieUsageMsg( $errors[0] );
136 $toMD5 = $params['text'];
137 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
138 $content = $pageObj->getContent();
141 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
142 # If this is a MediaWiki:x message, then load the messages
143 # and return the message value for x.
144 $text = $titleObj->getDefaultMessageText();
145 if ( $text === false ) {
150 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
151 } catch ( MWContentSerializationException
$ex ) {
152 $this->dieUsage( $ex->getMessage(), 'parseerror' );
157 # Otherwise, make a new empty content.
158 $content = $contentHandler->makeEmptyContent();
162 // @todo Add support for appending/prepending to the Content interface
164 if ( !( $content instanceof TextContent
) ) {
165 $mode = $contentHandler->getModelID();
166 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
169 if ( !is_null( $params['section'] ) ) {
170 if ( !$contentHandler->supportsSections() ) {
171 $modelName = $contentHandler->getModelID();
173 "Sections are not supported for this content model: $modelName.",
174 'sectionsnotsupported'
178 if ( $params['section'] == 'new' ) {
179 // DWIM if they're trying to prepend/append to a new section.
182 // Process the content for section edits
183 $section = $params['section'];
184 $content = $content->getSection( $section );
187 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
195 $text = $content->serialize( $contentFormat );
198 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
199 $toMD5 = $params['prependtext'] . $params['appendtext'];
202 if ( $params['undo'] > 0 ) {
203 if ( $params['undoafter'] > 0 ) {
204 if ( $params['undo'] < $params['undoafter'] ) {
205 list( $params['undo'], $params['undoafter'] ) =
206 array( $params['undoafter'], $params['undo'] );
208 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
210 $undoRev = Revision
::newFromId( $params['undo'] );
211 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
212 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
215 if ( $params['undoafter'] == 0 ) {
216 $undoafterRev = $undoRev->getPrevious();
218 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
219 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
222 if ( $undoRev->getPage() != $pageObj->getID() ) {
223 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
224 $titleObj->getPrefixedText() ) );
226 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
227 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
228 $titleObj->getPrefixedText() ) );
231 $newContent = $contentHandler->getUndoContent(
232 $pageObj->getRevision(),
237 if ( !$newContent ) {
238 $this->dieUsageMsg( 'undo-failure' );
241 $params['text'] = $newContent->serialize( $params['contentformat'] );
243 // If no summary was given and we only undid one rev,
244 // use an autosummary
245 if ( is_null( $params['summary'] ) &&
246 $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo']
248 $params['summary'] = wfMessage( 'undo-summary' )
249 ->params ( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
253 // See if the MD5 hash checks out
254 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
255 $this->dieUsageMsg( 'hashcheckfailed' );
258 // EditPage wants to parse its stuff from a WebRequest
259 // That interface kind of sucks, but it's workable
260 $requestArray = array(
261 'wpTextbox1' => $params['text'],
262 'format' => $contentFormat,
263 'model' => $contentHandler->getModelID(),
264 'wpEditToken' => $params['token'],
265 'wpIgnoreBlankSummary' => true,
266 'wpIgnoreBlankArticle' => true,
267 'wpIgnoreSelfRedirect' => true,
268 'bot' => $params['bot'],
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->dieUsage( "The section parameter must be a valid section id or 'new'",
312 $content = $pageObj->getContent();
313 if ( $section !== '0' && $section != 'new'
314 && ( !$content ||
!$content->getSection( $section ) )
316 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
318 $requestArray['wpSection'] = $params['section'];
320 $requestArray['wpSection'] = '';
323 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
325 // Deprecated parameters
326 if ( $params['watch'] ) {
327 $this->logFeatureUsage( 'action=edit&watch' );
329 } elseif ( $params['unwatch'] ) {
330 $this->logFeatureUsage( 'action=edit&unwatch' );
335 $requestArray['wpWatchthis'] = '';
339 if ( count( $params['tags'] ) ) {
340 if ( $user->isAllowed( 'applychangetags' ) ) {
341 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
343 $this->dieUsage( 'You don\'t have permission to set change tags.', 'taggingnotallowed' );
347 // Pass through anything else we might have been given, to support extensions
348 // This is kind of a hack but it's the best we can do to make extensions work
349 $requestArray +
= $this->getRequest()->getValues();
351 global $wgTitle, $wgRequest;
353 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
355 // Some functions depend on $wgTitle == $ep->mTitle
356 // TODO: Make them not or check if they still do
357 $wgTitle = $titleObj;
359 $articleContext = new RequestContext
;
360 $articleContext->setRequest( $req );
361 $articleContext->setWikiPage( $pageObj );
362 $articleContext->setUser( $this->getUser() );
364 /** @var $articleObject Article */
365 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
367 $ep = new EditPage( $articleObject );
369 $ep->setApiEditOverride( true );
370 $ep->setContextTitle( $titleObj );
371 $ep->importFormData( $req );
372 $content = $ep->textbox1
;
374 // The following is needed to give the hook the full content of the
375 // new revision rather than just the current section. (Bug 52077)
376 if ( !is_null( $params['section'] ) &&
377 $contentHandler->supportsSections() && $titleObj->exists()
379 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
380 // backwards compatibility with old forms/bots).
381 if ( $ep->sectiontitle
!== '' ) {
382 $sectionTitle = $ep->sectiontitle
;
384 $sectionTitle = $ep->summary
;
387 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
389 $fullContentObj = $articleObject->replaceSectionContent(
394 if ( $fullContentObj ) {
395 $content = $fullContentObj->serialize( $contentFormat );
397 // This most likely means we have an edit conflict which means that the edit
398 // wont succeed anyway.
399 $this->dieUsageMsg( 'editconflict' );
404 // Handle APIEditBeforeSave parameters
406 if ( !Hooks
::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
408 $r['result'] = 'Failure';
409 $apiResult->addValue( null, $this->getModuleName(), $r );
414 $this->dieUsageMsg( 'hookaborted' );
417 // Do the actual save
418 $oldRevId = $articleObject->getRevIdFetched();
420 // Fake $wgRequest for some hooks inside EditPage
421 // @todo FIXME: This interface SUCKS
422 $oldRequest = $wgRequest;
425 $status = $ep->attemptSave( $result );
426 $wgRequest = $oldRequest;
428 switch ( $status->value
) {
429 case EditPage
::AS_HOOK_ERROR
:
430 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
431 if ( isset( $status->apiHookResult
) ) {
432 $r = $status->apiHookResult
;
433 $r['result'] = 'Failure';
434 $apiResult->addValue( null, $this->getModuleName(), $r );
437 $this->dieUsageMsg( 'hookaborted' );
440 case EditPage
::AS_PARSE_ERROR
:
441 $this->dieUsage( $status->getMessage(), 'parseerror' );
443 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
444 $this->dieUsageMsg( 'noimageredirect-anon' );
446 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
447 $this->dieUsageMsg( 'noimageredirect-logged' );
449 case EditPage
::AS_SPAM_ERROR
:
450 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
452 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
453 $this->dieUsageMsg( 'blockedtext' );
455 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
456 case EditPage
::AS_CONTENT_TOO_BIG
:
457 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
459 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
460 $this->dieUsageMsg( 'noedit-anon' );
462 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
463 $this->dieUsageMsg( 'noedit' );
465 case EditPage
::AS_READ_ONLY_PAGE
:
466 $this->dieReadOnly();
468 case EditPage
::AS_RATE_LIMITED
:
469 $this->dieUsageMsg( 'actionthrottledtext' );
471 case EditPage
::AS_ARTICLE_WAS_DELETED
:
472 $this->dieUsageMsg( 'wasdeleted' );
474 case EditPage
::AS_NO_CREATE_PERMISSION
:
475 $this->dieUsageMsg( 'nocreate-loggedin' );
477 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
478 $this->dieUsageMsg( 'cantchangecontentmodel' );
480 case EditPage
::AS_BLANK_ARTICLE
:
481 $this->dieUsageMsg( 'blankpage' );
483 case EditPage
::AS_CONFLICT_DETECTED
:
484 $this->dieUsageMsg( 'editconflict' );
486 case EditPage
::AS_TEXTBOX_EMPTY
:
487 $this->dieUsageMsg( 'emptynewsection' );
489 case EditPage
::AS_CHANGE_TAG_ERROR
:
490 $this->dieStatus( $status );
492 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
496 case EditPage
::AS_SUCCESS_UPDATE
:
497 $r['result'] = 'Success';
498 $r['pageid'] = intval( $titleObj->getArticleID() );
499 $r['title'] = $titleObj->getPrefixedText();
500 $r['contentmodel'] = $articleObject->getContentModel();
501 $newRevId = $articleObject->getLatest();
502 if ( $newRevId == $oldRevId ) {
503 $r['nochange'] = true;
505 $r['oldrevid'] = intval( $oldRevId );
506 $r['newrevid'] = intval( $newRevId );
507 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
508 $pageObj->getTimestamp() );
512 case EditPage
::AS_SUMMARY_NEEDED
:
513 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
514 $this->dieUsageMsg( 'summaryrequired' );
516 case EditPage
::AS_END
:
518 // $status came from WikiPage::doEdit()
519 $errors = $status->getErrorsArray();
520 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
523 $apiResult->addValue( null, $this->getModuleName(), $r );
526 public function mustBePosted() {
530 public function isWriteMode() {
534 public function getAllowedParams() {
537 ApiBase
::PARAM_TYPE
=> 'string',
540 ApiBase
::PARAM_TYPE
=> 'integer',
543 'sectiontitle' => array(
544 ApiBase
::PARAM_TYPE
=> 'string',
547 ApiBase
::PARAM_TYPE
=> 'text',
551 ApiBase
::PARAM_TYPE
=> ChangeTags
::listExplicitlyDefinedTags(),
552 ApiBase
::PARAM_ISMULTI
=> true,
557 'basetimestamp' => array(
558 ApiBase
::PARAM_TYPE
=> 'timestamp',
560 'starttimestamp' => array(
561 ApiBase
::PARAM_TYPE
=> 'timestamp',
564 'createonly' => false,
567 ApiBase
::PARAM_DFLT
=> false,
568 ApiBase
::PARAM_DEPRECATED
=> true,
571 ApiBase
::PARAM_DFLT
=> false,
572 ApiBase
::PARAM_DEPRECATED
=> true,
574 'watchlist' => array(
575 ApiBase
::PARAM_DFLT
=> 'preferences',
576 ApiBase
::PARAM_TYPE
=> array(
584 'prependtext' => array(
585 ApiBase
::PARAM_TYPE
=> 'text',
587 'appendtext' => array(
588 ApiBase
::PARAM_TYPE
=> 'text',
591 ApiBase
::PARAM_TYPE
=> 'integer'
593 'undoafter' => array(
594 ApiBase
::PARAM_TYPE
=> 'integer'
597 ApiBase
::PARAM_TYPE
=> 'boolean',
598 ApiBase
::PARAM_DFLT
=> false,
600 'contentformat' => array(
601 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
603 'contentmodel' => array(
604 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
607 // Standard definition automatically inserted
608 ApiBase
::PARAM_HELP_MSG_APPEND
=> array( 'apihelp-edit-param-token' ),
613 public function needsToken() {
617 protected function getExamplesMessages() {
619 'action=edit&title=Test&summary=test%20summary&' .
620 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
621 => 'apihelp-edit-example-edit',
622 'action=edit&title=Test&summary=NOTOC&minor=&' .
623 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
624 => 'apihelp-edit-example-prepend',
625 'action=edit&title=Test&undo=13585&undoafter=13579&' .
626 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
627 => 'apihelp-edit-example-undo',
631 public function getHelpUrls() {
632 return 'https://www.mediawiki.org/wiki/API:Edit';