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
{
35 public function execute() {
36 $user = $this->getUser();
37 $params = $this->extractRequestParams();
39 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
40 is_null( $params['prependtext'] ) &&
43 $this->dieUsageMsg( 'missingtext' );
46 $pageObj = $this->getTitleOrPageId( $params );
47 $titleObj = $pageObj->getTitle();
48 $apiResult = $this->getResult();
50 if ( $params['redirect'] ) {
51 if ( $params['prependtext'] === null && $params['appendtext'] === null
52 && $params['section'] !== 'new'
54 $this->dieUsage( 'You have attempted to edit using the "redirect"-following'
55 . ' mode, which must be used in conjuction with section=new, prependtext'
56 . ', or appendtext.', 'redirect-appendonly' );
58 if ( $titleObj->isRedirect() ) {
59 $oldTitle = $titleObj;
61 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
62 ->getContent( Revision
::FOR_THIS_USER
, $user )
64 // array_shift( $titles );
66 $redirValues = array();
68 /** @var $newTitle Title */
69 foreach ( $titles as $id => $newTitle ) {
71 if ( !isset( $titles[$id - 1] ) ) {
72 $titles[$id - 1] = $oldTitle;
75 $redirValues[] = array(
76 'from' => $titles[$id - 1]->getPrefixedText(),
77 'to' => $newTitle->getPrefixedText()
80 $titleObj = $newTitle;
83 $apiResult->setIndexedTagName( $redirValues, 'r' );
84 $apiResult->addValue( null, 'redirects', $redirValues );
86 // Since the page changed, update $pageObj
87 $pageObj = WikiPage
::factory( $titleObj );
91 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
92 $contentHandler = $pageObj->getContentHandler();
94 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
97 // @todo Ask handler whether direct editing is supported at all! make
98 // allowFlatEdit() method or some such
100 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
101 $params['contentformat'] = $contentHandler->getDefaultFormat();
104 $contentFormat = $params['contentformat'];
106 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
107 $name = $titleObj->getPrefixedDBkey();
108 $model = $contentHandler->getModelID();
110 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
111 " $model used by $name", 'badformat' );
114 if ( $params['createonly'] && $titleObj->exists() ) {
115 $this->dieUsageMsg( 'createonly-exists' );
117 if ( $params['nocreate'] && !$titleObj->exists() ) {
118 $this->dieUsageMsg( 'nocreate-missing' );
121 // Now let's check whether we're even allowed to do this
122 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
123 if ( !$titleObj->exists() ) {
124 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
126 if ( count( $errors ) ) {
127 $this->dieUsageMsg( $errors[0] );
130 $toMD5 = $params['text'];
131 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
132 $content = $pageObj->getContent();
135 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
136 # If this is a MediaWiki:x message, then load the messages
137 # and return the message value for x.
138 $text = $titleObj->getDefaultMessageText();
139 if ( $text === false ) {
144 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
145 } catch ( MWContentSerializationException
$ex ) {
146 $this->dieUsage( $ex->getMessage(), 'parseerror' );
151 # Otherwise, make a new empty content.
152 $content = $contentHandler->makeEmptyContent();
156 // @todo Add support for appending/prepending to the Content interface
158 if ( !( $content instanceof TextContent
) ) {
159 $mode = $contentHandler->getModelID();
160 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
163 if ( !is_null( $params['section'] ) ) {
164 if ( !$contentHandler->supportsSections() ) {
165 $modelName = $contentHandler->getModelID();
167 "Sections are not supported for this content model: $modelName.",
168 'sectionsnotsupported'
172 if ( $params['section'] == 'new' ) {
173 // DWIM if they're trying to prepend/append to a new section.
176 // Process the content for section edits
177 $section = $params['section'];
178 $content = $content->getSection( $section );
181 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
189 $text = $content->serialize( $contentFormat );
192 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
193 $toMD5 = $params['prependtext'] . $params['appendtext'];
196 if ( $params['undo'] > 0 ) {
197 if ( $params['undoafter'] > 0 ) {
198 if ( $params['undo'] < $params['undoafter'] ) {
199 list( $params['undo'], $params['undoafter'] ) =
200 array( $params['undoafter'], $params['undo'] );
202 $undoafterRev = Revision
::newFromId( $params['undoafter'] );
204 $undoRev = Revision
::newFromId( $params['undo'] );
205 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
206 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
209 if ( $params['undoafter'] == 0 ) {
210 $undoafterRev = $undoRev->getPrevious();
212 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
213 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
216 if ( $undoRev->getPage() != $pageObj->getID() ) {
217 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
218 $titleObj->getPrefixedText() ) );
220 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
221 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
222 $titleObj->getPrefixedText() ) );
225 $newContent = $contentHandler->getUndoContent(
226 $pageObj->getRevision(),
231 if ( !$newContent ) {
232 $this->dieUsageMsg( 'undo-failure' );
235 $params['text'] = $newContent->serialize( $params['contentformat'] );
237 // If no summary was given and we only undid one rev,
238 // use an autosummary
239 if ( is_null( $params['summary'] ) &&
240 $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo']
242 $params['summary'] = wfMessage( 'undo-summary' )
243 ->params ( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
247 // See if the MD5 hash checks out
248 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
249 $this->dieUsageMsg( 'hashcheckfailed' );
252 // EditPage wants to parse its stuff from a WebRequest
253 // That interface kind of sucks, but it's workable
254 $requestArray = array(
255 'wpTextbox1' => $params['text'],
256 'format' => $contentFormat,
257 'model' => $contentHandler->getModelID(),
258 'wpEditToken' => $params['token'],
259 'wpIgnoreBlankSummary' => true,
260 'wpIgnoreBlankArticle' => true,
261 'wpIgnoreSelfRedirect' => true,
262 'bot' => $params['bot'],
265 if ( !is_null( $params['summary'] ) ) {
266 $requestArray['wpSummary'] = $params['summary'];
269 if ( !is_null( $params['sectiontitle'] ) ) {
270 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
273 // TODO: Pass along information from 'undoafter' as well
274 if ( $params['undo'] > 0 ) {
275 $requestArray['wpUndidRevision'] = $params['undo'];
278 // Watch out for basetimestamp == ''
279 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
280 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
281 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
283 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
286 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
287 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
289 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
292 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
293 $requestArray['wpMinoredit'] = '';
296 if ( $params['recreate'] ) {
297 $requestArray['wpRecreate'] = '';
300 if ( !is_null( $params['section'] ) ) {
301 $section = $params['section'];
302 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
303 $this->dieUsage( "The section parameter must be a valid section id or 'new'",
306 $content = $pageObj->getContent();
307 if ( $section !== '0' && $section != 'new'
308 && ( !$content ||
!$content->getSection( $section ) )
310 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
312 $requestArray['wpSection'] = $params['section'];
314 $requestArray['wpSection'] = '';
317 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
319 // Deprecated parameters
320 if ( $params['watch'] ) {
321 $this->logFeatureUsage( 'action=edit&watch' );
323 } elseif ( $params['unwatch'] ) {
324 $this->logFeatureUsage( 'action=edit&unwatch' );
329 $requestArray['wpWatchthis'] = '';
332 // Pass through anything else we might have been given, to support extensions
333 // This is kind of a hack but it's the best we can do to make extensions work
334 $requestArray +
= $this->getRequest()->getValues();
336 global $wgTitle, $wgRequest;
338 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
340 // Some functions depend on $wgTitle == $ep->mTitle
341 // TODO: Make them not or check if they still do
342 $wgTitle = $titleObj;
344 $articleContext = new RequestContext
;
345 $articleContext->setRequest( $req );
346 $articleContext->setWikiPage( $pageObj );
347 $articleContext->setUser( $this->getUser() );
349 /** @var $articleObject Article */
350 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
352 $ep = new EditPage( $articleObject );
354 // allow editing of non-textual content.
355 $ep->allowNonTextContent
= true;
357 $ep->setContextTitle( $titleObj );
358 $ep->importFormData( $req );
359 $content = $ep->textbox1
;
361 // The following is needed to give the hook the full content of the
362 // new revision rather than just the current section. (Bug 52077)
363 if ( !is_null( $params['section'] ) &&
364 $contentHandler->supportsSections() && $titleObj->exists()
366 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
367 // backwards compatibility with old forms/bots).
368 if ( $ep->sectiontitle
!== '' ) {
369 $sectionTitle = $ep->sectiontitle
;
371 $sectionTitle = $ep->summary
;
374 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
376 $fullContentObj = $articleObject->replaceSectionContent(
381 if ( $fullContentObj ) {
382 $content = $fullContentObj->serialize( $contentFormat );
384 // This most likely means we have an edit conflict which means that the edit
385 // wont succeed anyway.
386 $this->dieUsageMsg( 'editconflict' );
391 // Handle APIEditBeforeSave parameters
393 if ( !Hooks
::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
395 $r['result'] = 'Failure';
396 $apiResult->addValue( null, $this->getModuleName(), $r );
401 $this->dieUsageMsg( 'hookaborted' );
404 // Do the actual save
405 $oldRevId = $articleObject->getRevIdFetched();
407 // Fake $wgRequest for some hooks inside EditPage
408 // @todo FIXME: This interface SUCKS
409 $oldRequest = $wgRequest;
412 $status = $ep->attemptSave( $result );
413 $wgRequest = $oldRequest;
415 switch ( $status->value
) {
416 case EditPage
::AS_HOOK_ERROR
:
417 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
418 if ( isset( $status->apiHookResult
) ) {
419 $r = $status->apiHookResult
;
420 $r['result'] = 'Failure';
421 $apiResult->addValue( null, $this->getModuleName(), $r );
424 $this->dieUsageMsg( 'hookaborted' );
427 case EditPage
::AS_PARSE_ERROR
:
428 $this->dieUsage( $status->getMessage(), 'parseerror' );
430 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
431 $this->dieUsageMsg( 'noimageredirect-anon' );
433 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
434 $this->dieUsageMsg( 'noimageredirect-logged' );
436 case EditPage
::AS_SPAM_ERROR
:
437 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
439 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
440 $this->dieUsageMsg( 'blockedtext' );
442 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
443 case EditPage
::AS_CONTENT_TOO_BIG
:
444 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
446 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
447 $this->dieUsageMsg( 'noedit-anon' );
449 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
450 $this->dieUsageMsg( 'noedit' );
452 case EditPage
::AS_READ_ONLY_PAGE
:
453 $this->dieReadOnly();
455 case EditPage
::AS_RATE_LIMITED
:
456 $this->dieUsageMsg( 'actionthrottledtext' );
458 case EditPage
::AS_ARTICLE_WAS_DELETED
:
459 $this->dieUsageMsg( 'wasdeleted' );
461 case EditPage
::AS_NO_CREATE_PERMISSION
:
462 $this->dieUsageMsg( 'nocreate-loggedin' );
464 case EditPage
::AS_NO_CHANGE_CONTENT_MODEL
:
465 $this->dieUsageMsg( 'cantchangecontentmodel' );
467 case EditPage
::AS_BLANK_ARTICLE
:
468 $this->dieUsageMsg( 'blankpage' );
470 case EditPage
::AS_CONFLICT_DETECTED
:
471 $this->dieUsageMsg( 'editconflict' );
473 case EditPage
::AS_TEXTBOX_EMPTY
:
474 $this->dieUsageMsg( 'emptynewsection' );
476 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
480 case EditPage
::AS_SUCCESS_UPDATE
:
481 $r['result'] = 'Success';
482 $r['pageid'] = intval( $titleObj->getArticleID() );
483 $r['title'] = $titleObj->getPrefixedText();
484 $r['contentmodel'] = $titleObj->getContentModel();
485 $newRevId = $articleObject->getLatest();
486 if ( $newRevId == $oldRevId ) {
489 $r['oldrevid'] = intval( $oldRevId );
490 $r['newrevid'] = intval( $newRevId );
491 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
492 $pageObj->getTimestamp() );
496 case EditPage
::AS_SUMMARY_NEEDED
:
497 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
498 $this->dieUsageMsg( 'summaryrequired' );
500 case EditPage
::AS_END
:
502 // $status came from WikiPage::doEdit()
503 $errors = $status->getErrorsArray();
504 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
507 $apiResult->addValue( null, $this->getModuleName(), $r );
510 public function mustBePosted() {
514 public function isWriteMode() {
518 public function getAllowedParams() {
521 ApiBase
::PARAM_TYPE
=> 'string',
524 ApiBase
::PARAM_TYPE
=> 'integer',
527 'sectiontitle' => array(
528 ApiBase
::PARAM_TYPE
=> 'string',
535 'basetimestamp' => null,
536 'starttimestamp' => null,
538 'createonly' => false,
541 ApiBase
::PARAM_DFLT
=> false,
542 ApiBase
::PARAM_DEPRECATED
=> true,
545 ApiBase
::PARAM_DFLT
=> false,
546 ApiBase
::PARAM_DEPRECATED
=> true,
548 'watchlist' => array(
549 ApiBase
::PARAM_DFLT
=> 'preferences',
550 ApiBase
::PARAM_TYPE
=> array(
558 'prependtext' => null,
559 'appendtext' => null,
561 ApiBase
::PARAM_TYPE
=> 'integer'
563 'undoafter' => array(
564 ApiBase
::PARAM_TYPE
=> 'integer'
567 ApiBase
::PARAM_TYPE
=> 'boolean',
568 ApiBase
::PARAM_DFLT
=> false,
570 'contentformat' => array(
571 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
573 'contentmodel' => array(
574 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
577 // Standard definition automatically inserted
578 ApiBase
::PARAM_HELP_MSG_APPEND
=> array( 'apihelp-edit-param-token' ),
583 public function needsToken() {
587 protected function getExamplesMessages() {
589 'action=edit&title=Test&summary=test%20summary&' .
590 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
591 => 'apihelp-edit-example-edit',
592 'action=edit&title=Test&summary=NOTOC&minor=&' .
593 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
594 => 'apihelp-edit-example-prepend',
595 'action=edit&title=Test&undo=13585&undoafter=13579&' .
596 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
597 => 'apihelp-edit-example-undo',
601 public function getHelpUrls() {
602 return 'https://www.mediawiki.org/wiki/API:Edit';