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, false, Revision
::READ_LATEST
)
86 ->getContent( Revision
::FOR_THIS_USER
, $user )
88 // array_shift( $titles );
90 $redirValues = array();
91 foreach ( $titles as $id => $newTitle ) {
93 if ( !isset( $titles[ $id - 1 ] ) ) {
94 $titles[ $id - 1 ] = $oldTitle;
97 $redirValues[] = array(
98 'from' => $titles[ $id - 1 ]->getPrefixedText(),
99 'to' => $newTitle->getPrefixedText()
102 $titleObj = $newTitle;
105 $apiResult->setIndexedTagName( $redirValues, 'r' );
106 $apiResult->addValue( null, 'redirects', $redirValues );
110 if ( $params['createonly'] && $titleObj->exists() ) {
111 $this->dieUsageMsg( 'createonly-exists' );
113 if ( $params['nocreate'] && !$titleObj->exists() ) {
114 $this->dieUsageMsg( 'nocreate-missing' );
117 // Now let's check whether we're even allowed to do this
118 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
119 if ( !$titleObj->exists() ) {
120 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
122 if ( count( $errors ) ) {
123 $this->dieUsageMsg( $errors[0] );
126 $toMD5 = $params['text'];
127 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
129 $content = $pageObj->getContent();
132 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
133 # If this is a MediaWiki:x message, then load the messages
134 # and return the message value for x.
135 $text = $titleObj->getDefaultMessageText();
136 if ( $text === false ) {
141 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
142 } catch ( MWContentSerializationException
$ex ) {
143 $this->dieUsage( $ex->getMessage(), 'parseerror' );
147 # Otherwise, make a new empty content.
148 $content = $contentHandler->makeEmptyContent();
152 // @todo: Add support for appending/prepending to the Content interface
154 if ( !( $content instanceof TextContent
) ) {
155 $mode = $contentHandler->getModelID();
156 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
159 if ( !is_null( $params['section'] ) ) {
160 if ( !$contentHandler->supportsSections() ) {
161 $modelName = $contentHandler->getModelID();
162 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
165 // Process the content for section edits
166 $section = intval( $params['section'] );
167 $content = $content->getSection( $section );
170 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
177 $text = $content->serialize( $contentFormat );
180 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
181 $toMD5 = $params['prependtext'] . $params['appendtext'];
184 if ( $params['undo'] > 0 ) {
185 if ( $params['undoafter'] > 0 ) {
186 if ( $params['undo'] < $params['undoafter'] ) {
187 list( $params['undo'], $params['undoafter'] ) =
188 array( $params['undoafter'], $params['undo'] );
190 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
192 $undoRev = Revision
::newFromID( $params['undo'] );
193 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
194 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
197 if ( $params['undoafter'] == 0 ) {
198 $undoafterRev = $undoRev->getPrevious();
200 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
201 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
204 if ( $undoRev->getPage() != $pageObj->getID() ) {
205 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
207 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
208 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
211 $newContent = $contentHandler->getUndoContent( $pageObj->getRevision(), $undoRev, $undoafterRev );
213 if ( !$newContent ) {
214 $this->dieUsageMsg( 'undo-failure' );
217 $params['text'] = $newContent->serialize( $params['contentformat'] );
219 // If no summary was given and we only undid one rev,
220 // use an autosummary
221 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
222 $params['summary'] = wfMessage( 'undo-summary', $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
226 // See if the MD5 hash checks out
227 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
228 $this->dieUsageMsg( 'hashcheckfailed' );
231 // EditPage wants to parse its stuff from a WebRequest
232 // That interface kind of sucks, but it's workable
233 $requestArray = array(
234 'wpTextbox1' => $params['text'],
235 'format' => $contentFormat,
236 'model' => $contentHandler->getModelID(),
237 'wpEditToken' => $params['token'],
238 'wpIgnoreBlankSummary' => ''
241 if ( !is_null( $params['summary'] ) ) {
242 $requestArray['wpSummary'] = $params['summary'];
245 if ( !is_null( $params['sectiontitle'] ) ) {
246 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
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 $articleObject = new Article( $titleObj );
303 $ep = new EditPage( $articleObject );
305 // allow editing of non-textual content.
306 $ep->allowNonTextContent
= true;
308 $ep->setContextTitle( $titleObj );
309 $ep->importFormData( $req );
312 // Handle APIEditBeforeSave parameters
314 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
316 $r['result'] = 'Failure';
317 $apiResult->addValue( null, $this->getModuleName(), $r );
320 $this->dieUsageMsg( 'hookaborted' );
324 // Do the actual save
325 $oldRevId = $articleObject->getRevIdFetched();
327 // Fake $wgRequest for some hooks inside EditPage
328 // @todo FIXME: This interface SUCKS
329 $oldRequest = $wgRequest;
332 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
333 $wgRequest = $oldRequest;
334 global $wgMaxArticleSize;
336 switch( $status->value
) {
337 case EditPage
::AS_HOOK_ERROR
:
338 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
339 $this->dieUsageMsg( 'hookaborted' );
341 case EditPage
::AS_PARSE_ERROR
:
342 $this->dieUsage( $status->getMessage(), 'parseerror' );
344 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
345 $this->dieUsageMsg( 'noimageredirect-anon' );
347 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
348 $this->dieUsageMsg( 'noimageredirect-logged' );
350 case EditPage
::AS_SPAM_ERROR
:
351 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
353 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
354 $this->dieUsageMsg( 'blockedtext' );
356 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
357 case EditPage
::AS_CONTENT_TOO_BIG
:
358 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
360 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
361 $this->dieUsageMsg( 'noedit-anon' );
363 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
364 $this->dieUsageMsg( 'noedit' );
366 case EditPage
::AS_READ_ONLY_PAGE
:
367 $this->dieReadOnly();
369 case EditPage
::AS_RATE_LIMITED
:
370 $this->dieUsageMsg( 'actionthrottledtext' );
372 case EditPage
::AS_ARTICLE_WAS_DELETED
:
373 $this->dieUsageMsg( 'wasdeleted' );
375 case EditPage
::AS_NO_CREATE_PERMISSION
:
376 $this->dieUsageMsg( 'nocreate-loggedin' );
378 case EditPage
::AS_BLANK_ARTICLE
:
379 $this->dieUsageMsg( 'blankpage' );
381 case EditPage
::AS_CONFLICT_DETECTED
:
382 $this->dieUsageMsg( 'editconflict' );
384 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
385 case EditPage
::AS_TEXTBOX_EMPTY
:
386 $this->dieUsageMsg( 'emptynewsection' );
388 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
391 case EditPage
::AS_SUCCESS_UPDATE
:
392 $r['result'] = 'Success';
393 $r['pageid'] = intval( $titleObj->getArticleID() );
394 $r['title'] = $titleObj->getPrefixedText();
395 $r['contentmodel'] = $titleObj->getContentModel();
396 $newRevId = $articleObject->getLatest();
397 if ( $newRevId == $oldRevId ) {
400 $r['oldrevid'] = intval( $oldRevId );
401 $r['newrevid'] = intval( $newRevId );
402 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
403 $pageObj->getTimestamp() );
407 case EditPage
::AS_SUMMARY_NEEDED
:
408 $this->dieUsageMsg( 'summaryrequired' );
410 case EditPage
::AS_END
:
412 // $status came from WikiPage::doEdit()
413 $errors = $status->getErrorsArray();
414 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
417 $apiResult->addValue( null, $this->getModuleName(), $r );
420 public function mustBePosted() {
424 public function isWriteMode() {
428 public function getDescription() {
429 return 'Create and edit pages.';
432 public function getPossibleErrors() {
433 global $wgMaxArticleSize;
435 return array_merge( parent
::getPossibleErrors(),
436 $this->getTitleOrPageIdErrorMessage(),
438 array( 'missingtext' ),
439 array( 'createonly-exists' ),
440 array( 'nocreate-missing' ),
441 array( 'nosuchrevid', 'undo' ),
442 array( 'nosuchrevid', 'undoafter' ),
443 array( 'revwrongpage', 'id', 'text' ),
444 array( 'undo-failure' ),
445 array( 'hashcheckfailed' ),
446 array( 'hookaborted' ),
447 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
448 array( 'noimageredirect-anon' ),
449 array( 'noimageredirect-logged' ),
450 array( 'spamdetected', 'spam' ),
451 array( 'summaryrequired' ),
452 array( 'blockedtext' ),
453 array( 'contenttoobig', $wgMaxArticleSize ),
454 array( 'noedit-anon' ),
456 array( 'actionthrottledtext' ),
457 array( 'wasdeleted' ),
458 array( 'nocreate-loggedin' ),
459 array( 'blankpage' ),
460 array( 'editconflict' ),
461 array( 'emptynewsection' ),
462 array( 'unknownerror', 'retval' ),
463 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
464 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
465 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
466 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using '
467 . 'the text based edit API.' ),
468 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending '
469 . 'or prepending text.' ),
470 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to '
471 . 'the page\'s content model' ),
472 array( 'customcssprotected' ),
473 array( 'customjsprotected' ),
478 public function getAllowedParams() {
481 ApiBase
::PARAM_TYPE
=> 'string',
484 ApiBase
::PARAM_TYPE
=> 'integer',
487 'sectiontitle' => array(
488 ApiBase
::PARAM_TYPE
=> 'string',
489 ApiBase
::PARAM_REQUIRED
=> false,
493 ApiBase
::PARAM_TYPE
=> 'string',
494 ApiBase
::PARAM_REQUIRED
=> true
500 'basetimestamp' => null,
501 'starttimestamp' => null,
503 'createonly' => false,
506 ApiBase
::PARAM_DFLT
=> false,
507 ApiBase
::PARAM_DEPRECATED
=> true,
510 ApiBase
::PARAM_DFLT
=> false,
511 ApiBase
::PARAM_DEPRECATED
=> true,
513 'watchlist' => array(
514 ApiBase
::PARAM_DFLT
=> 'preferences',
515 ApiBase
::PARAM_TYPE
=> array(
523 'prependtext' => null,
524 'appendtext' => null,
526 ApiBase
::PARAM_TYPE
=> 'integer'
528 'undoafter' => array(
529 ApiBase
::PARAM_TYPE
=> 'integer'
532 ApiBase
::PARAM_TYPE
=> 'boolean',
533 ApiBase
::PARAM_DFLT
=> false,
535 'contentformat' => array(
536 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
538 'contentmodel' => array(
539 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
544 public function getParamDescription() {
545 $p = $this->getModulePrefix();
547 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
548 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
549 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
550 'sectiontitle' => 'The title for a new section',
551 'text' => 'Page content',
552 'token' => array( 'Edit token. You can get one of these through prop=info.',
553 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
555 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
556 'minor' => 'Minor edit',
557 'notminor' => 'Non-minor edit',
558 'bot' => 'Mark this edit as bot',
559 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
560 'Used to detect edit conflicts; leave unset to ignore conflicts'
562 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
563 'Used to detect edit conflicts; leave unset to ignore conflicts'
565 'recreate' => 'Override any errors about the article having been deleted in the meantime',
566 'createonly' => 'Don\'t edit the page if it exists already',
567 'nocreate' => 'Throw an error if the page doesn\'t exist',
568 'watch' => 'Add the page to your watchlist',
569 'unwatch' => 'Remove the page from your watchlist',
570 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
571 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
572 'If set, the edit won\'t be done unless the hash is correct' ),
573 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
574 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
575 "Use {$p}section=new to append a new section" ),
576 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
577 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
578 'redirect' => 'Automatically resolve redirects',
579 'contentformat' => 'Content serialization format used for the input text',
580 'contentmodel' => 'Content model of the new content',
584 public function getResultProperties() {
589 ApiBase
::PROP_TYPE
=> array(
595 ApiBase
::PROP_TYPE
=> 'integer',
596 ApiBase
::PROP_NULLABLE
=> true
599 ApiBase
::PROP_TYPE
=> 'string',
600 ApiBase
::PROP_NULLABLE
=> true
602 'nochange' => 'boolean',
604 ApiBase
::PROP_TYPE
=> 'integer',
605 ApiBase
::PROP_NULLABLE
=> true
608 ApiBase
::PROP_TYPE
=> 'integer',
609 ApiBase
::PROP_NULLABLE
=> true
611 'newtimestamp' => array(
612 ApiBase
::PROP_TYPE
=> 'string',
613 ApiBase
::PROP_NULLABLE
=> true
619 public function needsToken() {
623 public function getTokenSalt() {
627 public function getExamples() {
630 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
631 => 'Edit a page (anonymous user)',
633 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
634 => 'Prepend __NOTOC__ to a page (anonymous user)',
635 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
636 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
640 public function getHelpUrls() {
641 return 'https://www.mediawiki.org/wiki/API:Edit';
644 public function getVersion() {
645 return __CLASS__
. ': $Id$';