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'] = '';
335 if ( count( $params['tags'] ) ) {
336 if ( $user->isAllowed( 'applychangetags' ) ) {
337 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
339 $this->dieUsage( 'You don\'t have permission to set change tags.', 'taggingnotallowed' );
343 // Pass through anything else we might have been given, to support extensions
344 // This is kind of a hack but it's the best we can do to make extensions work
345 $requestArray +
= $this->getRequest()->getValues();
347 global $wgTitle, $wgRequest;
349 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
351 // Some functions depend on $wgTitle == $ep->mTitle
352 // TODO: Make them not or check if they still do
353 $wgTitle = $titleObj;
355 $articleContext = new RequestContext
;
356 $articleContext->setRequest( $req );
357 $articleContext->setWikiPage( $pageObj );
358 $articleContext->setUser( $this->getUser() );
360 /** @var $articleObject Article */
361 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
363 $ep = new EditPage( $articleObject );
365 // allow editing of non-textual content.
366 $ep->allowNonTextContent
= true;
368 $ep->setContextTitle( $titleObj );
369 $ep->importFormData( $req );
370 $content = $ep->textbox1
;
372 // The following is needed to give the hook the full content of the
373 // new revision rather than just the current section. (Bug 52077)
374 if ( !is_null( $params['section'] ) &&
375 $contentHandler->supportsSections() && $titleObj->exists()
377 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
378 // backwards compatibility with old forms/bots).
379 if ( $ep->sectiontitle
!== '' ) {
380 $sectionTitle = $ep->sectiontitle
;
382 $sectionTitle = $ep->summary
;
385 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
387 $fullContentObj = $articleObject->replaceSectionContent(
392 if ( $fullContentObj ) {
393 $content = $fullContentObj->serialize( $contentFormat );
395 // This most likely means we have an edit conflict which means that the edit
396 // wont succeed anyway.
397 $this->dieUsageMsg( 'editconflict' );
402 // Handle APIEditBeforeSave parameters
404 if ( !Hooks
::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
406 $r['result'] = 'Failure';
407 $apiResult->addValue( null, $this->getModuleName(), $r );
412 $this->dieUsageMsg( 'hookaborted' );
415 // Do the actual save
416 $oldRevId = $articleObject->getRevIdFetched();
418 // Fake $wgRequest for some hooks inside EditPage
419 // @todo FIXME: This interface SUCKS
420 $oldRequest = $wgRequest;
423 $status = $ep->attemptSave( $result );
424 $wgRequest = $oldRequest;
426 switch ( $status->value
) {
427 case EditPage
::AS_HOOK_ERROR
:
428 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
429 if ( isset( $status->apiHookResult
) ) {
430 $r = $status->apiHookResult
;
431 $r['result'] = 'Failure';
432 $apiResult->addValue( null, $this->getModuleName(), $r );
435 $this->dieUsageMsg( 'hookaborted' );
438 case EditPage
::AS_PARSE_ERROR
:
439 $this->dieUsage( $status->getMessage(), 'parseerror' );
441 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
442 $this->dieUsageMsg( 'noimageredirect-anon' );
444 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
445 $this->dieUsageMsg( 'noimageredirect-logged' );
447 case EditPage
::AS_SPAM_ERROR
:
448 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
450 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
451 $this->dieUsageMsg( 'blockedtext' );
453 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
454 case EditPage
::AS_CONTENT_TOO_BIG
:
455 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
457 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
458 $this->dieUsageMsg( 'noedit-anon' );
460 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
461 $this->dieUsageMsg( 'noedit' );
463 case EditPage
::AS_READ_ONLY_PAGE
:
464 $this->dieReadOnly();
466 case EditPage
::AS_RATE_LIMITED
:
467 $this->dieUsageMsg( 'actionthrottledtext' );
469 case EditPage
::AS_ARTICLE_WAS_DELETED
:
470 $this->dieUsageMsg( 'wasdeleted' );
472 case EditPage
::AS_NO_CREATE_PERMISSION
:
473 $this->dieUsageMsg( 'nocreate-loggedin' );
475 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
476 $this->dieUsageMsg( 'cantchangecontentmodel' );
478 case EditPage
::AS_BLANK_ARTICLE
:
479 $this->dieUsageMsg( 'blankpage' );
481 case EditPage
::AS_CONFLICT_DETECTED
:
482 $this->dieUsageMsg( 'editconflict' );
484 case EditPage
::AS_TEXTBOX_EMPTY
:
485 $this->dieUsageMsg( 'emptynewsection' );
487 case EditPage
::AS_CHANGE_TAG_ERROR
:
488 $this->dieStatus( $status );
490 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
494 case EditPage
::AS_SUCCESS_UPDATE
:
495 $r['result'] = 'Success';
496 $r['pageid'] = intval( $titleObj->getArticleID() );
497 $r['title'] = $titleObj->getPrefixedText();
498 $r['contentmodel'] = $titleObj->getContentModel();
499 $newRevId = $articleObject->getLatest();
500 if ( $newRevId == $oldRevId ) {
503 $r['oldrevid'] = intval( $oldRevId );
504 $r['newrevid'] = intval( $newRevId );
505 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
506 $pageObj->getTimestamp() );
510 case EditPage
::AS_SUMMARY_NEEDED
:
511 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
512 $this->dieUsageMsg( 'summaryrequired' );
514 case EditPage
::AS_END
:
516 // $status came from WikiPage::doEdit()
517 $errors = $status->getErrorsArray();
518 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
521 $apiResult->addValue( null, $this->getModuleName(), $r );
524 public function mustBePosted() {
528 public function isWriteMode() {
532 public function getAllowedParams() {
535 ApiBase
::PARAM_TYPE
=> 'string',
538 ApiBase
::PARAM_TYPE
=> 'integer',
541 'sectiontitle' => array(
542 ApiBase
::PARAM_TYPE
=> 'string',
547 ApiBase
::PARAM_TYPE
=> ChangeTags
::listExplicitlyDefinedTags(),
548 ApiBase
::PARAM_ISMULTI
=> true,
553 'basetimestamp' => null,
554 'starttimestamp' => null,
556 'createonly' => false,
559 ApiBase
::PARAM_DFLT
=> false,
560 ApiBase
::PARAM_DEPRECATED
=> true,
563 ApiBase
::PARAM_DFLT
=> false,
564 ApiBase
::PARAM_DEPRECATED
=> true,
566 'watchlist' => array(
567 ApiBase
::PARAM_DFLT
=> 'preferences',
568 ApiBase
::PARAM_TYPE
=> array(
576 'prependtext' => null,
577 'appendtext' => null,
579 ApiBase
::PARAM_TYPE
=> 'integer'
581 'undoafter' => array(
582 ApiBase
::PARAM_TYPE
=> 'integer'
585 ApiBase
::PARAM_TYPE
=> 'boolean',
586 ApiBase
::PARAM_DFLT
=> false,
588 'contentformat' => array(
589 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
591 'contentmodel' => array(
592 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
595 // Standard definition automatically inserted
596 ApiBase
::PARAM_HELP_MSG_APPEND
=> array( 'apihelp-edit-param-token' ),
601 public function needsToken() {
605 protected function getExamplesMessages() {
607 'action=edit&title=Test&summary=test%20summary&' .
608 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
609 => 'apihelp-edit-example-edit',
610 'action=edit&title=Test&summary=NOTOC&minor=&' .
611 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
612 => 'apihelp-edit-example-prepend',
613 'action=edit&title=Test&undo=13585&undoafter=13579&' .
614 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
615 => 'apihelp-edit-example-undo',
619 public function getHelpUrls() {
620 return 'https://www.mediawiki.org/wiki/API:Edit';