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
34 class ApiEditPage
extends ApiBase
{
36 public function execute() {
37 $user = $this->getUser();
38 $params = $this->extractRequestParams();
40 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
41 is_null( $params['prependtext'] ) &&
42 $params['undo'] == 0 )
44 $this->dieUsageMsg( 'missingtext' );
47 $pageObj = $this->getTitleOrPageId( $params );
48 $titleObj = $pageObj->getTitle();
49 $apiResult = $this->getResult();
51 if ( $params['redirect'] ) {
52 if ( $titleObj->isRedirect() ) {
53 $oldTitle = $titleObj;
55 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
56 ->getContent( Revision
::FOR_THIS_USER
, $user )
58 // array_shift( $titles );
60 $redirValues = array();
61 foreach ( $titles as $id => $newTitle ) {
63 if ( !isset( $titles[$id - 1] ) ) {
64 $titles[$id - 1] = $oldTitle;
67 $redirValues[] = array(
68 'from' => $titles[$id - 1]->getPrefixedText(),
69 'to' => $newTitle->getPrefixedText()
72 $titleObj = $newTitle;
75 $apiResult->setIndexedTagName( $redirValues, 'r' );
76 $apiResult->addValue( null, 'redirects', $redirValues );
78 // Since the page changed, update $pageObj
79 $pageObj = WikiPage
::factory( $titleObj );
83 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
84 $contentHandler = $pageObj->getContentHandler();
86 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
89 // @todo ask handler whether direct editing is supported at all! make allowFlatEdit() method or some such
91 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
92 $params['contentformat'] = $contentHandler->getDefaultFormat();
95 $contentFormat = $params['contentformat'];
97 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
98 $name = $titleObj->getPrefixedDBkey();
99 $model = $contentHandler->getModelID();
101 $this->dieUsage( "The requested format $contentFormat is not supported for content model ".
102 " $model used by $name", 'badformat' );
105 if ( $params['createonly'] && $titleObj->exists() ) {
106 $this->dieUsageMsg( 'createonly-exists' );
108 if ( $params['nocreate'] && !$titleObj->exists() ) {
109 $this->dieUsageMsg( 'nocreate-missing' );
112 // Now let's check whether we're even allowed to do this
113 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
114 if ( !$titleObj->exists() ) {
115 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
117 if ( count( $errors ) ) {
118 $this->dieUsageMsg( $errors[0] );
121 $toMD5 = $params['text'];
122 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
124 $content = $pageObj->getContent();
127 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
128 # If this is a MediaWiki:x message, then load the messages
129 # and return the message value for x.
130 $text = $titleObj->getDefaultMessageText();
131 if ( $text === false ) {
136 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
137 } catch ( MWContentSerializationException
$ex ) {
138 $this->dieUsage( $ex->getMessage(), 'parseerror' );
142 # Otherwise, make a new empty content.
143 $content = $contentHandler->makeEmptyContent();
147 // @todo: Add support for appending/prepending to the Content interface
149 if ( !( $content instanceof TextContent
) ) {
150 $mode = $contentHandler->getModelID();
151 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
154 if ( !is_null( $params['section'] ) ) {
155 if ( !$contentHandler->supportsSections() ) {
156 $modelName = $contentHandler->getModelID();
157 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
160 // Process the content for section edits
161 $section = intval( $params['section'] );
162 $content = $content->getSection( $section );
165 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
172 $text = $content->serialize( $contentFormat );
175 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
176 $toMD5 = $params['prependtext'] . $params['appendtext'];
179 if ( $params['undo'] > 0 ) {
180 if ( $params['undoafter'] > 0 ) {
181 if ( $params['undo'] < $params['undoafter'] ) {
182 list( $params['undo'], $params['undoafter'] ) =
183 array( $params['undoafter'], $params['undo'] );
185 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
187 $undoRev = Revision
::newFromID( $params['undo'] );
188 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
189 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
192 if ( $params['undoafter'] == 0 ) {
193 $undoafterRev = $undoRev->getPrevious();
195 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
196 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
199 if ( $undoRev->getPage() != $pageObj->getID() ) {
200 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
202 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
203 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
206 $newContent = $contentHandler->getUndoContent( $pageObj->getRevision(), $undoRev, $undoafterRev );
208 if ( !$newContent ) {
209 $this->dieUsageMsg( 'undo-failure' );
212 $params['text'] = $newContent->serialize( $params['contentformat'] );
214 // If no summary was given and we only undid one rev,
215 // use an autosummary
216 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
217 $params['summary'] = wfMessage( 'undo-summary', $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
221 // See if the MD5 hash checks out
222 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
223 $this->dieUsageMsg( 'hashcheckfailed' );
226 // EditPage wants to parse its stuff from a WebRequest
227 // That interface kind of sucks, but it's workable
228 $requestArray = array(
229 'wpTextbox1' => $params['text'],
230 'format' => $contentFormat,
231 'model' => $contentHandler->getModelID(),
232 'wpEditToken' => $params['token'],
233 'wpIgnoreBlankSummary' => ''
236 if ( !is_null( $params['summary'] ) ) {
237 $requestArray['wpSummary'] = $params['summary'];
240 if ( !is_null( $params['sectiontitle'] ) ) {
241 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
244 // TODO: Pass along information from 'undoafter' as well
245 if ( $params['undo'] > 0 ) {
246 $requestArray['wpUndidRevision'] = $params['undo'];
249 // Watch out for basetimestamp == ''
250 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
251 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
252 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
254 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
257 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
258 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
260 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
263 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
264 $requestArray['wpMinoredit'] = '';
267 if ( $params['recreate'] ) {
268 $requestArray['wpRecreate'] = '';
271 if ( !is_null( $params['section'] ) ) {
272 $section = intval( $params['section'] );
273 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
274 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
276 $requestArray['wpSection'] = $params['section'];
278 $requestArray['wpSection'] = '';
281 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
283 // Deprecated parameters
284 if ( $params['watch'] ) {
286 } elseif ( $params['unwatch'] ) {
291 $requestArray['wpWatchthis'] = '';
294 global $wgTitle, $wgRequest;
296 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
298 // Some functions depend on $wgTitle == $ep->mTitle
299 // TODO: Make them not or check if they still do
300 $wgTitle = $titleObj;
302 $articleContext = new RequestContext
;
303 $articleContext->setRequest( $req );
304 $articleContext->setWikiPage( $pageObj );
305 $articleContext->setUser( $this->getUser() );
307 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
309 $ep = new EditPage( $articleObject );
311 // allow editing of non-textual content.
312 $ep->allowNonTextContent
= true;
314 $ep->setContextTitle( $titleObj );
315 $ep->importFormData( $req );
318 // Handle APIEditBeforeSave parameters
320 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
322 $r['result'] = 'Failure';
323 $apiResult->addValue( null, $this->getModuleName(), $r );
326 $this->dieUsageMsg( 'hookaborted' );
330 // Do the actual save
331 $oldRevId = $articleObject->getRevIdFetched();
333 // Fake $wgRequest for some hooks inside EditPage
334 // @todo FIXME: This interface SUCKS
335 $oldRequest = $wgRequest;
338 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
339 $wgRequest = $oldRequest;
340 global $wgMaxArticleSize;
342 switch( $status->value
) {
343 case EditPage
::AS_HOOK_ERROR
:
344 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
345 $this->dieUsageMsg( 'hookaborted' );
347 case EditPage
::AS_PARSE_ERROR
:
348 $this->dieUsage( $status->getMessage(), 'parseerror' );
350 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
351 $this->dieUsageMsg( 'noimageredirect-anon' );
353 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
354 $this->dieUsageMsg( 'noimageredirect-logged' );
356 case EditPage
::AS_SPAM_ERROR
:
357 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
359 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
360 $this->dieUsageMsg( 'blockedtext' );
362 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
363 case EditPage
::AS_CONTENT_TOO_BIG
:
364 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
366 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
367 $this->dieUsageMsg( 'noedit-anon' );
369 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
370 $this->dieUsageMsg( 'noedit' );
372 case EditPage
::AS_READ_ONLY_PAGE
:
373 $this->dieReadOnly();
375 case EditPage
::AS_RATE_LIMITED
:
376 $this->dieUsageMsg( 'actionthrottledtext' );
378 case EditPage
::AS_ARTICLE_WAS_DELETED
:
379 $this->dieUsageMsg( 'wasdeleted' );
381 case EditPage
::AS_NO_CREATE_PERMISSION
:
382 $this->dieUsageMsg( 'nocreate-loggedin' );
384 case EditPage
::AS_BLANK_ARTICLE
:
385 $this->dieUsageMsg( 'blankpage' );
387 case EditPage
::AS_CONFLICT_DETECTED
:
388 $this->dieUsageMsg( 'editconflict' );
390 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
391 case EditPage
::AS_TEXTBOX_EMPTY
:
392 $this->dieUsageMsg( 'emptynewsection' );
394 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
397 case EditPage
::AS_SUCCESS_UPDATE
:
398 $r['result'] = 'Success';
399 $r['pageid'] = intval( $titleObj->getArticleID() );
400 $r['title'] = $titleObj->getPrefixedText();
401 $r['contentmodel'] = $titleObj->getContentModel();
402 $newRevId = $articleObject->getLatest();
403 if ( $newRevId == $oldRevId ) {
406 $r['oldrevid'] = intval( $oldRevId );
407 $r['newrevid'] = intval( $newRevId );
408 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
409 $pageObj->getTimestamp() );
413 case EditPage
::AS_SUMMARY_NEEDED
:
414 $this->dieUsageMsg( 'summaryrequired' );
416 case EditPage
::AS_END
:
418 // $status came from WikiPage::doEdit()
419 $errors = $status->getErrorsArray();
420 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
423 $apiResult->addValue( null, $this->getModuleName(), $r );
426 public function mustBePosted() {
430 public function isWriteMode() {
434 public function getDescription() {
435 return 'Create and edit pages.';
438 public function getPossibleErrors() {
439 global $wgMaxArticleSize;
441 return array_merge( parent
::getPossibleErrors(),
442 $this->getTitleOrPageIdErrorMessage(),
444 array( 'missingtext' ),
445 array( 'createonly-exists' ),
446 array( 'nocreate-missing' ),
447 array( 'nosuchrevid', 'undo' ),
448 array( 'nosuchrevid', 'undoafter' ),
449 array( 'revwrongpage', 'id', 'text' ),
450 array( 'undo-failure' ),
451 array( 'hashcheckfailed' ),
452 array( 'hookaborted' ),
453 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
454 array( 'noimageredirect-anon' ),
455 array( 'noimageredirect-logged' ),
456 array( 'spamdetected', 'spam' ),
457 array( 'summaryrequired' ),
458 array( 'blockedtext' ),
459 array( 'contenttoobig', $wgMaxArticleSize ),
460 array( 'noedit-anon' ),
462 array( 'actionthrottledtext' ),
463 array( 'wasdeleted' ),
464 array( 'nocreate-loggedin' ),
465 array( 'blankpage' ),
466 array( 'editconflict' ),
467 array( 'emptynewsection' ),
468 array( 'unknownerror', 'retval' ),
469 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
470 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
471 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
472 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using '
473 . 'the text based edit API.' ),
474 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending '
475 . 'or prepending text.' ),
476 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to '
477 . 'the page\'s content model' ),
478 array( 'customcssprotected' ),
479 array( 'customjsprotected' ),
484 public function getAllowedParams() {
487 ApiBase
::PARAM_TYPE
=> 'string',
490 ApiBase
::PARAM_TYPE
=> 'integer',
493 'sectiontitle' => array(
494 ApiBase
::PARAM_TYPE
=> 'string',
495 ApiBase
::PARAM_REQUIRED
=> false,
499 ApiBase
::PARAM_TYPE
=> 'string',
500 ApiBase
::PARAM_REQUIRED
=> true
506 'basetimestamp' => null,
507 'starttimestamp' => null,
509 'createonly' => false,
512 ApiBase
::PARAM_DFLT
=> false,
513 ApiBase
::PARAM_DEPRECATED
=> true,
516 ApiBase
::PARAM_DFLT
=> false,
517 ApiBase
::PARAM_DEPRECATED
=> true,
519 'watchlist' => array(
520 ApiBase
::PARAM_DFLT
=> 'preferences',
521 ApiBase
::PARAM_TYPE
=> array(
529 'prependtext' => null,
530 'appendtext' => null,
532 ApiBase
::PARAM_TYPE
=> 'integer'
534 'undoafter' => array(
535 ApiBase
::PARAM_TYPE
=> 'integer'
538 ApiBase
::PARAM_TYPE
=> 'boolean',
539 ApiBase
::PARAM_DFLT
=> false,
541 'contentformat' => array(
542 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
544 'contentmodel' => array(
545 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
550 public function getParamDescription() {
551 $p = $this->getModulePrefix();
553 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
554 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
555 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
556 'sectiontitle' => 'The title for a new section',
557 'text' => 'Page content',
558 'token' => array( 'Edit token. You can get one of these through prop=info.',
559 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
561 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
562 'minor' => 'Minor edit',
563 'notminor' => 'Non-minor edit',
564 'bot' => 'Mark this edit as bot',
565 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
566 'Used to detect edit conflicts; leave unset to ignore conflicts'
568 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
569 'Used to detect edit conflicts; leave unset to ignore conflicts'
571 'recreate' => 'Override any errors about the article having been deleted in the meantime',
572 'createonly' => 'Don\'t edit the page if it exists already',
573 'nocreate' => 'Throw an error if the page doesn\'t exist',
574 'watch' => 'Add the page to your watchlist',
575 'unwatch' => 'Remove the page from your watchlist',
576 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
577 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
578 'If set, the edit won\'t be done unless the hash is correct' ),
579 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
580 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
581 "Use {$p}section=new to append a new section" ),
582 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
583 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
584 'redirect' => 'Automatically resolve redirects',
585 'contentformat' => 'Content serialization format used for the input text',
586 'contentmodel' => 'Content model of the new content',
590 public function getResultProperties() {
595 ApiBase
::PROP_TYPE
=> array(
601 ApiBase
::PROP_TYPE
=> 'integer',
602 ApiBase
::PROP_NULLABLE
=> true
605 ApiBase
::PROP_TYPE
=> 'string',
606 ApiBase
::PROP_NULLABLE
=> true
608 'nochange' => 'boolean',
610 ApiBase
::PROP_TYPE
=> 'integer',
611 ApiBase
::PROP_NULLABLE
=> true
614 ApiBase
::PROP_TYPE
=> 'integer',
615 ApiBase
::PROP_NULLABLE
=> true
617 'newtimestamp' => array(
618 ApiBase
::PROP_TYPE
=> 'string',
619 ApiBase
::PROP_NULLABLE
=> true
625 public function needsToken() {
629 public function getTokenSalt() {
633 public function getExamples() {
636 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
637 => 'Edit a page (anonymous user)',
639 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
640 => 'Prepend __NOTOC__ to a page (anonymous user)',
641 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
642 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
646 public function getHelpUrls() {
647 return 'https://www.mediawiki.org/wiki/API:Edit';