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 // @todo Ask handler whether direct editing is supported at all! make
100 // allowFlatEdit() method or some such
102 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
103 $params['contentformat'] = $contentHandler->getDefaultFormat();
106 $contentFormat = $params['contentformat'];
108 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
109 $name = $titleObj->getPrefixedDBkey();
110 $model = $contentHandler->getModelID();
112 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
113 " $model used by $name", 'badformat' );
116 if ( $params['createonly'] && $titleObj->exists() ) {
117 $this->dieUsageMsg( 'createonly-exists' );
119 if ( $params['nocreate'] && !$titleObj->exists() ) {
120 $this->dieUsageMsg( 'nocreate-missing' );
123 // Now let's check whether we're even allowed to do this
124 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
125 if ( !$titleObj->exists() ) {
126 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
128 if ( count( $errors ) ) {
129 $this->dieUsageMsg( $errors[0] );
132 $toMD5 = $params['text'];
133 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
134 $content = $pageObj->getContent();
137 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
138 # If this is a MediaWiki:x message, then load the messages
139 # and return the message value for x.
140 $text = $titleObj->getDefaultMessageText();
141 if ( $text === false ) {
146 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
147 } catch ( MWContentSerializationException
$ex ) {
148 $this->dieUsage( $ex->getMessage(), 'parseerror' );
153 # Otherwise, make a new empty content.
154 $content = $contentHandler->makeEmptyContent();
158 // @todo Add support for appending/prepending to the Content interface
160 if ( !( $content instanceof TextContent
) ) {
161 $mode = $contentHandler->getModelID();
162 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
165 if ( !is_null( $params['section'] ) ) {
166 if ( !$contentHandler->supportsSections() ) {
167 $modelName = $contentHandler->getModelID();
169 "Sections are not supported for this content model: $modelName.",
170 'sectionsnotsupported'
174 if ( $params['section'] == 'new' ) {
175 // DWIM if they're trying to prepend/append to a new section.
178 // Process the content for section edits
179 $section = $params['section'];
180 $content = $content->getSection( $section );
183 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
191 $text = $content->serialize( $contentFormat );
194 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
195 $toMD5 = $params['prependtext'] . $params['appendtext'];
198 if ( $params['undo'] > 0 ) {
199 if ( $params['undoafter'] > 0 ) {
200 if ( $params['undo'] < $params['undoafter'] ) {
201 list( $params['undo'], $params['undoafter'] ) =
202 array( $params['undoafter'], $params['undo'] );
204 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
206 $undoRev = Revision
::newFromId( $params['undo'] );
207 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
208 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
211 if ( $params['undoafter'] == 0 ) {
212 $undoafterRev = $undoRev->getPrevious();
214 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
215 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
218 if ( $undoRev->getPage() != $pageObj->getID() ) {
219 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
220 $titleObj->getPrefixedText() ) );
222 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
223 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
224 $titleObj->getPrefixedText() ) );
227 $newContent = $contentHandler->getUndoContent(
228 $pageObj->getRevision(),
233 if ( !$newContent ) {
234 $this->dieUsageMsg( 'undo-failure' );
237 $params['text'] = $newContent->serialize( $params['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->dieUsageMsg( 'hashcheckfailed' );
254 // EditPage wants to parse its stuff from a WebRequest
255 // That interface kind of sucks, but it's workable
256 $requestArray = array(
257 'wpTextbox1' => $params['text'],
258 'format' => $contentFormat,
259 'model' => $contentHandler->getModelID(),
260 'wpEditToken' => $params['token'],
261 'wpIgnoreBlankSummary' => true,
262 'wpIgnoreBlankArticle' => true,
263 'wpIgnoreSelfRedirect' => true,
264 'bot' => $params['bot'],
267 if ( !is_null( $params['summary'] ) ) {
268 $requestArray['wpSummary'] = $params['summary'];
271 if ( !is_null( $params['sectiontitle'] ) ) {
272 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
275 // TODO: Pass along information from 'undoafter' as well
276 if ( $params['undo'] > 0 ) {
277 $requestArray['wpUndidRevision'] = $params['undo'];
280 // Watch out for basetimestamp == ''
281 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
282 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
283 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
285 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
288 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
289 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
291 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
294 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
295 $requestArray['wpMinoredit'] = '';
298 if ( $params['recreate'] ) {
299 $requestArray['wpRecreate'] = '';
302 if ( !is_null( $params['section'] ) ) {
303 $section = $params['section'];
304 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
305 $this->dieUsage( "The section parameter must be a valid section id or 'new'",
308 $content = $pageObj->getContent();
309 if ( $section !== '0' && $section != 'new'
310 && ( !$content ||
!$content->getSection( $section ) )
312 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
314 $requestArray['wpSection'] = $params['section'];
316 $requestArray['wpSection'] = '';
319 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
321 // Deprecated parameters
322 if ( $params['watch'] ) {
323 $this->logFeatureUsage( 'action=edit&watch' );
325 } elseif ( $params['unwatch'] ) {
326 $this->logFeatureUsage( 'action=edit&unwatch' );
331 $requestArray['wpWatchthis'] = '';
334 // Pass through anything else we might have been given, to support extensions
335 // This is kind of a hack but it's the best we can do to make extensions work
336 $requestArray +
= $this->getRequest()->getValues();
338 global $wgTitle, $wgRequest;
340 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
342 // Some functions depend on $wgTitle == $ep->mTitle
343 // TODO: Make them not or check if they still do
344 $wgTitle = $titleObj;
346 $articleContext = new RequestContext
;
347 $articleContext->setRequest( $req );
348 $articleContext->setWikiPage( $pageObj );
349 $articleContext->setUser( $this->getUser() );
351 /** @var $articleObject Article */
352 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
354 $ep = new EditPage( $articleObject );
356 // allow editing of non-textual content.
357 $ep->allowNonTextContent
= true;
359 $ep->setContextTitle( $titleObj );
360 $ep->importFormData( $req );
361 $content = $ep->textbox1
;
363 // The following is needed to give the hook the full content of the
364 // new revision rather than just the current section. (Bug 52077)
365 if ( !is_null( $params['section'] ) &&
366 $contentHandler->supportsSections() && $titleObj->exists()
368 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
369 // backwards compatibility with old forms/bots).
370 if ( $ep->sectiontitle
!== '' ) {
371 $sectionTitle = $ep->sectiontitle
;
373 $sectionTitle = $ep->summary
;
376 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
378 $fullContentObj = $articleObject->replaceSectionContent(
383 if ( $fullContentObj ) {
384 $content = $fullContentObj->serialize( $contentFormat );
386 // This most likely means we have an edit conflict which means that the edit
387 // wont succeed anyway.
388 $this->dieUsageMsg( 'editconflict' );
393 // Handle APIEditBeforeSave parameters
395 if ( !Hooks
::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
397 $r['result'] = 'Failure';
398 $apiResult->addValue( null, $this->getModuleName(), $r );
403 $this->dieUsageMsg( 'hookaborted' );
406 // Do the actual save
407 $oldRevId = $articleObject->getRevIdFetched();
409 // Fake $wgRequest for some hooks inside EditPage
410 // @todo FIXME: This interface SUCKS
411 $oldRequest = $wgRequest;
414 $status = $ep->attemptSave( $result );
415 $wgRequest = $oldRequest;
417 switch ( $status->value
) {
418 case EditPage
::AS_HOOK_ERROR
:
419 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
420 if ( isset( $status->apiHookResult
) ) {
421 $r = $status->apiHookResult
;
422 $r['result'] = 'Failure';
423 $apiResult->addValue( null, $this->getModuleName(), $r );
426 $this->dieUsageMsg( 'hookaborted' );
429 case EditPage
::AS_PARSE_ERROR
:
430 $this->dieUsage( $status->getMessage(), 'parseerror' );
432 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
433 $this->dieUsageMsg( 'noimageredirect-anon' );
435 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
436 $this->dieUsageMsg( 'noimageredirect-logged' );
438 case EditPage
::AS_SPAM_ERROR
:
439 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
441 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
442 $this->dieUsageMsg( 'blockedtext' );
444 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
445 case EditPage
::AS_CONTENT_TOO_BIG
:
446 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
448 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
449 $this->dieUsageMsg( 'noedit-anon' );
451 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
452 $this->dieUsageMsg( 'noedit' );
454 case EditPage
::AS_READ_ONLY_PAGE
:
455 $this->dieReadOnly();
457 case EditPage
::AS_RATE_LIMITED
:
458 $this->dieUsageMsg( 'actionthrottledtext' );
460 case EditPage
::AS_ARTICLE_WAS_DELETED
:
461 $this->dieUsageMsg( 'wasdeleted' );
463 case EditPage
::AS_NO_CREATE_PERMISSION
:
464 $this->dieUsageMsg( 'nocreate-loggedin' );
466 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
467 $this->dieUsageMsg( 'cantchangecontentmodel' );
469 case EditPage
::AS_BLANK_ARTICLE
:
470 $this->dieUsageMsg( 'blankpage' );
472 case EditPage
::AS_CONFLICT_DETECTED
:
473 $this->dieUsageMsg( 'editconflict' );
475 case EditPage
::AS_TEXTBOX_EMPTY
:
476 $this->dieUsageMsg( 'emptynewsection' );
478 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
482 case EditPage
::AS_SUCCESS_UPDATE
:
483 $r['result'] = 'Success';
484 $r['pageid'] = intval( $titleObj->getArticleID() );
485 $r['title'] = $titleObj->getPrefixedText();
486 $r['contentmodel'] = $titleObj->getContentModel();
487 $newRevId = $articleObject->getLatest();
488 if ( $newRevId == $oldRevId ) {
491 $r['oldrevid'] = intval( $oldRevId );
492 $r['newrevid'] = intval( $newRevId );
493 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
494 $pageObj->getTimestamp() );
498 case EditPage
::AS_SUMMARY_NEEDED
:
499 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
500 $this->dieUsageMsg( 'summaryrequired' );
502 case EditPage
::AS_END
:
504 // $status came from WikiPage::doEdit()
505 $errors = $status->getErrorsArray();
506 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
509 $apiResult->addValue( null, $this->getModuleName(), $r );
512 public function mustBePosted() {
516 public function isWriteMode() {
520 public function getAllowedParams() {
523 ApiBase
::PARAM_TYPE
=> 'string',
526 ApiBase
::PARAM_TYPE
=> 'integer',
529 'sectiontitle' => array(
530 ApiBase
::PARAM_TYPE
=> 'string',
537 'basetimestamp' => null,
538 'starttimestamp' => null,
540 'createonly' => false,
543 ApiBase
::PARAM_DFLT
=> false,
544 ApiBase
::PARAM_DEPRECATED
=> true,
547 ApiBase
::PARAM_DFLT
=> false,
548 ApiBase
::PARAM_DEPRECATED
=> true,
550 'watchlist' => array(
551 ApiBase
::PARAM_DFLT
=> 'preferences',
552 ApiBase
::PARAM_TYPE
=> array(
560 'prependtext' => null,
561 'appendtext' => null,
563 ApiBase
::PARAM_TYPE
=> 'integer'
565 'undoafter' => array(
566 ApiBase
::PARAM_TYPE
=> 'integer'
569 ApiBase
::PARAM_TYPE
=> 'boolean',
570 ApiBase
::PARAM_DFLT
=> false,
572 'contentformat' => array(
573 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
575 'contentmodel' => array(
576 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
579 // Standard definition automatically inserted
580 ApiBase
::PARAM_HELP_MSG_APPEND
=> array( 'apihelp-edit-param-token' ),
585 public function needsToken() {
589 protected function getExamplesMessages() {
591 'action=edit&title=Test&summary=test%20summary&' .
592 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
593 => 'apihelp-edit-example-edit',
594 'action=edit&title=Test&summary=NOTOC&minor=&' .
595 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
596 => 'apihelp-edit-example-prepend',
597 'action=edit&title=Test&undo=13585&undoafter=13579&' .
598 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
599 => 'apihelp-edit-example-undo',
603 public function getHelpUrls() {
604 return 'https://www.mediawiki.org/wiki/API:Edit';