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 __construct( $query, $moduleName ) {
37 parent
::__construct( $query, $moduleName );
40 public function execute() {
41 $user = $this->getUser();
42 $params = $this->extractRequestParams();
44 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
45 is_null( $params['prependtext'] ) &&
46 $params['undo'] == 0 )
48 $this->dieUsageMsg( 'missingtext' );
51 $pageObj = $this->getTitleOrPageId( $params );
52 $titleObj = $pageObj->getTitle();
53 if ( $titleObj->isExternal() ) {
54 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
57 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
58 $contentHandler = $pageObj->getContentHandler();
60 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
63 // @todo ask handler whether direct editing is supported at all! make allowFlatEdit() method or some such
65 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
66 $params['contentformat'] = $contentHandler->getDefaultFormat();
69 $contentFormat = $params['contentformat'];
71 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
72 $name = $titleObj->getPrefixedDBkey();
73 $model = $contentHandler->getModelID();
75 $this->dieUsage( "The requested format $contentFormat is not supported for content model ".
76 " $model used by $name", 'badformat' );
79 $apiResult = $this->getResult();
81 if ( $params['redirect'] ) {
82 if ( $titleObj->isRedirect() ) {
83 $oldTitle = $titleObj;
85 $titles = Revision
::newFromTitle( $oldTitle )->getContent( Revision
::FOR_THIS_USER
)->getRedirectChain();
86 // array_shift( $titles );
88 $redirValues = array();
89 foreach ( $titles as $id => $newTitle ) {
91 if ( !isset( $titles[ $id - 1 ] ) ) {
92 $titles[ $id - 1 ] = $oldTitle;
95 $redirValues[] = array(
96 'from' => $titles[ $id - 1 ]->getPrefixedText(),
97 'to' => $newTitle->getPrefixedText()
100 $titleObj = $newTitle;
103 $apiResult->setIndexedTagName( $redirValues, 'r' );
104 $apiResult->addValue( null, 'redirects', $redirValues );
108 if ( $params['createonly'] && $titleObj->exists() ) {
109 $this->dieUsageMsg( 'createonly-exists' );
111 if ( $params['nocreate'] && !$titleObj->exists() ) {
112 $this->dieUsageMsg( 'nocreate-missing' );
115 // Now let's check whether we're even allowed to do this
116 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
117 if ( !$titleObj->exists() ) {
118 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
120 if ( count( $errors ) ) {
121 $this->dieUsageMsg( $errors[0] );
124 $toMD5 = $params['text'];
125 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
127 $content = $pageObj->getContent();
129 if ( !( $content instanceof TextContent
) ) {
130 // @todo: ContentHandler should have an isFlat() method or some such
131 // @todo: XXX: or perhaps there should be Content::append(), Content::prepend()
132 // @todo: ...and Content::supportsConcatenation()
133 $mode = $contentHandler->getModelID();
134 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
138 # If this is a MediaWiki:x message, then load the messages
139 # and return the message value for x.
140 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
141 $text = $titleObj->getDefaultMessageText();
142 if ( $text === false ) {
147 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
148 } catch ( MWContentSerializationException
$ex ) {
149 $this->dieUsage( $ex->getMessage(), 'parseerror' );
155 if ( !is_null( $params['section'] ) ) {
156 if ( !$contentHandler->supportsSections() ) {
157 $modelName = $contentHandler->getModelID();
158 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
161 // Process the content for section edits
162 $section = intval( $params['section'] );
163 $content = $content->getSection( $section );
166 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
173 $text = $content->serialize( $contentFormat );
176 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
177 $toMD5 = $params['prependtext'] . $params['appendtext'];
180 if ( $params['undo'] > 0 ) {
181 if ( $params['undoafter'] > 0 ) {
182 if ( $params['undo'] < $params['undoafter'] ) {
183 list( $params['undo'], $params['undoafter'] ) =
184 array( $params['undoafter'], $params['undo'] );
186 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
188 $undoRev = Revision
::newFromID( $params['undo'] );
189 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
190 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
193 if ( $params['undoafter'] == 0 ) {
194 $undoafterRev = $undoRev->getPrevious();
196 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
197 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
200 if ( $undoRev->getPage() != $pageObj->getID() ) {
201 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
203 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
204 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
207 $newContent = $contentHandler->getUndoContent( $pageObj->getRevision(), $undoRev, $undoafterRev );
209 if ( !$newContent ) {
210 $this->dieUsageMsg( 'undo-failure' );
213 $params['text'] = $newContent->serialize( $params['contentformat'] );
215 // If no summary was given and we only undid one rev,
216 // use an autosummary
217 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
218 $params['summary'] = wfMessage( 'undo-summary', $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
222 // See if the MD5 hash checks out
223 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
224 $this->dieUsageMsg( 'hashcheckfailed' );
227 // EditPage wants to parse its stuff from a WebRequest
228 // That interface kind of sucks, but it's workable
229 $requestArray = array(
230 'wpTextbox1' => $params['text'],
231 'format' => $contentFormat,
232 'model' => $contentHandler->getModelID(),
233 'wpEditToken' => $params['token'],
234 'wpIgnoreBlankSummary' => ''
237 if ( !is_null( $params['summary'] ) ) {
238 $requestArray['wpSummary'] = $params['summary'];
241 if ( !is_null( $params['sectiontitle'] ) ) {
242 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
245 // Watch out for basetimestamp == ''
246 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
247 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
248 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
250 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
253 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
254 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
256 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
259 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
260 $requestArray['wpMinoredit'] = '';
263 if ( $params['recreate'] ) {
264 $requestArray['wpRecreate'] = '';
267 if ( !is_null( $params['section'] ) ) {
268 $section = intval( $params['section'] );
269 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
270 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
272 $requestArray['wpSection'] = $params['section'];
274 $requestArray['wpSection'] = '';
277 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
279 // Deprecated parameters
280 if ( $params['watch'] ) {
282 } elseif ( $params['unwatch'] ) {
287 $requestArray['wpWatchthis'] = '';
290 global $wgTitle, $wgRequest;
292 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
294 // Some functions depend on $wgTitle == $ep->mTitle
295 // TODO: Make them not or check if they still do
296 $wgTitle = $titleObj;
298 $articleObject = new Article( $titleObj );
299 $ep = new EditPage( $articleObject );
301 $ep->setContextTitle( $titleObj );
302 $ep->importFormData( $req );
305 // Handle APIEditBeforeSave parameters
307 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
309 $r['result'] = 'Failure';
310 $apiResult->addValue( null, $this->getModuleName(), $r );
313 $this->dieUsageMsg( 'hookaborted' );
317 // Do the actual save
318 $oldRevId = $articleObject->getRevIdFetched();
320 // Fake $wgRequest for some hooks inside EditPage
321 // @todo FIXME: This interface SUCKS
322 $oldRequest = $wgRequest;
325 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
326 $wgRequest = $oldRequest;
327 global $wgMaxArticleSize;
329 switch( $status->value
) {
330 case EditPage
::AS_HOOK_ERROR
:
331 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
332 $this->dieUsageMsg( 'hookaborted' );
334 case EditPage
::AS_PARSE_ERROR
:
335 $this->dieUsage( $status->getMessage(), 'parseerror' );
337 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
338 $this->dieUsageMsg( 'noimageredirect-anon' );
340 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
341 $this->dieUsageMsg( 'noimageredirect-logged' );
343 case EditPage
::AS_SPAM_ERROR
:
344 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
346 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
347 $this->dieUsageMsg( 'blockedtext' );
349 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
350 case EditPage
::AS_CONTENT_TOO_BIG
:
351 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
353 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
354 $this->dieUsageMsg( 'noedit-anon' );
356 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
357 $this->dieUsageMsg( 'noedit' );
359 case EditPage
::AS_READ_ONLY_PAGE
:
360 $this->dieReadOnly();
362 case EditPage
::AS_RATE_LIMITED
:
363 $this->dieUsageMsg( 'actionthrottledtext' );
365 case EditPage
::AS_ARTICLE_WAS_DELETED
:
366 $this->dieUsageMsg( 'wasdeleted' );
368 case EditPage
::AS_NO_CREATE_PERMISSION
:
369 $this->dieUsageMsg( 'nocreate-loggedin' );
371 case EditPage
::AS_BLANK_ARTICLE
:
372 $this->dieUsageMsg( 'blankpage' );
374 case EditPage
::AS_CONFLICT_DETECTED
:
375 $this->dieUsageMsg( 'editconflict' );
377 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
378 case EditPage
::AS_TEXTBOX_EMPTY
:
379 $this->dieUsageMsg( 'emptynewsection' );
381 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
384 case EditPage
::AS_SUCCESS_UPDATE
:
385 $r['result'] = 'Success';
386 $r['pageid'] = intval( $titleObj->getArticleID() );
387 $r['title'] = $titleObj->getPrefixedText();
388 $r['contentmodel'] = $titleObj->getContentModel();
389 $newRevId = $articleObject->getLatest();
390 if ( $newRevId == $oldRevId ) {
393 $r['oldrevid'] = intval( $oldRevId );
394 $r['newrevid'] = intval( $newRevId );
395 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
396 $pageObj->getTimestamp() );
400 case EditPage
::AS_SUMMARY_NEEDED
:
401 $this->dieUsageMsg( 'summaryrequired' );
403 case EditPage
::AS_END
:
405 // $status came from WikiPage::doEdit()
406 $errors = $status->getErrorsArray();
407 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
410 $apiResult->addValue( null, $this->getModuleName(), $r );
413 public function mustBePosted() {
417 public function isWriteMode() {
421 public function getDescription() {
422 return 'Create and edit pages.';
425 public function getPossibleErrors() {
426 global $wgMaxArticleSize;
428 return array_merge( parent
::getPossibleErrors(),
429 $this->getTitleOrPageIdErrorMessage(),
431 array( 'missingtext' ),
432 array( 'createonly-exists' ),
433 array( 'nocreate-missing' ),
434 array( 'nosuchrevid', 'undo' ),
435 array( 'nosuchrevid', 'undoafter' ),
436 array( 'revwrongpage', 'id', 'text' ),
437 array( 'undo-failure' ),
438 array( 'hashcheckfailed' ),
439 array( 'hookaborted' ),
440 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
441 array( 'noimageredirect-anon' ),
442 array( 'noimageredirect-logged' ),
443 array( 'spamdetected', 'spam' ),
444 array( 'summaryrequired' ),
445 array( 'blockedtext' ),
446 array( 'contenttoobig', $wgMaxArticleSize ),
447 array( 'noedit-anon' ),
449 array( 'actionthrottledtext' ),
450 array( 'wasdeleted' ),
451 array( 'nocreate-loggedin' ),
452 array( 'blankpage' ),
453 array( 'editconflict' ),
454 array( 'emptynewsection' ),
455 array( 'unknownerror', 'retval' ),
456 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
457 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
458 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
459 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using '
460 . 'the text based edit API.' ),
461 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending '
462 . 'or prepending text.' ),
463 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to '
464 . 'the page\'s content model' ),
465 array( 'customcssprotected' ),
466 array( 'customjsprotected' ),
471 public function getAllowedParams() {
474 ApiBase
::PARAM_TYPE
=> 'string',
477 ApiBase
::PARAM_TYPE
=> 'integer',
480 'sectiontitle' => array(
481 ApiBase
::PARAM_TYPE
=> 'string',
482 ApiBase
::PARAM_REQUIRED
=> false,
486 ApiBase
::PARAM_TYPE
=> 'string',
487 ApiBase
::PARAM_REQUIRED
=> true
493 'basetimestamp' => null,
494 'starttimestamp' => null,
496 'createonly' => false,
499 ApiBase
::PARAM_DFLT
=> false,
500 ApiBase
::PARAM_DEPRECATED
=> true,
503 ApiBase
::PARAM_DFLT
=> false,
504 ApiBase
::PARAM_DEPRECATED
=> true,
506 'watchlist' => array(
507 ApiBase
::PARAM_DFLT
=> 'preferences',
508 ApiBase
::PARAM_TYPE
=> array(
516 'prependtext' => null,
517 'appendtext' => null,
519 ApiBase
::PARAM_TYPE
=> 'integer'
521 'undoafter' => array(
522 ApiBase
::PARAM_TYPE
=> 'integer'
525 ApiBase
::PARAM_TYPE
=> 'boolean',
526 ApiBase
::PARAM_DFLT
=> false,
528 'contentformat' => array(
529 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
531 'contentmodel' => array(
532 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
537 public function getParamDescription() {
538 $p = $this->getModulePrefix();
540 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
541 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
542 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
543 'sectiontitle' => 'The title for a new section',
544 'text' => 'Page content',
545 'token' => array( 'Edit token. You can get one of these through prop=info.',
546 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
548 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
549 'minor' => 'Minor edit',
550 'notminor' => 'Non-minor edit',
551 'bot' => 'Mark this edit as bot',
552 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
553 'Used to detect edit conflicts; leave unset to ignore conflicts'
555 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
556 'Used to detect edit conflicts; leave unset to ignore conflicts'
558 'recreate' => 'Override any errors about the article having been deleted in the meantime',
559 'createonly' => 'Don\'t edit the page if it exists already',
560 'nocreate' => 'Throw an error if the page doesn\'t exist',
561 'watch' => 'Add the page to your watchlist',
562 'unwatch' => 'Remove the page from your watchlist',
563 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
564 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
565 'If set, the edit won\'t be done unless the hash is correct' ),
566 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
567 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
568 "Use {$p}section=new to append a new section" ),
569 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
570 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
571 'redirect' => 'Automatically resolve redirects',
572 'contentformat' => 'Content serialization format used for the input text',
573 'contentmodel' => 'Content model of the new content',
577 public function getResultProperties() {
582 ApiBase
::PROP_TYPE
=> array(
588 ApiBase
::PROP_TYPE
=> 'integer',
589 ApiBase
::PROP_NULLABLE
=> true
592 ApiBase
::PROP_TYPE
=> 'string',
593 ApiBase
::PROP_NULLABLE
=> true
595 'nochange' => 'boolean',
597 ApiBase
::PROP_TYPE
=> 'integer',
598 ApiBase
::PROP_NULLABLE
=> true
601 ApiBase
::PROP_TYPE
=> 'integer',
602 ApiBase
::PROP_NULLABLE
=> true
604 'newtimestamp' => array(
605 ApiBase
::PROP_TYPE
=> 'string',
606 ApiBase
::PROP_NULLABLE
=> true
612 public function needsToken() {
616 public function getTokenSalt() {
620 public function getExamples() {
623 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
624 => 'Edit a page (anonymous user)',
626 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
627 => 'Prepend __NOTOC__ to a page (anonymous user)',
628 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
629 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
633 public function getHelpUrls() {
634 return 'https://www.mediawiki.org/wiki/API:Edit';
637 public function getVersion() {
638 return __CLASS__
. ': $Id$';