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 ".
72 " $model used by $name", 'badformat' );
75 $apiResult = $this->getResult();
77 if ( $params['redirect'] ) {
78 if ( $titleObj->isRedirect() ) {
79 $oldTitle = $titleObj;
81 $titles = Revision
::newFromTitle( $oldTitle )->getContent( Revision
::FOR_THIS_USER
)->getRedirectChain();
82 // array_shift( $titles );
84 $redirValues = array();
85 foreach ( $titles as $id => $newTitle ) {
87 if ( !isset( $titles[ $id - 1 ] ) ) {
88 $titles[ $id - 1 ] = $oldTitle;
91 $redirValues[] = array(
92 'from' => $titles[ $id - 1 ]->getPrefixedText(),
93 'to' => $newTitle->getPrefixedText()
96 $titleObj = $newTitle;
99 $apiResult->setIndexedTagName( $redirValues, 'r' );
100 $apiResult->addValue( null, 'redirects', $redirValues );
104 if ( $params['createonly'] && $titleObj->exists() ) {
105 $this->dieUsageMsg( 'createonly-exists' );
107 if ( $params['nocreate'] && !$titleObj->exists() ) {
108 $this->dieUsageMsg( 'nocreate-missing' );
111 // Now let's check whether we're even allowed to do this
112 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
113 if ( !$titleObj->exists() ) {
114 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
116 if ( count( $errors ) ) {
117 $this->dieUsageMsg( $errors[0] );
120 $toMD5 = $params['text'];
121 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
123 $content = $pageObj->getContent();
125 if ( !( $content instanceof TextContent
) ) {
126 // @todo: ContentHandler should have an isFlat() method or some such
127 // @todo: XXX: or perhaps there should be Content::append(), Content::prepend()
128 // @todo: ...and Content::supportsConcatenation()
129 $mode = $contentHandler->getModelID();
130 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
134 # If this is a MediaWiki:x message, then load the messages
135 # and return the message value for x.
136 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
137 $text = $titleObj->getDefaultMessageText();
138 if ( $text === false ) {
142 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
146 if ( !is_null( $params['section'] ) ) {
147 if ( !$contentHandler->supportsSections() ) {
148 $modelName = $contentHandler->getModelID();
149 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
152 // Process the content for section edits
153 $section = intval( $params['section'] );
154 $content = $content->getSection( $section );
157 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
164 $text = $content->serialize( $contentFormat );
167 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
168 $toMD5 = $params['prependtext'] . $params['appendtext'];
171 if ( $params['undo'] > 0 ) {
172 if ( $params['undoafter'] > 0 ) {
173 if ( $params['undo'] < $params['undoafter'] ) {
174 list( $params['undo'], $params['undoafter'] ) =
175 array( $params['undoafter'], $params['undo'] );
177 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
179 $undoRev = Revision
::newFromID( $params['undo'] );
180 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
181 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
184 if ( $params['undoafter'] == 0 ) {
185 $undoafterRev = $undoRev->getPrevious();
187 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
188 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
191 if ( $undoRev->getPage() != $pageObj->getID() ) {
192 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
194 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
195 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
198 $newContent = $contentHandler->getUndoContent( $undoRev, $undoafterRev );
199 if ( !$newContent ) {
200 $this->dieUsageMsg( 'undo-failure' );
203 $params['contentformat'] = $contentHandler->getDefaultFormat();
204 $params['text'] = $newContent->serialize( $params['contentformat'] );
206 // If no summary was given and we only undid one rev,
207 // use an autosummary
208 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
209 $params['summary'] = wfMessage( 'undo-summary', $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
213 // See if the MD5 hash checks out
214 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
215 $this->dieUsageMsg( 'hashcheckfailed' );
218 // EditPage wants to parse its stuff from a WebRequest
219 // That interface kind of sucks, but it's workable
220 $requestArray = array(
221 'wpTextbox1' => $params['text'],
222 'format' => $contentFormat,
223 'model' => $contentHandler->getModelID(),
224 'wpEditToken' => $params['token'],
225 'wpIgnoreBlankSummary' => ''
228 if ( !is_null( $params['summary'] ) ) {
229 $requestArray['wpSummary'] = $params['summary'];
232 if ( !is_null( $params['sectiontitle'] ) ) {
233 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
236 // Watch out for basetimestamp == ''
237 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
238 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
239 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
241 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
244 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
245 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
247 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
250 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
251 $requestArray['wpMinoredit'] = '';
254 if ( $params['recreate'] ) {
255 $requestArray['wpRecreate'] = '';
258 if ( !is_null( $params['section'] ) ) {
259 $section = intval( $params['section'] );
260 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
261 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
263 $requestArray['wpSection'] = $params['section'];
265 $requestArray['wpSection'] = '';
268 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
270 // Deprecated parameters
271 if ( $params['watch'] ) {
273 } elseif ( $params['unwatch'] ) {
278 $requestArray['wpWatchthis'] = '';
281 global $wgTitle, $wgRequest;
283 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
285 // Some functions depend on $wgTitle == $ep->mTitle
286 // TODO: Make them not or check if they still do
287 $wgTitle = $titleObj;
289 $articleObject = new Article( $titleObj );
290 $ep = new EditPage( $articleObject );
292 $ep->setContextTitle( $titleObj );
293 $ep->importFormData( $req );
296 // Handle APIEditBeforeSave parameters
298 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
300 $r['result'] = 'Failure';
301 $apiResult->addValue( null, $this->getModuleName(), $r );
304 $this->dieUsageMsg( 'hookaborted' );
308 // Do the actual save
309 $oldRevId = $articleObject->getRevIdFetched();
311 // Fake $wgRequest for some hooks inside EditPage
312 // @todo FIXME: This interface SUCKS
313 $oldRequest = $wgRequest;
316 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
317 $wgRequest = $oldRequest;
318 global $wgMaxArticleSize;
320 switch( $status->value
) {
321 case EditPage
::AS_HOOK_ERROR
:
322 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
323 $this->dieUsageMsg( 'hookaborted' );
325 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
326 $this->dieUsageMsg( 'noimageredirect-anon' );
328 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
329 $this->dieUsageMsg( 'noimageredirect-logged' );
331 case EditPage
::AS_SPAM_ERROR
:
332 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
334 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
335 $this->dieUsageMsg( 'blockedtext' );
337 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
338 case EditPage
::AS_CONTENT_TOO_BIG
:
339 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
341 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
342 $this->dieUsageMsg( 'noedit-anon' );
344 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
345 $this->dieUsageMsg( 'noedit' );
347 case EditPage
::AS_READ_ONLY_PAGE
:
348 $this->dieReadOnly();
350 case EditPage
::AS_RATE_LIMITED
:
351 $this->dieUsageMsg( 'actionthrottledtext' );
353 case EditPage
::AS_ARTICLE_WAS_DELETED
:
354 $this->dieUsageMsg( 'wasdeleted' );
356 case EditPage
::AS_NO_CREATE_PERMISSION
:
357 $this->dieUsageMsg( 'nocreate-loggedin' );
359 case EditPage
::AS_BLANK_ARTICLE
:
360 $this->dieUsageMsg( 'blankpage' );
362 case EditPage
::AS_CONFLICT_DETECTED
:
363 $this->dieUsageMsg( 'editconflict' );
365 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
366 case EditPage
::AS_TEXTBOX_EMPTY
:
367 $this->dieUsageMsg( 'emptynewsection' );
369 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
372 case EditPage
::AS_SUCCESS_UPDATE
:
373 $r['result'] = 'Success';
374 $r['pageid'] = intval( $titleObj->getArticleID() );
375 $r['title'] = $titleObj->getPrefixedText();
376 $r['contentmodel'] = $titleObj->getContentModel();
377 $newRevId = $articleObject->getLatest();
378 if ( $newRevId == $oldRevId ) {
381 $r['oldrevid'] = intval( $oldRevId );
382 $r['newrevid'] = intval( $newRevId );
383 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
384 $pageObj->getTimestamp() );
388 case EditPage
::AS_SUMMARY_NEEDED
:
389 $this->dieUsageMsg( 'summaryrequired' );
391 case EditPage
::AS_END
:
393 // $status came from WikiPage::doEdit()
394 $errors = $status->getErrorsArray();
395 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
398 $apiResult->addValue( null, $this->getModuleName(), $r );
401 public function mustBePosted() {
405 public function isWriteMode() {
409 public function getDescription() {
410 return 'Create and edit pages.';
413 public function getPossibleErrors() {
414 global $wgMaxArticleSize;
416 return array_merge( parent
::getPossibleErrors(),
417 $this->getTitleOrPageIdErrorMessage(),
419 array( 'missingtext' ),
420 array( 'createonly-exists' ),
421 array( 'nocreate-missing' ),
422 array( 'nosuchrevid', 'undo' ),
423 array( 'nosuchrevid', 'undoafter' ),
424 array( 'revwrongpage', 'id', 'text' ),
425 array( 'undo-failure' ),
426 array( 'hashcheckfailed' ),
427 array( 'hookaborted' ),
428 array( 'noimageredirect-anon' ),
429 array( 'noimageredirect-logged' ),
430 array( 'spamdetected', 'spam' ),
431 array( 'summaryrequired' ),
432 array( 'blockedtext' ),
433 array( 'contenttoobig', $wgMaxArticleSize ),
434 array( 'noedit-anon' ),
436 array( 'actionthrottledtext' ),
437 array( 'wasdeleted' ),
438 array( 'nocreate-loggedin' ),
439 array( 'blankpage' ),
440 array( 'editconflict' ),
441 array( 'emptynewsection' ),
442 array( 'unknownerror', 'retval' ),
443 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
444 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
445 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
446 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using '
447 . 'the text based edit API.' ),
448 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending '
449 . 'or prepending text.' ),
450 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to '
451 . 'the page\'s content model' ),
452 array( 'customcssprotected' ),
453 array( 'customjsprotected' ),
458 public function getAllowedParams() {
461 ApiBase
::PARAM_TYPE
=> 'string',
464 ApiBase
::PARAM_TYPE
=> 'integer',
467 'sectiontitle' => array(
468 ApiBase
::PARAM_TYPE
=> 'string',
469 ApiBase
::PARAM_REQUIRED
=> false,
473 ApiBase
::PARAM_TYPE
=> 'string',
474 ApiBase
::PARAM_REQUIRED
=> true
480 'basetimestamp' => null,
481 'starttimestamp' => null,
483 'createonly' => false,
486 ApiBase
::PARAM_DFLT
=> false,
487 ApiBase
::PARAM_DEPRECATED
=> true,
490 ApiBase
::PARAM_DFLT
=> false,
491 ApiBase
::PARAM_DEPRECATED
=> true,
493 'watchlist' => array(
494 ApiBase
::PARAM_DFLT
=> 'preferences',
495 ApiBase
::PARAM_TYPE
=> array(
503 'prependtext' => null,
504 'appendtext' => null,
506 ApiBase
::PARAM_TYPE
=> 'integer'
508 'undoafter' => array(
509 ApiBase
::PARAM_TYPE
=> 'integer'
512 ApiBase
::PARAM_TYPE
=> 'boolean',
513 ApiBase
::PARAM_DFLT
=> false,
518 public function getParamDescription() {
519 $p = $this->getModulePrefix();
521 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
522 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
523 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
524 'sectiontitle' => 'The title for a new section',
525 'text' => 'Page content',
526 'token' => array( 'Edit token. You can get one of these through prop=info.',
527 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
529 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
530 'minor' => 'Minor edit',
531 'notminor' => 'Non-minor edit',
532 'bot' => 'Mark this edit as bot',
533 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
534 'Used to detect edit conflicts; leave unset to ignore conflicts'
536 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
537 'Used to detect edit conflicts; leave unset to ignore conflicts'
539 'recreate' => 'Override any errors about the article having been deleted in the meantime',
540 'createonly' => 'Don\'t edit the page if it exists already',
541 'nocreate' => 'Throw an error if the page doesn\'t exist',
542 'watch' => 'Add the page to your watchlist',
543 'unwatch' => 'Remove the page from your watchlist',
544 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
545 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
546 'If set, the edit won\'t be done unless the hash is correct' ),
547 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
548 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
549 "Use {$p}section=new to append a new section" ),
550 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
551 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
552 'redirect' => 'Automatically resolve redirects',
556 public function getResultProperties() {
561 ApiBase
::PROP_TYPE
=> array(
567 ApiBase
::PROP_TYPE
=> 'integer',
568 ApiBase
::PROP_NULLABLE
=> true
571 ApiBase
::PROP_TYPE
=> 'string',
572 ApiBase
::PROP_NULLABLE
=> true
574 'nochange' => 'boolean',
576 ApiBase
::PROP_TYPE
=> 'integer',
577 ApiBase
::PROP_NULLABLE
=> true
580 ApiBase
::PROP_TYPE
=> 'integer',
581 ApiBase
::PROP_NULLABLE
=> true
583 'newtimestamp' => array(
584 ApiBase
::PROP_TYPE
=> 'string',
585 ApiBase
::PROP_NULLABLE
=> true
591 public function needsToken() {
595 public function getTokenSalt() {
599 public function getExamples() {
602 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
603 => 'Edit a page (anonymous user)',
605 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
606 => 'Prepend __NOTOC__ to a page (anonymous user)',
607 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
608 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
612 public function getHelpUrls() {
613 return 'https://www.mediawiki.org/wiki/API:Edit';
616 public function getVersion() {
617 return __CLASS__
. ': $Id$';