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 $contentHandler = $pageObj->getContentHandler();
59 // @todo ask handler whether direct editing is supported at all! make allowFlatEdit() method or some such
61 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
62 $params['contentformat'] = $contentHandler->getDefaultFormat();
65 $contentFormat = $params['contentformat'];
67 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
68 $name = $titleObj->getPrefixedDBkey();
69 $model = $contentHandler->getModelID();
71 $this->dieUsage( "The requested format $contentFormat is not supported for content model $model used by $name", 'badformat' );
74 $apiResult = $this->getResult();
76 if ( $params['redirect'] ) {
77 if ( $titleObj->isRedirect() ) {
78 $oldTitle = $titleObj;
80 $titles = Revision
::newFromTitle( $oldTitle )->getContent( Revision
::FOR_THIS_USER
)->getRedirectChain();
81 // array_shift( $titles );
83 $redirValues = array();
84 foreach ( $titles as $id => $newTitle ) {
86 if ( !isset( $titles[ $id - 1 ] ) ) {
87 $titles[ $id - 1 ] = $oldTitle;
90 $redirValues[] = array(
91 'from' => $titles[ $id - 1 ]->getPrefixedText(),
92 'to' => $newTitle->getPrefixedText()
95 $titleObj = $newTitle;
98 $apiResult->setIndexedTagName( $redirValues, 'r' );
99 $apiResult->addValue( null, 'redirects', $redirValues );
103 if ( $params['createonly'] && $titleObj->exists() ) {
104 $this->dieUsageMsg( 'createonly-exists' );
106 if ( $params['nocreate'] && !$titleObj->exists() ) {
107 $this->dieUsageMsg( 'nocreate-missing' );
110 // Now let's check whether we're even allowed to do this
111 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
112 if ( !$titleObj->exists() ) {
113 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
115 if ( count( $errors ) ) {
116 $this->dieUsageMsg( $errors[0] );
119 $toMD5 = $params['text'];
120 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
122 $content = $pageObj->getContent();
124 if ( !( $content instanceof TextContent
) ) {
125 // @todo: ContentHandler should have an isFlat() method or some such
126 // @todo: XXX: or perhaps there should be Content::append(), Content::prepend() and Content::supportsConcatenation()
127 $mode = $contentHandler->getModelID();
128 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
132 # If this is a MediaWiki:x message, then load the messages
133 # and return the message value for x.
134 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
135 $text = $titleObj->getDefaultMessageText();
136 if ( $text === false ) {
140 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
144 if ( !is_null( $params['section'] ) ) {
145 if ( !$contentHandler->supportsSections() ) {
146 $modelName = $contentHandler->getModelID();
147 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
150 // Process the content for section edits
151 $section = intval( $params['section'] );
152 $content = $content->getSection( $section );
155 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
162 $text = $content->serialize( $contentFormat );
165 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
166 $toMD5 = $params['prependtext'] . $params['appendtext'];
169 if ( $params['undo'] > 0 ) {
170 if ( $params['undoafter'] > 0 ) {
171 if ( $params['undo'] < $params['undoafter'] ) {
172 list( $params['undo'], $params['undoafter'] ) =
173 array( $params['undoafter'], $params['undo'] );
175 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
177 $undoRev = Revision
::newFromID( $params['undo'] );
178 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
179 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
182 if ( $params['undoafter'] == 0 ) {
183 $undoafterRev = $undoRev->getPrevious();
185 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
186 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
189 if ( $undoRev->getPage() != $pageObj->getID() ) {
190 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
192 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
193 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
196 $newContent = $contentHandler->getUndoContent( $undoRev, $undoafterRev );
197 if ( !$newContent ) {
198 $this->dieUsageMsg( 'undo-failure' );
201 $params['contentformat'] = $contentHandler->getDefaultFormat();
202 $params['text'] = $newContent->serialize( $params['contentformat'] );
204 // If no summary was given and we only undid one rev,
205 // use an autosummary
206 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
207 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
211 // See if the MD5 hash checks out
212 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
213 $this->dieUsageMsg( 'hashcheckfailed' );
216 // EditPage wants to parse its stuff from a WebRequest
217 // That interface kind of sucks, but it's workable
218 $requestArray = array(
219 'wpTextbox1' => $params['text'],
220 'format' => $contentFormat,
221 'model' => $contentHandler->getModelID(),
222 'wpEditToken' => $params['token'],
223 'wpIgnoreBlankSummary' => ''
226 if ( !is_null( $params['summary'] ) ) {
227 $requestArray['wpSummary'] = $params['summary'];
230 if ( !is_null( $params['sectiontitle'] ) ) {
231 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
234 // Watch out for basetimestamp == ''
235 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
236 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
237 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
239 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
242 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
243 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
245 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
248 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
249 $requestArray['wpMinoredit'] = '';
252 if ( $params['recreate'] ) {
253 $requestArray['wpRecreate'] = '';
256 if ( !is_null( $params['section'] ) ) {
257 $section = intval( $params['section'] );
258 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
259 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
261 $requestArray['wpSection'] = $params['section'];
263 $requestArray['wpSection'] = '';
266 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
268 // Deprecated parameters
269 if ( $params['watch'] ) {
271 } elseif ( $params['unwatch'] ) {
276 $requestArray['wpWatchthis'] = '';
279 global $wgTitle, $wgRequest;
281 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
283 // Some functions depend on $wgTitle == $ep->mTitle
284 // TODO: Make them not or check if they still do
285 $wgTitle = $titleObj;
287 $articleObject = new Article( $titleObj );
288 $ep = new EditPage( $articleObject );
290 $ep->setContextTitle( $titleObj );
291 $ep->importFormData( $req );
294 // Handle APIEditBeforeSave parameters
296 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
298 $r['result'] = 'Failure';
299 $apiResult->addValue( null, $this->getModuleName(), $r );
302 $this->dieUsageMsg( 'hookaborted' );
306 // Do the actual save
307 $oldRevId = $articleObject->getRevIdFetched();
309 // Fake $wgRequest for some hooks inside EditPage
310 // @todo FIXME: This interface SUCKS
311 $oldRequest = $wgRequest;
314 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
315 $wgRequest = $oldRequest;
316 global $wgMaxArticleSize;
318 switch( $status->value
) {
319 case EditPage
::AS_HOOK_ERROR
:
320 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
321 $this->dieUsageMsg( 'hookaborted' );
323 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
324 $this->dieUsageMsg( 'noimageredirect-anon' );
326 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
327 $this->dieUsageMsg( 'noimageredirect-logged' );
329 case EditPage
::AS_SPAM_ERROR
:
330 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
332 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
333 $this->dieUsageMsg( 'blockedtext' );
335 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
336 case EditPage
::AS_CONTENT_TOO_BIG
:
337 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
339 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
340 $this->dieUsageMsg( 'noedit-anon' );
342 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
343 $this->dieUsageMsg( 'noedit' );
345 case EditPage
::AS_READ_ONLY_PAGE
:
346 $this->dieReadOnly();
348 case EditPage
::AS_RATE_LIMITED
:
349 $this->dieUsageMsg( 'actionthrottledtext' );
351 case EditPage
::AS_ARTICLE_WAS_DELETED
:
352 $this->dieUsageMsg( 'wasdeleted' );
354 case EditPage
::AS_NO_CREATE_PERMISSION
:
355 $this->dieUsageMsg( 'nocreate-loggedin' );
357 case EditPage
::AS_BLANK_ARTICLE
:
358 $this->dieUsageMsg( 'blankpage' );
360 case EditPage
::AS_CONFLICT_DETECTED
:
361 $this->dieUsageMsg( 'editconflict' );
363 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
364 case EditPage
::AS_TEXTBOX_EMPTY
:
365 $this->dieUsageMsg( 'emptynewsection' );
367 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
370 case EditPage
::AS_SUCCESS_UPDATE
:
371 $r['result'] = 'Success';
372 $r['pageid'] = intval( $titleObj->getArticleID() );
373 $r['title'] = $titleObj->getPrefixedText();
374 $r['contentmodel'] = $titleObj->getContentModel();
375 $newRevId = $articleObject->getLatest();
376 if ( $newRevId == $oldRevId ) {
379 $r['oldrevid'] = intval( $oldRevId );
380 $r['newrevid'] = intval( $newRevId );
381 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
382 $pageObj->getTimestamp() );
386 case EditPage
::AS_SUMMARY_NEEDED
:
387 $this->dieUsageMsg( 'summaryrequired' );
389 case EditPage
::AS_END
:
391 // $status came from WikiPage::doEdit()
392 $errors = $status->getErrorsArray();
393 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
396 $apiResult->addValue( null, $this->getModuleName(), $r );
399 public function mustBePosted() {
403 public function isWriteMode() {
407 public function getDescription() {
408 return 'Create and edit pages.';
411 public function getPossibleErrors() {
412 global $wgMaxArticleSize;
414 return array_merge( parent
::getPossibleErrors(),
415 $this->getTitleOrPageIdErrorMessage(),
417 array( 'missingtext' ),
418 array( 'createonly-exists' ),
419 array( 'nocreate-missing' ),
420 array( 'nosuchrevid', 'undo' ),
421 array( 'nosuchrevid', 'undoafter' ),
422 array( 'revwrongpage', 'id', 'text' ),
423 array( 'undo-failure' ),
424 array( 'hashcheckfailed' ),
425 array( 'hookaborted' ),
426 array( 'noimageredirect-anon' ),
427 array( 'noimageredirect-logged' ),
428 array( 'spamdetected', 'spam' ),
429 array( 'summaryrequired' ),
430 array( 'blockedtext' ),
431 array( 'contenttoobig', $wgMaxArticleSize ),
432 array( 'noedit-anon' ),
434 array( 'actionthrottledtext' ),
435 array( 'wasdeleted' ),
436 array( 'nocreate-loggedin' ),
437 array( 'blankpage' ),
438 array( 'editconflict' ),
439 array( 'emptynewsection' ),
440 array( 'unknownerror', 'retval' ),
441 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
442 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
443 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
444 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using the text based edit API.' ),
445 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending or prepending text.' ),
446 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to the page\'s content model' ),
447 array( 'customcssprotected' ),
448 array( 'customjsprotected' ),
453 public function getAllowedParams() {
456 ApiBase
::PARAM_TYPE
=> 'string',
459 ApiBase
::PARAM_TYPE
=> 'integer',
462 'sectiontitle' => array(
463 ApiBase
::PARAM_TYPE
=> 'string',
464 ApiBase
::PARAM_REQUIRED
=> false,
472 'basetimestamp' => null,
473 'starttimestamp' => null,
475 'createonly' => false,
478 ApiBase
::PARAM_DFLT
=> false,
479 ApiBase
::PARAM_DEPRECATED
=> true,
482 ApiBase
::PARAM_DFLT
=> false,
483 ApiBase
::PARAM_DEPRECATED
=> true,
485 'watchlist' => array(
486 ApiBase
::PARAM_DFLT
=> 'preferences',
487 ApiBase
::PARAM_TYPE
=> array(
495 'prependtext' => null,
496 'appendtext' => null,
498 ApiBase
::PARAM_TYPE
=> 'integer'
500 'undoafter' => array(
501 ApiBase
::PARAM_TYPE
=> 'integer'
504 ApiBase
::PARAM_TYPE
=> 'boolean',
505 ApiBase
::PARAM_DFLT
=> false,
510 public function getParamDescription() {
511 $p = $this->getModulePrefix();
513 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
514 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
515 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
516 'sectiontitle' => 'The title for a new section',
517 'text' => 'Page content',
518 'token' => array( 'Edit token. You can get one of these through prop=info.',
519 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
521 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
522 'minor' => 'Minor edit',
523 'notminor' => 'Non-minor edit',
524 'bot' => 'Mark this edit as bot',
525 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
526 'Used to detect edit conflicts; leave unset to ignore conflicts'
528 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
529 'Used to detect edit conflicts; leave unset to ignore conflicts'
531 'recreate' => 'Override any errors about the article having been deleted in the meantime',
532 'createonly' => 'Don\'t edit the page if it exists already',
533 'nocreate' => 'Throw an error if the page doesn\'t exist',
534 'watch' => 'Add the page to your watchlist',
535 'unwatch' => 'Remove the page from your watchlist',
536 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
537 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
538 'If set, the edit won\'t be done unless the hash is correct' ),
539 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
540 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
541 "Use {$p}section=new to append a new section" ),
542 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
543 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
544 'redirect' => 'Automatically resolve redirects',
548 public function getResultProperties() {
553 ApiBase
::PROP_TYPE
=> array(
559 ApiBase
::PROP_TYPE
=> 'integer',
560 ApiBase
::PROP_NULLABLE
=> true
563 ApiBase
::PROP_TYPE
=> 'string',
564 ApiBase
::PROP_NULLABLE
=> true
566 'nochange' => 'boolean',
568 ApiBase
::PROP_TYPE
=> 'integer',
569 ApiBase
::PROP_NULLABLE
=> true
572 ApiBase
::PROP_TYPE
=> 'integer',
573 ApiBase
::PROP_NULLABLE
=> true
575 'newtimestamp' => array(
576 ApiBase
::PROP_TYPE
=> 'string',
577 ApiBase
::PROP_NULLABLE
=> true
583 public function needsToken() {
587 public function getTokenSalt() {
591 public function getExamples() {
594 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
595 => 'Edit a page (anonymous user)',
597 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
598 => 'Prepend __NOTOC__ to a page (anonymous user)',
599 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
600 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
604 public function getHelpUrls() {
605 return 'https://www.mediawiki.org/wiki/API:Edit';
608 public function getVersion() {
609 return __CLASS__
. ': $Id$';