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 if ( $titleObj->isExternal() ) {
50 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
53 $apiResult = $this->getResult();
55 if ( $params['redirect'] ) {
56 if ( $titleObj->isRedirect() ) {
57 $oldTitle = $titleObj;
59 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
60 ->getContent( Revision
::FOR_THIS_USER
, $user )
62 // array_shift( $titles );
64 $redirValues = array();
65 foreach ( $titles as $id => $newTitle ) {
67 if ( !isset( $titles[$id - 1] ) ) {
68 $titles[$id - 1] = $oldTitle;
71 $redirValues[] = array(
72 'from' => $titles[$id - 1]->getPrefixedText(),
73 'to' => $newTitle->getPrefixedText()
76 $titleObj = $newTitle;
79 $apiResult->setIndexedTagName( $redirValues, 'r' );
80 $apiResult->addValue( null, 'redirects', $redirValues );
82 // Since the page changed, update $pageObj
83 $pageObj = WikiPage
::factory( $titleObj );
87 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
88 $contentHandler = $pageObj->getContentHandler();
90 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
93 // @todo ask handler whether direct editing is supported at all! make allowFlatEdit() method or some such
95 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
96 $params['contentformat'] = $contentHandler->getDefaultFormat();
99 $contentFormat = $params['contentformat'];
101 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
102 $name = $titleObj->getPrefixedDBkey();
103 $model = $contentHandler->getModelID();
105 $this->dieUsage( "The requested format $contentFormat is not supported for content model ".
106 " $model used by $name", 'badformat' );
109 if ( $params['createonly'] && $titleObj->exists() ) {
110 $this->dieUsageMsg( 'createonly-exists' );
112 if ( $params['nocreate'] && !$titleObj->exists() ) {
113 $this->dieUsageMsg( 'nocreate-missing' );
116 // Now let's check whether we're even allowed to do this
117 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
118 if ( !$titleObj->exists() ) {
119 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
121 if ( count( $errors ) ) {
122 $this->dieUsageMsg( $errors[0] );
125 $toMD5 = $params['text'];
126 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
128 $content = $pageObj->getContent();
131 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
132 # If this is a MediaWiki:x message, then load the messages
133 # and return the message value for x.
134 $text = $titleObj->getDefaultMessageText();
135 if ( $text === false ) {
140 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
141 } catch ( MWContentSerializationException
$ex ) {
142 $this->dieUsage( $ex->getMessage(), 'parseerror' );
146 # Otherwise, make a new empty content.
147 $content = $contentHandler->makeEmptyContent();
151 // @todo: Add support for appending/prepending to the Content interface
153 if ( !( $content instanceof TextContent
) ) {
154 $mode = $contentHandler->getModelID();
155 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
158 if ( !is_null( $params['section'] ) ) {
159 if ( !$contentHandler->supportsSections() ) {
160 $modelName = $contentHandler->getModelID();
161 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
164 // Process the content for section edits
165 $section = intval( $params['section'] );
166 $content = $content->getSection( $section );
169 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
176 $text = $content->serialize( $contentFormat );
179 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
180 $toMD5 = $params['prependtext'] . $params['appendtext'];
183 if ( $params['undo'] > 0 ) {
184 if ( $params['undoafter'] > 0 ) {
185 if ( $params['undo'] < $params['undoafter'] ) {
186 list( $params['undo'], $params['undoafter'] ) =
187 array( $params['undoafter'], $params['undo'] );
189 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
191 $undoRev = Revision
::newFromID( $params['undo'] );
192 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
193 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
196 if ( $params['undoafter'] == 0 ) {
197 $undoafterRev = $undoRev->getPrevious();
199 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
200 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
203 if ( $undoRev->getPage() != $pageObj->getID() ) {
204 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
206 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
207 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
210 $newContent = $contentHandler->getUndoContent( $pageObj->getRevision(), $undoRev, $undoafterRev );
212 if ( !$newContent ) {
213 $this->dieUsageMsg( 'undo-failure' );
216 $params['text'] = $newContent->serialize( $params['contentformat'] );
218 // If no summary was given and we only undid one rev,
219 // use an autosummary
220 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
221 $params['summary'] = wfMessage( 'undo-summary', $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
225 // See if the MD5 hash checks out
226 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
227 $this->dieUsageMsg( 'hashcheckfailed' );
230 // EditPage wants to parse its stuff from a WebRequest
231 // That interface kind of sucks, but it's workable
232 $requestArray = array(
233 'wpTextbox1' => $params['text'],
234 'format' => $contentFormat,
235 'model' => $contentHandler->getModelID(),
236 'wpEditToken' => $params['token'],
237 'wpIgnoreBlankSummary' => ''
240 if ( !is_null( $params['summary'] ) ) {
241 $requestArray['wpSummary'] = $params['summary'];
244 if ( !is_null( $params['sectiontitle'] ) ) {
245 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
248 // TODO: Pass along information from 'undoafter' as well
249 if ( $params['undo'] > 0 ) {
250 $requestArray['wpUndidRevision'] = $params['undo'];
253 // Watch out for basetimestamp == ''
254 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
255 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
256 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
258 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
261 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
262 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
264 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
267 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
268 $requestArray['wpMinoredit'] = '';
271 if ( $params['recreate'] ) {
272 $requestArray['wpRecreate'] = '';
275 if ( !is_null( $params['section'] ) ) {
276 $section = intval( $params['section'] );
277 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
278 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
280 $requestArray['wpSection'] = $params['section'];
282 $requestArray['wpSection'] = '';
285 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
287 // Deprecated parameters
288 if ( $params['watch'] ) {
290 } elseif ( $params['unwatch'] ) {
295 $requestArray['wpWatchthis'] = '';
298 global $wgTitle, $wgRequest;
300 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
302 // Some functions depend on $wgTitle == $ep->mTitle
303 // TODO: Make them not or check if they still do
304 $wgTitle = $titleObj;
306 $articleObject = new Article( $titleObj );
307 $ep = new EditPage( $articleObject );
309 // allow editing of non-textual content.
310 $ep->allowNonTextContent
= true;
312 $ep->setContextTitle( $titleObj );
313 $ep->importFormData( $req );
316 // Handle APIEditBeforeSave parameters
318 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
320 $r['result'] = 'Failure';
321 $apiResult->addValue( null, $this->getModuleName(), $r );
324 $this->dieUsageMsg( 'hookaborted' );
328 // Do the actual save
329 $oldRevId = $articleObject->getRevIdFetched();
331 // Fake $wgRequest for some hooks inside EditPage
332 // @todo FIXME: This interface SUCKS
333 $oldRequest = $wgRequest;
336 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
337 $wgRequest = $oldRequest;
338 global $wgMaxArticleSize;
340 switch( $status->value
) {
341 case EditPage
::AS_HOOK_ERROR
:
342 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
343 $this->dieUsageMsg( 'hookaborted' );
345 case EditPage
::AS_PARSE_ERROR
:
346 $this->dieUsage( $status->getMessage(), 'parseerror' );
348 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
349 $this->dieUsageMsg( 'noimageredirect-anon' );
351 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
352 $this->dieUsageMsg( 'noimageredirect-logged' );
354 case EditPage
::AS_SPAM_ERROR
:
355 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
357 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
358 $this->dieUsageMsg( 'blockedtext' );
360 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
361 case EditPage
::AS_CONTENT_TOO_BIG
:
362 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
364 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
365 $this->dieUsageMsg( 'noedit-anon' );
367 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
368 $this->dieUsageMsg( 'noedit' );
370 case EditPage
::AS_READ_ONLY_PAGE
:
371 $this->dieReadOnly();
373 case EditPage
::AS_RATE_LIMITED
:
374 $this->dieUsageMsg( 'actionthrottledtext' );
376 case EditPage
::AS_ARTICLE_WAS_DELETED
:
377 $this->dieUsageMsg( 'wasdeleted' );
379 case EditPage
::AS_NO_CREATE_PERMISSION
:
380 $this->dieUsageMsg( 'nocreate-loggedin' );
382 case EditPage
::AS_BLANK_ARTICLE
:
383 $this->dieUsageMsg( 'blankpage' );
385 case EditPage
::AS_CONFLICT_DETECTED
:
386 $this->dieUsageMsg( 'editconflict' );
388 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
389 case EditPage
::AS_TEXTBOX_EMPTY
:
390 $this->dieUsageMsg( 'emptynewsection' );
392 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
395 case EditPage
::AS_SUCCESS_UPDATE
:
396 $r['result'] = 'Success';
397 $r['pageid'] = intval( $titleObj->getArticleID() );
398 $r['title'] = $titleObj->getPrefixedText();
399 $r['contentmodel'] = $titleObj->getContentModel();
400 $newRevId = $articleObject->getLatest();
401 if ( $newRevId == $oldRevId ) {
404 $r['oldrevid'] = intval( $oldRevId );
405 $r['newrevid'] = intval( $newRevId );
407 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
408 $pageObj->getTimestamp() );
412 case EditPage
::AS_SUMMARY_NEEDED
:
413 $this->dieUsageMsg( 'summaryrequired' );
415 case EditPage
::AS_END
:
417 // $status came from WikiPage::doEdit()
418 $errors = $status->getErrorsArray();
419 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
422 $apiResult->addValue( null, $this->getModuleName(), $r );
425 public function mustBePosted() {
429 public function isWriteMode() {
433 public function getDescription() {
434 return 'Create and edit pages.';
437 public function getPossibleErrors() {
438 global $wgMaxArticleSize;
440 return array_merge( parent
::getPossibleErrors(),
441 $this->getTitleOrPageIdErrorMessage(),
443 array( 'missingtext' ),
444 array( 'createonly-exists' ),
445 array( 'nocreate-missing' ),
446 array( 'nosuchrevid', 'undo' ),
447 array( 'nosuchrevid', 'undoafter' ),
448 array( 'revwrongpage', 'id', 'text' ),
449 array( 'undo-failure' ),
450 array( 'hashcheckfailed' ),
451 array( 'hookaborted' ),
452 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
453 array( 'noimageredirect-anon' ),
454 array( 'noimageredirect-logged' ),
455 array( 'spamdetected', 'spam' ),
456 array( 'summaryrequired' ),
457 array( 'blockedtext' ),
458 array( 'contenttoobig', $wgMaxArticleSize ),
459 array( 'noedit-anon' ),
461 array( 'actionthrottledtext' ),
462 array( 'wasdeleted' ),
463 array( 'nocreate-loggedin' ),
464 array( 'blankpage' ),
465 array( 'editconflict' ),
466 array( 'emptynewsection' ),
467 array( 'unknownerror', 'retval' ),
468 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
469 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
470 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
471 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using '
472 . 'the text based edit API.' ),
473 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending '
474 . 'or prepending text.' ),
475 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to '
476 . 'the page\'s content model' ),
477 array( 'customcssprotected' ),
478 array( 'customjsprotected' ),
483 public function getAllowedParams() {
486 ApiBase
::PARAM_TYPE
=> 'string',
489 ApiBase
::PARAM_TYPE
=> 'integer',
492 'sectiontitle' => array(
493 ApiBase
::PARAM_TYPE
=> 'string',
494 ApiBase
::PARAM_REQUIRED
=> false,
498 ApiBase
::PARAM_TYPE
=> 'string',
499 ApiBase
::PARAM_REQUIRED
=> true
505 'basetimestamp' => null,
506 'starttimestamp' => null,
508 'createonly' => false,
511 ApiBase
::PARAM_DFLT
=> false,
512 ApiBase
::PARAM_DEPRECATED
=> true,
515 ApiBase
::PARAM_DFLT
=> false,
516 ApiBase
::PARAM_DEPRECATED
=> true,
518 'watchlist' => array(
519 ApiBase
::PARAM_DFLT
=> 'preferences',
520 ApiBase
::PARAM_TYPE
=> array(
528 'prependtext' => null,
529 'appendtext' => null,
531 ApiBase
::PARAM_TYPE
=> 'integer'
533 'undoafter' => array(
534 ApiBase
::PARAM_TYPE
=> 'integer'
537 ApiBase
::PARAM_TYPE
=> 'boolean',
538 ApiBase
::PARAM_DFLT
=> false,
540 'contentformat' => array(
541 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
543 'contentmodel' => array(
544 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
549 public function getParamDescription() {
550 $p = $this->getModulePrefix();
552 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
553 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
554 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
555 'sectiontitle' => 'The title for a new section',
556 'text' => 'Page content',
557 'token' => array( 'Edit token. You can get one of these through prop=info.',
558 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
560 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
561 'minor' => 'Minor edit',
562 'notminor' => 'Non-minor edit',
563 'bot' => 'Mark this edit as bot',
564 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
565 'Used to detect edit conflicts; leave unset to ignore conflicts'
567 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
568 'Used to detect edit conflicts; leave unset to ignore conflicts'
570 'recreate' => 'Override any errors about the article having been deleted in the meantime',
571 'createonly' => 'Don\'t edit the page if it exists already',
572 'nocreate' => 'Throw an error if the page doesn\'t exist',
573 'watch' => 'Add the page to your watchlist',
574 'unwatch' => 'Remove the page from your watchlist',
575 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
576 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
577 'If set, the edit won\'t be done unless the hash is correct' ),
578 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
579 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
580 "Use {$p}section=new to append a new section" ),
581 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
582 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
583 'redirect' => 'Automatically resolve redirects',
584 'contentformat' => 'Content serialization format used for the input text',
585 'contentmodel' => 'Content model of the new content',
589 public function getResultProperties() {
594 ApiBase
::PROP_TYPE
=> array(
600 ApiBase
::PROP_TYPE
=> 'integer',
601 ApiBase
::PROP_NULLABLE
=> true
604 ApiBase
::PROP_TYPE
=> 'string',
605 ApiBase
::PROP_NULLABLE
=> true
607 'nochange' => 'boolean',
609 ApiBase
::PROP_TYPE
=> 'integer',
610 ApiBase
::PROP_NULLABLE
=> true
613 ApiBase
::PROP_TYPE
=> 'integer',
614 ApiBase
::PROP_NULLABLE
=> true
616 'newtimestamp' => array(
617 ApiBase
::PROP_TYPE
=> 'string',
618 ApiBase
::PROP_NULLABLE
=> true
624 public function needsToken() {
628 public function getTokenSalt() {
632 public function getExamples() {
635 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
636 => 'Edit a page (anonymous user)',
638 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
639 => 'Prepend __NOTOC__ to a page (anonymous user)',
640 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
641 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
645 public function getHelpUrls() {
646 return 'https://www.mediawiki.org/wiki/API:Edit';