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();
62 /** @var $newTitle Title */
63 foreach ( $titles as $id => $newTitle ) {
65 if ( !isset( $titles[$id - 1] ) ) {
66 $titles[$id - 1] = $oldTitle;
69 $redirValues[] = array(
70 'from' => $titles[$id - 1]->getPrefixedText(),
71 'to' => $newTitle->getPrefixedText()
74 $titleObj = $newTitle;
77 $apiResult->setIndexedTagName( $redirValues, 'r' );
78 $apiResult->addValue( null, 'redirects', $redirValues );
80 // Since the page changed, update $pageObj
81 $pageObj = WikiPage
::factory( $titleObj );
85 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
86 $contentHandler = $pageObj->getContentHandler();
88 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
91 // @todo ask handler whether direct editing is supported at all! make allowFlatEdit() method or some such
93 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
94 $params['contentformat'] = $contentHandler->getDefaultFormat();
97 $contentFormat = $params['contentformat'];
99 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
100 $name = $titleObj->getPrefixedDBkey();
101 $model = $contentHandler->getModelID();
103 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
104 " $model used by $name", 'badformat' );
107 if ( $params['createonly'] && $titleObj->exists() ) {
108 $this->dieUsageMsg( 'createonly-exists' );
110 if ( $params['nocreate'] && !$titleObj->exists() ) {
111 $this->dieUsageMsg( 'nocreate-missing' );
114 // Now let's check whether we're even allowed to do this
115 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
116 if ( !$titleObj->exists() ) {
117 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
119 if ( count( $errors ) ) {
120 $this->dieUsageMsg( $errors[0] );
123 $toMD5 = $params['text'];
124 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
126 $content = $pageObj->getContent();
129 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
130 # If this is a MediaWiki:x message, then load the messages
131 # and return the message value for x.
132 $text = $titleObj->getDefaultMessageText();
133 if ( $text === false ) {
138 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
139 } catch ( MWContentSerializationException
$ex ) {
140 $this->dieUsage( $ex->getMessage(), 'parseerror' );
144 # Otherwise, make a new empty content.
145 $content = $contentHandler->makeEmptyContent();
149 // @todo: Add support for appending/prepending to the Content interface
151 if ( !( $content instanceof TextContent
) ) {
152 $mode = $contentHandler->getModelID();
153 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
156 if ( !is_null( $params['section'] ) ) {
157 if ( !$contentHandler->supportsSections() ) {
158 $modelName = $contentHandler->getModelID();
159 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
162 // Process the content for section edits
163 $section = intval( $params['section'] );
164 $content = $content->getSection( $section );
167 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
174 $text = $content->serialize( $contentFormat );
177 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
178 $toMD5 = $params['prependtext'] . $params['appendtext'];
181 if ( $params['undo'] > 0 ) {
182 if ( $params['undoafter'] > 0 ) {
183 if ( $params['undo'] < $params['undoafter'] ) {
184 list( $params['undo'], $params['undoafter'] ) =
185 array( $params['undoafter'], $params['undo'] );
187 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
189 $undoRev = Revision
::newFromID( $params['undo'] );
190 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
191 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
194 if ( $params['undoafter'] == 0 ) {
195 $undoafterRev = $undoRev->getPrevious();
197 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
198 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
201 if ( $undoRev->getPage() != $pageObj->getID() ) {
202 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
204 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
205 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
208 $newContent = $contentHandler->getUndoContent( $pageObj->getRevision(), $undoRev, $undoafterRev );
210 if ( !$newContent ) {
211 $this->dieUsageMsg( 'undo-failure' );
214 $params['text'] = $newContent->serialize( $params['contentformat'] );
216 // If no summary was given and we only undid one rev,
217 // use an autosummary
218 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
219 $params['summary'] = wfMessage( 'undo-summary', $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
223 // See if the MD5 hash checks out
224 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
225 $this->dieUsageMsg( 'hashcheckfailed' );
228 // EditPage wants to parse its stuff from a WebRequest
229 // That interface kind of sucks, but it's workable
230 $requestArray = array(
231 'wpTextbox1' => $params['text'],
232 'format' => $contentFormat,
233 'model' => $contentHandler->getModelID(),
234 'wpEditToken' => $params['token'],
235 'wpIgnoreBlankSummary' => ''
238 if ( !is_null( $params['summary'] ) ) {
239 $requestArray['wpSummary'] = $params['summary'];
242 if ( !is_null( $params['sectiontitle'] ) ) {
243 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
246 // TODO: Pass along information from 'undoafter' as well
247 if ( $params['undo'] > 0 ) {
248 $requestArray['wpUndidRevision'] = $params['undo'];
251 // Watch out for basetimestamp == ''
252 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
253 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
254 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
256 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
259 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
260 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
262 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
265 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
266 $requestArray['wpMinoredit'] = '';
269 if ( $params['recreate'] ) {
270 $requestArray['wpRecreate'] = '';
273 if ( !is_null( $params['section'] ) ) {
274 $section = intval( $params['section'] );
275 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
276 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
278 $requestArray['wpSection'] = $params['section'];
280 $requestArray['wpSection'] = '';
283 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
285 // Deprecated parameters
286 if ( $params['watch'] ) {
288 } elseif ( $params['unwatch'] ) {
293 $requestArray['wpWatchthis'] = '';
296 global $wgTitle, $wgRequest;
298 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
300 // Some functions depend on $wgTitle == $ep->mTitle
301 // TODO: Make them not or check if they still do
302 $wgTitle = $titleObj;
304 $articleContext = new RequestContext
;
305 $articleContext->setRequest( $req );
306 $articleContext->setWikiPage( $pageObj );
307 $articleContext->setUser( $this->getUser() );
309 /** @var $articleObject Article */
310 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
312 $ep = new EditPage( $articleObject );
314 // allow editing of non-textual content.
315 $ep->allowNonTextContent
= true;
317 $ep->setContextTitle( $titleObj );
318 $ep->importFormData( $req );
321 // Handle APIEditBeforeSave parameters
323 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
325 $r['result'] = 'Failure';
326 $apiResult->addValue( null, $this->getModuleName(), $r );
329 $this->dieUsageMsg( 'hookaborted' );
333 // Do the actual save
334 $oldRevId = $articleObject->getRevIdFetched();
336 // Fake $wgRequest for some hooks inside EditPage
337 // @todo FIXME: This interface SUCKS
338 $oldRequest = $wgRequest;
341 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
342 $wgRequest = $oldRequest;
343 global $wgMaxArticleSize;
345 switch( $status->value
) {
346 case EditPage
::AS_HOOK_ERROR
:
347 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
348 $this->dieUsageMsg( 'hookaborted' );
350 case EditPage
::AS_PARSE_ERROR
:
351 $this->dieUsage( $status->getMessage(), 'parseerror' );
353 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
354 $this->dieUsageMsg( 'noimageredirect-anon' );
356 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
357 $this->dieUsageMsg( 'noimageredirect-logged' );
359 case EditPage
::AS_SPAM_ERROR
:
360 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
362 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
363 $this->dieUsageMsg( 'blockedtext' );
365 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
366 case EditPage
::AS_CONTENT_TOO_BIG
:
367 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
369 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
370 $this->dieUsageMsg( 'noedit-anon' );
372 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
373 $this->dieUsageMsg( 'noedit' );
375 case EditPage
::AS_READ_ONLY_PAGE
:
376 $this->dieReadOnly();
378 case EditPage
::AS_RATE_LIMITED
:
379 $this->dieUsageMsg( 'actionthrottledtext' );
381 case EditPage
::AS_ARTICLE_WAS_DELETED
:
382 $this->dieUsageMsg( 'wasdeleted' );
384 case EditPage
::AS_NO_CREATE_PERMISSION
:
385 $this->dieUsageMsg( 'nocreate-loggedin' );
387 case EditPage
::AS_BLANK_ARTICLE
:
388 $this->dieUsageMsg( 'blankpage' );
390 case EditPage
::AS_CONFLICT_DETECTED
:
391 $this->dieUsageMsg( 'editconflict' );
393 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
394 case EditPage
::AS_TEXTBOX_EMPTY
:
395 $this->dieUsageMsg( 'emptynewsection' );
397 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
401 case EditPage
::AS_SUCCESS_UPDATE
:
402 $r['result'] = 'Success';
403 $r['pageid'] = intval( $titleObj->getArticleID() );
404 $r['title'] = $titleObj->getPrefixedText();
405 $r['contentmodel'] = $titleObj->getContentModel();
406 $newRevId = $articleObject->getLatest();
407 if ( $newRevId == $oldRevId ) {
410 $r['oldrevid'] = intval( $oldRevId );
411 $r['newrevid'] = intval( $newRevId );
412 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
413 $pageObj->getTimestamp() );
417 case EditPage
::AS_SUMMARY_NEEDED
:
418 $this->dieUsageMsg( 'summaryrequired' );
420 case EditPage
::AS_END
:
422 // $status came from WikiPage::doEdit()
423 $errors = $status->getErrorsArray();
424 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
427 $apiResult->addValue( null, $this->getModuleName(), $r );
430 public function mustBePosted() {
434 public function isWriteMode() {
438 public function getDescription() {
439 return 'Create and edit pages.';
442 public function getPossibleErrors() {
443 global $wgMaxArticleSize;
445 return array_merge( parent
::getPossibleErrors(),
446 $this->getTitleOrPageIdErrorMessage(),
448 array( 'missingtext' ),
449 array( 'createonly-exists' ),
450 array( 'nocreate-missing' ),
451 array( 'nosuchrevid', 'undo' ),
452 array( 'nosuchrevid', 'undoafter' ),
453 array( 'revwrongpage', 'id', 'text' ),
454 array( 'undo-failure' ),
455 array( 'hashcheckfailed' ),
456 array( 'hookaborted' ),
457 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
458 array( 'noimageredirect-anon' ),
459 array( 'noimageredirect-logged' ),
460 array( 'spamdetected', 'spam' ),
461 array( 'summaryrequired' ),
462 array( 'blockedtext' ),
463 array( 'contenttoobig', $wgMaxArticleSize ),
464 array( 'noedit-anon' ),
466 array( 'actionthrottledtext' ),
467 array( 'wasdeleted' ),
468 array( 'nocreate-loggedin' ),
469 array( 'blankpage' ),
470 array( 'editconflict' ),
471 array( 'emptynewsection' ),
472 array( 'unknownerror', 'retval' ),
473 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
474 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
475 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
476 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using '
477 . 'the text based edit API.' ),
478 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending '
479 . 'or prepending text.' ),
480 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to '
481 . 'the page\'s content model' ),
482 array( 'customcssprotected' ),
483 array( 'customjsprotected' ),
488 public function getAllowedParams() {
491 ApiBase
::PARAM_TYPE
=> 'string',
494 ApiBase
::PARAM_TYPE
=> 'integer',
497 'sectiontitle' => array(
498 ApiBase
::PARAM_TYPE
=> 'string',
502 ApiBase
::PARAM_TYPE
=> 'string',
503 ApiBase
::PARAM_REQUIRED
=> true
509 'basetimestamp' => null,
510 'starttimestamp' => null,
512 'createonly' => false,
515 ApiBase
::PARAM_DFLT
=> false,
516 ApiBase
::PARAM_DEPRECATED
=> true,
519 ApiBase
::PARAM_DFLT
=> false,
520 ApiBase
::PARAM_DEPRECATED
=> true,
522 'watchlist' => array(
523 ApiBase
::PARAM_DFLT
=> 'preferences',
524 ApiBase
::PARAM_TYPE
=> array(
532 'prependtext' => null,
533 'appendtext' => null,
535 ApiBase
::PARAM_TYPE
=> 'integer'
537 'undoafter' => array(
538 ApiBase
::PARAM_TYPE
=> 'integer'
541 ApiBase
::PARAM_TYPE
=> 'boolean',
542 ApiBase
::PARAM_DFLT
=> false,
544 'contentformat' => array(
545 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
547 'contentmodel' => array(
548 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
553 public function getParamDescription() {
554 $p = $this->getModulePrefix();
556 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
557 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
558 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
559 'sectiontitle' => 'The title for a new section',
560 'text' => 'Page content',
561 'token' => array( 'Edit token. You can get one of these through prop=info.',
562 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
564 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
565 'minor' => 'Minor edit',
566 'notminor' => 'Non-minor edit',
567 'bot' => 'Mark this edit as bot',
568 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
569 'Used to detect edit conflicts; leave unset to ignore conflicts'
571 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
572 'Used to detect edit conflicts; leave unset to ignore conflicts'
574 'recreate' => 'Override any errors about the article having been deleted in the meantime',
575 'createonly' => 'Don\'t edit the page if it exists already',
576 'nocreate' => 'Throw an error if the page doesn\'t exist',
577 'watch' => 'Add the page to your watchlist',
578 'unwatch' => 'Remove the page from your watchlist',
579 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
580 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
581 'If set, the edit won\'t be done unless the hash is correct' ),
582 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
583 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
584 "Use {$p}section=new to append a new section" ),
585 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
586 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
587 'redirect' => 'Automatically resolve redirects',
588 'contentformat' => 'Content serialization format used for the input text',
589 'contentmodel' => 'Content model of the new content',
593 public function getResultProperties() {
598 ApiBase
::PROP_TYPE
=> array(
604 ApiBase
::PROP_TYPE
=> 'integer',
605 ApiBase
::PROP_NULLABLE
=> true
608 ApiBase
::PROP_TYPE
=> 'string',
609 ApiBase
::PROP_NULLABLE
=> true
611 'nochange' => 'boolean',
613 ApiBase
::PROP_TYPE
=> 'integer',
614 ApiBase
::PROP_NULLABLE
=> true
617 ApiBase
::PROP_TYPE
=> 'integer',
618 ApiBase
::PROP_NULLABLE
=> true
620 'newtimestamp' => array(
621 ApiBase
::PROP_TYPE
=> 'string',
622 ApiBase
::PROP_NULLABLE
=> true
628 public function needsToken() {
632 public function getTokenSalt() {
636 public function getExamples() {
638 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
639 => 'Edit a page (anonymous user)',
640 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
641 => 'Prepend __NOTOC__ to a page (anonymous user)',
642 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
643 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
647 public function getHelpUrls() {
648 return 'https://www.mediawiki.org/wiki/API:Edit';