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 $titleObj = $this->getTitleOrPageId( $params );
52 if ( $titleObj->isExternal() ) {
53 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
56 $apiResult = $this->getResult();
58 if ( $params['redirect'] ) {
59 if ( $titleObj->isRedirect() ) {
60 $oldTitle = $titleObj;
62 $titles = Title
::newFromRedirectArray( Revision
::newFromTitle( $oldTitle )->getText( Revision
::FOR_THIS_USER
) );
63 // array_shift( $titles );
65 $redirValues = array();
66 foreach ( $titles as $id => $newTitle ) {
68 if ( !isset( $titles[ $id - 1 ] ) ) {
69 $titles[ $id - 1 ] = $oldTitle;
72 $redirValues[] = array(
73 'from' => $titles[ $id - 1 ]->getPrefixedText(),
74 'to' => $newTitle->getPrefixedText()
77 $titleObj = $newTitle;
80 $apiResult->setIndexedTagName( $redirValues, 'r' );
81 $apiResult->addValue( null, 'redirects', $redirValues );
85 if ( $params['createonly'] && $titleObj->exists() ) {
86 $this->dieUsageMsg( 'createonly-exists' );
88 if ( $params['nocreate'] && !$titleObj->exists() ) {
89 $this->dieUsageMsg( 'nocreate-missing' );
92 // Now let's check whether we're even allowed to do this
93 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
94 if ( !$titleObj->exists() ) {
95 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
97 if ( count( $errors ) ) {
98 $this->dieUsageMsg( $errors[0] );
101 $articleObj = Article
::newFromTitle( $titleObj, $this->getContext() );
103 $toMD5 = $params['text'];
104 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
106 // For non-existent pages, Article::getContent()
107 // returns an interface message rather than ''
108 // We do want getContent()'s behavior for non-existent
109 // MediaWiki: pages, though
110 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI
) {
113 $content = $articleObj->getContent();
116 if ( !is_null( $params['section'] ) ) {
117 // Process the content for section edits
119 $section = intval( $params['section'] );
120 $content = $wgParser->getSection( $content, $section, false );
121 if ( $content === false ) {
122 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
125 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
126 $toMD5 = $params['prependtext'] . $params['appendtext'];
129 if ( $params['undo'] > 0 ) {
130 if ( $params['undoafter'] > 0 ) {
131 if ( $params['undo'] < $params['undoafter'] ) {
132 list( $params['undo'], $params['undoafter'] ) =
133 array( $params['undoafter'], $params['undo'] );
135 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
137 $undoRev = Revision
::newFromID( $params['undo'] );
138 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
139 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
142 if ( $params['undoafter'] == 0 ) {
143 $undoafterRev = $undoRev->getPrevious();
145 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
146 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
149 if ( $undoRev->getPage() != $articleObj->getID() ) {
150 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
152 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
153 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
156 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
157 if ( $newtext === false ) {
158 $this->dieUsageMsg( 'undo-failure' );
160 $params['text'] = $newtext;
161 // If no summary was given and we only undid one rev,
162 // use an autosummary
163 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
164 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
168 // See if the MD5 hash checks out
169 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
170 $this->dieUsageMsg( 'hashcheckfailed' );
173 // EditPage wants to parse its stuff from a WebRequest
174 // That interface kind of sucks, but it's workable
175 $requestArray = array(
176 'wpTextbox1' => $params['text'],
177 'wpEditToken' => $params['token'],
178 'wpIgnoreBlankSummary' => ''
181 if ( !is_null( $params['summary'] ) ) {
182 $requestArray['wpSummary'] = $params['summary'];
185 if ( !is_null( $params['sectiontitle'] ) ) {
186 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
189 // Watch out for basetimestamp == ''
190 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
191 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
192 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
194 $requestArray['wpEdittime'] = $articleObj->getTimestamp();
197 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
198 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
200 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
203 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
204 $requestArray['wpMinoredit'] = '';
207 if ( $params['recreate'] ) {
208 $requestArray['wpRecreate'] = '';
211 if ( !is_null( $params['section'] ) ) {
212 $section = intval( $params['section'] );
213 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
214 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
216 $requestArray['wpSection'] = $params['section'];
218 $requestArray['wpSection'] = '';
221 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
223 // Deprecated parameters
224 if ( $params['watch'] ) {
226 } elseif ( $params['unwatch'] ) {
231 $requestArray['wpWatchthis'] = '';
234 global $wgTitle, $wgRequest;
236 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
238 // Some functions depend on $wgTitle == $ep->mTitle
239 // TODO: Make them not or check if they still do
240 $wgTitle = $titleObj;
242 $ep = new EditPage( $articleObj );
243 $ep->setContextTitle( $titleObj );
244 $ep->importFormData( $req );
247 // Handle APIEditBeforeSave parameters
249 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
251 $r['result'] = 'Failure';
252 $apiResult->addValue( null, $this->getModuleName(), $r );
255 $this->dieUsageMsg( 'hookaborted' );
259 // Do the actual save
260 $oldRevId = $articleObj->getRevIdFetched();
262 // Fake $wgRequest for some hooks inside EditPage
263 // @todo FIXME: This interface SUCKS
264 $oldRequest = $wgRequest;
267 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
268 $wgRequest = $oldRequest;
269 global $wgMaxArticleSize;
271 switch( $status->value
) {
272 case EditPage
::AS_HOOK_ERROR
:
273 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
274 $this->dieUsageMsg( 'hookaborted' );
276 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
277 $this->dieUsageMsg( 'noimageredirect-anon' );
279 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
280 $this->dieUsageMsg( 'noimageredirect-logged' );
282 case EditPage
::AS_SPAM_ERROR
:
283 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
285 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
286 $this->dieUsageMsg( 'blockedtext' );
288 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
289 case EditPage
::AS_CONTENT_TOO_BIG
:
290 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
292 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
293 $this->dieUsageMsg( 'noedit-anon' );
295 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
296 $this->dieUsageMsg( 'noedit' );
298 case EditPage
::AS_READ_ONLY_PAGE
:
299 $this->dieReadOnly();
301 case EditPage
::AS_RATE_LIMITED
:
302 $this->dieUsageMsg( 'actionthrottledtext' );
304 case EditPage
::AS_ARTICLE_WAS_DELETED
:
305 $this->dieUsageMsg( 'wasdeleted' );
307 case EditPage
::AS_NO_CREATE_PERMISSION
:
308 $this->dieUsageMsg( 'nocreate-loggedin' );
310 case EditPage
::AS_BLANK_ARTICLE
:
311 $this->dieUsageMsg( 'blankpage' );
313 case EditPage
::AS_CONFLICT_DETECTED
:
314 $this->dieUsageMsg( 'editconflict' );
316 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
317 case EditPage
::AS_TEXTBOX_EMPTY
:
318 $this->dieUsageMsg( 'emptynewsection' );
320 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
323 case EditPage
::AS_SUCCESS_UPDATE
:
324 $r['result'] = 'Success';
325 $r['pageid'] = intval( $titleObj->getArticleID() );
326 $r['title'] = $titleObj->getPrefixedText();
327 $newRevId = $articleObj->getLatest();
328 if ( $newRevId == $oldRevId ) {
331 $r['oldrevid'] = intval( $oldRevId );
332 $r['newrevid'] = intval( $newRevId );
333 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
334 $articleObj->getTimestamp() );
338 case EditPage
::AS_SUMMARY_NEEDED
:
339 $this->dieUsageMsg( 'summaryrequired' );
341 case EditPage
::AS_END
:
342 // $status came from WikiPage::doEdit()
343 $errors = $status->getErrorsArray();
344 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
347 if ( is_string( $status->value
) && strlen( $status->value
) ) {
348 $this->dieUsage( "An unknown return value was returned by Editpage. The code returned was \"{$status->value}\"" , $status->value
);
350 $this->dieUsageMsg( array( 'unknownerror', $status->value
) );
353 $apiResult->addValue( null, $this->getModuleName(), $r );
356 public function mustBePosted() {
360 public function isWriteMode() {
364 public function getDescription() {
365 return 'Create and edit pages.';
368 public function getPossibleErrors() {
369 global $wgMaxArticleSize;
371 return array_merge( parent
::getPossibleErrors(),
372 $this->getTitleOrPageIdErrorMessage(),
374 array( 'missingtext' ),
375 array( 'createonly-exists' ),
376 array( 'nocreate-missing' ),
377 array( 'nosuchrevid', 'undo' ),
378 array( 'nosuchrevid', 'undoafter' ),
379 array( 'revwrongpage', 'id', 'text' ),
380 array( 'undo-failure' ),
381 array( 'hashcheckfailed' ),
382 array( 'hookaborted' ),
383 array( 'noimageredirect-anon' ),
384 array( 'noimageredirect-logged' ),
385 array( 'spamdetected', 'spam' ),
386 array( 'summaryrequired' ),
387 array( 'blockedtext' ),
388 array( 'contenttoobig', $wgMaxArticleSize ),
389 array( 'noedit-anon' ),
391 array( 'actionthrottledtext' ),
392 array( 'wasdeleted' ),
393 array( 'nocreate-loggedin' ),
394 array( 'blankpage' ),
395 array( 'editconflict' ),
396 array( 'emptynewsection' ),
397 array( 'unknownerror', 'retval' ),
398 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
399 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
400 array( 'customcssprotected' ),
401 array( 'customjsprotected' ),
406 public function getAllowedParams() {
409 ApiBase
::PARAM_TYPE
=> 'string',
412 ApiBase
::PARAM_TYPE
=> 'integer',
415 'sectiontitle' => array(
416 ApiBase
::PARAM_TYPE
=> 'string',
417 ApiBase
::PARAM_REQUIRED
=> false,
425 'basetimestamp' => null,
426 'starttimestamp' => null,
428 'createonly' => false,
431 ApiBase
::PARAM_DFLT
=> false,
432 ApiBase
::PARAM_DEPRECATED
=> true,
435 ApiBase
::PARAM_DFLT
=> false,
436 ApiBase
::PARAM_DEPRECATED
=> true,
438 'watchlist' => array(
439 ApiBase
::PARAM_DFLT
=> 'preferences',
440 ApiBase
::PARAM_TYPE
=> array(
448 'prependtext' => null,
449 'appendtext' => null,
451 ApiBase
::PARAM_TYPE
=> 'integer'
453 'undoafter' => array(
454 ApiBase
::PARAM_TYPE
=> 'integer'
457 ApiBase
::PARAM_TYPE
=> 'boolean',
458 ApiBase
::PARAM_DFLT
=> false,
463 public function getParamDescription() {
464 $p = $this->getModulePrefix();
466 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
467 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
468 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
469 'sectiontitle' => 'The title for a new section',
470 'text' => 'Page content',
471 'token' => array( 'Edit token. You can get one of these through prop=info.',
472 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
474 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
475 'minor' => 'Minor edit',
476 'notminor' => 'Non-minor edit',
477 'bot' => 'Mark this edit as bot',
478 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
479 'Used to detect edit conflicts; leave unset to ignore conflicts'
481 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
482 'Used to detect edit conflicts; leave unset to ignore conflicts'
484 'recreate' => 'Override any errors about the article having been deleted in the meantime',
485 'createonly' => 'Don\'t edit the page if it exists already',
486 'nocreate' => 'Throw an error if the page doesn\'t exist',
487 'watch' => 'Add the page to your watchlist',
488 'unwatch' => 'Remove the page from your watchlist',
489 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
490 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
491 'If set, the edit won\'t be done unless the hash is correct' ),
492 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
493 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
494 "Use {$p}section=new to append a new section" ),
495 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
496 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
497 'redirect' => 'Automatically resolve redirects',
501 public function needsToken() {
505 public function getTokenSalt() {
509 public function getExamples() {
512 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
513 => 'Edit a page (anonymous user)',
515 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
516 => 'Prepend __NOTOC__ to a page (anonymous user)',
517 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
518 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
522 public function getHelpUrls() {
523 return 'https://www.mediawiki.org/wiki/API:Edit';
526 public function getVersion() {
527 return __CLASS__
. ': $Id$';