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 ( $titleObj->isRedirect() ) {
52 $oldTitle = $titleObj;
54 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
55 ->getContent( Revision
::FOR_THIS_USER
, $user )
57 // array_shift( $titles );
59 $redirValues = array();
61 /** @var $newTitle Title */
62 foreach ( $titles as $id => $newTitle ) {
64 if ( !isset( $titles[$id - 1] ) ) {
65 $titles[$id - 1] = $oldTitle;
68 $redirValues[] = array(
69 'from' => $titles[$id - 1]->getPrefixedText(),
70 'to' => $newTitle->getPrefixedText()
73 $titleObj = $newTitle;
76 $apiResult->setIndexedTagName( $redirValues, 'r' );
77 $apiResult->addValue( null, 'redirects', $redirValues );
79 // Since the page changed, update $pageObj
80 $pageObj = WikiPage
::factory( $titleObj );
84 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
85 $contentHandler = $pageObj->getContentHandler();
87 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
90 // @todo Ask handler whether direct editing is supported at all! make
91 // 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'] ) ) {
125 $content = $pageObj->getContent();
128 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
129 # If this is a MediaWiki:x message, then load the messages
130 # and return the message value for x.
131 $text = $titleObj->getDefaultMessageText();
132 if ( $text === false ) {
137 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
138 } catch ( MWContentSerializationException
$ex ) {
139 $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();
160 "Sections are not supported for this content model: $modelName.",
161 'sectionsnotsupported'
165 if ( $params['section'] == 'new' ) {
166 // DWIM if they're trying to prepend/append to a new section.
169 // Process the content for section edits
170 $section = intval( $params['section'] );
171 $content = $content->getSection( $section );
174 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
182 $text = $content->serialize( $contentFormat );
185 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
186 $toMD5 = $params['prependtext'] . $params['appendtext'];
189 if ( $params['undo'] > 0 ) {
190 if ( $params['undoafter'] > 0 ) {
191 if ( $params['undo'] < $params['undoafter'] ) {
192 list( $params['undo'], $params['undoafter'] ) =
193 array( $params['undoafter'], $params['undo'] );
195 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
197 $undoRev = Revision
::newFromID( $params['undo'] );
198 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
199 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
202 if ( $params['undoafter'] == 0 ) {
203 $undoafterRev = $undoRev->getPrevious();
205 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
206 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
209 if ( $undoRev->getPage() != $pageObj->getID() ) {
210 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
211 $titleObj->getPrefixedText() ) );
213 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
214 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
215 $titleObj->getPrefixedText() ) );
218 $newContent = $contentHandler->getUndoContent(
219 $pageObj->getRevision(),
224 if ( !$newContent ) {
225 $this->dieUsageMsg( 'undo-failure' );
228 $params['text'] = $newContent->serialize( $params['contentformat'] );
230 // If no summary was given and we only undid one rev,
231 // use an autosummary
232 if ( is_null( $params['summary'] ) &&
233 $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo']
235 $params['summary'] = wfMessage( 'undo-summary' )
236 ->params ( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
240 // See if the MD5 hash checks out
241 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
242 $this->dieUsageMsg( 'hashcheckfailed' );
245 // EditPage wants to parse its stuff from a WebRequest
246 // That interface kind of sucks, but it's workable
247 $requestArray = array(
248 'wpTextbox1' => $params['text'],
249 'format' => $contentFormat,
250 'model' => $contentHandler->getModelID(),
251 'wpEditToken' => $params['token'],
252 'wpIgnoreBlankSummary' => ''
255 if ( !is_null( $params['summary'] ) ) {
256 $requestArray['wpSummary'] = $params['summary'];
259 if ( !is_null( $params['sectiontitle'] ) ) {
260 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
263 // TODO: Pass along information from 'undoafter' as well
264 if ( $params['undo'] > 0 ) {
265 $requestArray['wpUndidRevision'] = $params['undo'];
268 // Watch out for basetimestamp == ''
269 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
270 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
271 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
273 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
276 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
277 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
279 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
282 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
283 $requestArray['wpMinoredit'] = '';
286 if ( $params['recreate'] ) {
287 $requestArray['wpRecreate'] = '';
290 if ( !is_null( $params['section'] ) ) {
291 $section = intval( $params['section'] );
292 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
293 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
295 $content = $pageObj->getContent();
296 if ( $section !== 0 && ( !$content ||
!$content->getSection( $section ) ) ) {
297 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
299 $requestArray['wpSection'] = $params['section'];
301 $requestArray['wpSection'] = '';
304 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
306 // Deprecated parameters
307 if ( $params['watch'] ) {
309 } elseif ( $params['unwatch'] ) {
314 $requestArray['wpWatchthis'] = '';
317 // Pass through anything else we might have been given, to support extensions
318 // This is kind of a hack but it's the best we can do to make extensions work
319 $requestArray +
= $this->getRequest()->getValues();
321 global $wgTitle, $wgRequest;
323 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
325 // Some functions depend on $wgTitle == $ep->mTitle
326 // TODO: Make them not or check if they still do
327 $wgTitle = $titleObj;
329 $articleContext = new RequestContext
;
330 $articleContext->setRequest( $req );
331 $articleContext->setWikiPage( $pageObj );
332 $articleContext->setUser( $this->getUser() );
334 /** @var $articleObject Article */
335 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
337 $ep = new EditPage( $articleObject );
339 // allow editing of non-textual content.
340 $ep->allowNonTextContent
= true;
342 $ep->setContextTitle( $titleObj );
343 $ep->importFormData( $req );
344 $content = $ep->textbox1
;
346 // The following is needed to give the hook the full content of the
347 // new revision rather than just the current section. (Bug 52077)
348 if ( !is_null( $params['section'] ) &&
349 $contentHandler->supportsSections() && $titleObj->exists()
351 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
352 // backwards compatibility with old forms/bots).
353 if ( $ep->sectiontitle
!== '' ) {
354 $sectionTitle = $ep->sectiontitle
;
356 $sectionTitle = $ep->summary
;
359 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
361 $fullContentObj = $articleObject->replaceSectionContent(
366 if ( $fullContentObj ) {
367 $content = $fullContentObj->serialize( $contentFormat );
369 // This most likely means we have an edit conflict which means that the edit
370 // wont succeed anyway.
371 $this->dieUsageMsg( 'editconflict' );
376 // Handle APIEditBeforeSave parameters
378 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
380 $r['result'] = 'Failure';
381 $apiResult->addValue( null, $this->getModuleName(), $r );
386 $this->dieUsageMsg( 'hookaborted' );
389 // Do the actual save
390 $oldRevId = $articleObject->getRevIdFetched();
392 // Fake $wgRequest for some hooks inside EditPage
393 // @todo FIXME: This interface SUCKS
394 $oldRequest = $wgRequest;
397 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
398 $wgRequest = $oldRequest;
399 global $wgMaxArticleSize;
401 switch ( $status->value
) {
402 case EditPage
::AS_HOOK_ERROR
:
403 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
404 $this->dieUsageMsg( 'hookaborted' );
406 case EditPage
::AS_PARSE_ERROR
:
407 $this->dieUsage( $status->getMessage(), 'parseerror' );
409 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
410 $this->dieUsageMsg( 'noimageredirect-anon' );
412 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
413 $this->dieUsageMsg( 'noimageredirect-logged' );
415 case EditPage
::AS_SPAM_ERROR
:
416 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
418 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
419 $this->dieUsageMsg( 'blockedtext' );
421 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
422 case EditPage
::AS_CONTENT_TOO_BIG
:
423 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
425 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
426 $this->dieUsageMsg( 'noedit-anon' );
428 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
429 $this->dieUsageMsg( 'noedit' );
431 case EditPage
::AS_READ_ONLY_PAGE
:
432 $this->dieReadOnly();
434 case EditPage
::AS_RATE_LIMITED
:
435 $this->dieUsageMsg( 'actionthrottledtext' );
437 case EditPage
::AS_ARTICLE_WAS_DELETED
:
438 $this->dieUsageMsg( 'wasdeleted' );
440 case EditPage
::AS_NO_CREATE_PERMISSION
:
441 $this->dieUsageMsg( 'nocreate-loggedin' );
443 case EditPage
::AS_BLANK_ARTICLE
:
444 $this->dieUsageMsg( 'blankpage' );
446 case EditPage
::AS_CONFLICT_DETECTED
:
447 $this->dieUsageMsg( 'editconflict' );
449 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
450 case EditPage
::AS_TEXTBOX_EMPTY
:
451 $this->dieUsageMsg( 'emptynewsection' );
453 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
457 case EditPage
::AS_SUCCESS_UPDATE
:
458 $r['result'] = 'Success';
459 $r['pageid'] = intval( $titleObj->getArticleID() );
460 $r['title'] = $titleObj->getPrefixedText();
461 $r['contentmodel'] = $titleObj->getContentModel();
462 $newRevId = $articleObject->getLatest();
463 if ( $newRevId == $oldRevId ) {
466 $r['oldrevid'] = intval( $oldRevId );
467 $r['newrevid'] = intval( $newRevId );
468 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
469 $pageObj->getTimestamp() );
473 case EditPage
::AS_SUMMARY_NEEDED
:
474 $this->dieUsageMsg( 'summaryrequired' );
476 case EditPage
::AS_END
:
478 // $status came from WikiPage::doEdit()
479 $errors = $status->getErrorsArray();
480 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
483 $apiResult->addValue( null, $this->getModuleName(), $r );
486 public function mustBePosted() {
490 public function isWriteMode() {
494 public function getDescription() {
495 return 'Create and edit pages.';
498 public function getPossibleErrors() {
499 global $wgMaxArticleSize;
501 return array_merge( parent
::getPossibleErrors(),
502 $this->getTitleOrPageIdErrorMessage(),
504 array( 'missingtext' ),
505 array( 'createonly-exists' ),
506 array( 'nocreate-missing' ),
507 array( 'nosuchrevid', 'undo' ),
508 array( 'nosuchrevid', 'undoafter' ),
509 array( 'revwrongpage', 'id', 'text' ),
510 array( 'undo-failure' ),
511 array( 'hashcheckfailed' ),
512 array( 'hookaborted' ),
513 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
514 array( 'noimageredirect-anon' ),
515 array( 'noimageredirect-logged' ),
516 array( 'spamdetected', 'spam' ),
517 array( 'summaryrequired' ),
518 array( 'blockedtext' ),
519 array( 'contenttoobig', $wgMaxArticleSize ),
520 array( 'noedit-anon' ),
522 array( 'actionthrottledtext' ),
523 array( 'wasdeleted' ),
524 array( 'nocreate-loggedin' ),
525 array( 'blankpage' ),
526 array( 'editconflict' ),
527 array( 'emptynewsection' ),
528 array( 'unknownerror', 'retval' ),
529 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
531 'code' => 'invalidsection',
532 'info' => 'The section parameter must be set to an integer or \'new\''
535 'code' => 'sectionsnotsupported',
536 'info' => 'Sections are not supported for this type of page.'
539 'code' => 'editnotsupported',
540 'info' => 'Editing of this type of page is not supported using the text based edit API.'
543 'code' => 'appendnotsupported',
544 'info' => 'This type of page can not be edited by appending or prepending text.' ),
546 'code' => 'badformat',
547 'info' => 'The requested serialization format can not be applied to the page\'s content model'
549 array( 'customcssprotected' ),
550 array( 'customjsprotected' ),
555 public function getAllowedParams() {
558 ApiBase
::PARAM_TYPE
=> 'string',
561 ApiBase
::PARAM_TYPE
=> 'integer',
564 'sectiontitle' => array(
565 ApiBase
::PARAM_TYPE
=> 'string',
569 ApiBase
::PARAM_TYPE
=> 'string',
570 ApiBase
::PARAM_REQUIRED
=> true
576 'basetimestamp' => null,
577 'starttimestamp' => null,
579 'createonly' => false,
582 ApiBase
::PARAM_DFLT
=> false,
583 ApiBase
::PARAM_DEPRECATED
=> true,
586 ApiBase
::PARAM_DFLT
=> false,
587 ApiBase
::PARAM_DEPRECATED
=> true,
589 'watchlist' => array(
590 ApiBase
::PARAM_DFLT
=> 'preferences',
591 ApiBase
::PARAM_TYPE
=> array(
599 'prependtext' => null,
600 'appendtext' => null,
602 ApiBase
::PARAM_TYPE
=> 'integer'
604 'undoafter' => array(
605 ApiBase
::PARAM_TYPE
=> 'integer'
608 ApiBase
::PARAM_TYPE
=> 'boolean',
609 ApiBase
::PARAM_DFLT
=> false,
611 'contentformat' => array(
612 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
614 'contentmodel' => array(
615 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
620 public function getParamDescription() {
621 $p = $this->getModulePrefix();
624 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
625 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
626 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
627 'sectiontitle' => 'The title for a new section',
628 'text' => 'Page content',
630 'Edit token. You can get one of these through prop=info.',
631 "The token should always be sent as the last parameter, or at " .
632 "least, after the {$p}text parameter"
635 => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
636 'minor' => 'Minor edit',
637 'notminor' => 'Non-minor edit',
638 'bot' => 'Mark this edit as bot',
639 'basetimestamp' => array(
640 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
641 'Used to detect edit conflicts; leave unset to ignore conflicts'
643 'starttimestamp' => array(
644 'Timestamp when you obtained the edit token.',
645 'Used to detect edit conflicts; leave unset to ignore conflicts'
647 'recreate' => 'Override any errors about the article having been deleted in the meantime',
648 'createonly' => 'Don\'t edit the page if it exists already',
649 'nocreate' => 'Throw an error if the page doesn\'t exist',
650 'watch' => 'Add the page to your watchlist',
651 'unwatch' => 'Remove the page from your watchlist',
652 'watchlist' => 'Unconditionally add or remove the page from your ' .
653 'watchlist, use preferences or do not change watch',
655 "The MD5 hash of the {$p}text parameter, or the {$p}prependtext " .
656 "and {$p}appendtext parameters concatenated.",
657 'If set, the edit won\'t be done unless the hash is correct'
659 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
660 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
661 "Use {$p}section=new to append a new section" ),
662 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
663 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
664 'redirect' => 'Automatically resolve redirects',
665 'contentformat' => 'Content serialization format used for the input text',
666 'contentmodel' => 'Content model of the new content',
670 public function getResultProperties() {
675 ApiBase
::PROP_TYPE
=> array(
681 ApiBase
::PROP_TYPE
=> 'integer',
682 ApiBase
::PROP_NULLABLE
=> true
685 ApiBase
::PROP_TYPE
=> 'string',
686 ApiBase
::PROP_NULLABLE
=> true
688 'nochange' => 'boolean',
690 ApiBase
::PROP_TYPE
=> 'integer',
691 ApiBase
::PROP_NULLABLE
=> true
694 ApiBase
::PROP_TYPE
=> 'integer',
695 ApiBase
::PROP_NULLABLE
=> true
697 'newtimestamp' => array(
698 ApiBase
::PROP_TYPE
=> 'string',
699 ApiBase
::PROP_NULLABLE
=> true
705 public function needsToken() {
709 public function getTokenSalt() {
713 public function getExamples() {
715 'api.php?action=edit&title=Test&summary=test%20summary&' .
716 'text=article%20content&basetimestamp=20070824123454&token=%2B\\'
717 => 'Edit a page (anonymous user)',
718 'api.php?action=edit&title=Test&summary=NOTOC&minor=&' .
719 'prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
720 => 'Prepend __NOTOC__ to a page (anonymous user)',
721 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&' .
722 'basetimestamp=20070824123454&token=%2B\\'
723 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
727 public function getHelpUrls() {
728 return 'https://www.mediawiki.org/wiki/API:Edit';