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 && $params['section'] !== 'new' ) {
52 $this->dieUsage( 'You have attempted to edit using the "redirect"-following mode, which must be used in conjuction with section=new, prependtext, or appendtext.', 'redirect-appendonly' );
54 if ( $titleObj->isRedirect() ) {
55 $oldTitle = $titleObj;
57 $titles = Revision
::newFromTitle( $oldTitle, false, Revision
::READ_LATEST
)
58 ->getContent( Revision
::FOR_THIS_USER
, $user )
60 // array_shift( $titles );
62 $redirValues = array();
64 /** @var $newTitle Title */
65 foreach ( $titles as $id => $newTitle ) {
67 if ( !isset( $titles[$id - 1] ) ) {
68 $titles[$id - 1] = $oldTitle;
71 $redirValues[] = array(
72 'from' => $titles[$id - 1]->getPrefixedText(),
73 'to' => $newTitle->getPrefixedText()
76 $titleObj = $newTitle;
79 $apiResult->setIndexedTagName( $redirValues, 'r' );
80 $apiResult->addValue( null, 'redirects', $redirValues );
82 // Since the page changed, update $pageObj
83 $pageObj = WikiPage
::factory( $titleObj );
87 if ( !isset( $params['contentmodel'] ) ||
$params['contentmodel'] == '' ) {
88 $contentHandler = $pageObj->getContentHandler();
90 $contentHandler = ContentHandler
::getForModelID( $params['contentmodel'] );
93 // @todo Ask handler whether direct editing is supported at all! make
94 // allowFlatEdit() method or some such
96 if ( !isset( $params['contentformat'] ) ||
$params['contentformat'] == '' ) {
97 $params['contentformat'] = $contentHandler->getDefaultFormat();
100 $contentFormat = $params['contentformat'];
102 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
103 $name = $titleObj->getPrefixedDBkey();
104 $model = $contentHandler->getModelID();
106 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
107 " $model used by $name", 'badformat' );
110 if ( $params['createonly'] && $titleObj->exists() ) {
111 $this->dieUsageMsg( 'createonly-exists' );
113 if ( $params['nocreate'] && !$titleObj->exists() ) {
114 $this->dieUsageMsg( 'nocreate-missing' );
117 // Now let's check whether we're even allowed to do this
118 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
119 if ( !$titleObj->exists() ) {
120 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
122 if ( count( $errors ) ) {
123 $this->dieUsageMsg( $errors[0] );
126 $toMD5 = $params['text'];
127 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) ) {
128 $content = $pageObj->getContent();
131 if ( $titleObj->getNamespace() == NS_MEDIAWIKI
) {
132 # If this is a MediaWiki:x message, then load the messages
133 # and return the message value for x.
134 $text = $titleObj->getDefaultMessageText();
135 if ( $text === false ) {
140 $content = ContentHandler
::makeContent( $text, $this->getTitle() );
141 } catch ( MWContentSerializationException
$ex ) {
142 $this->dieUsage( $ex->getMessage(), 'parseerror' );
147 # Otherwise, make a new empty content.
148 $content = $contentHandler->makeEmptyContent();
152 // @todo Add support for appending/prepending to the Content interface
154 if ( !( $content instanceof TextContent
) ) {
155 $mode = $contentHandler->getModelID();
156 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
159 if ( !is_null( $params['section'] ) ) {
160 if ( !$contentHandler->supportsSections() ) {
161 $modelName = $contentHandler->getModelID();
163 "Sections are not supported for this content model: $modelName.",
164 'sectionsnotsupported'
168 if ( $params['section'] == 'new' ) {
169 // DWIM if they're trying to prepend/append to a new section.
172 // Process the content for section edits
173 $section = $params['section'];
174 $content = $content->getSection( $section );
177 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
185 $text = $content->serialize( $contentFormat );
188 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
189 $toMD5 = $params['prependtext'] . $params['appendtext'];
192 if ( $params['undo'] > 0 ) {
193 if ( $params['undoafter'] > 0 ) {
194 if ( $params['undo'] < $params['undoafter'] ) {
195 list( $params['undo'], $params['undoafter'] ) =
196 array( $params['undoafter'], $params['undo'] );
198 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
200 $undoRev = Revision
::newFromID( $params['undo'] );
201 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
202 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
205 if ( $params['undoafter'] == 0 ) {
206 $undoafterRev = $undoRev->getPrevious();
208 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
209 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
212 if ( $undoRev->getPage() != $pageObj->getID() ) {
213 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
214 $titleObj->getPrefixedText() ) );
216 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
217 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
218 $titleObj->getPrefixedText() ) );
221 $newContent = $contentHandler->getUndoContent(
222 $pageObj->getRevision(),
227 if ( !$newContent ) {
228 $this->dieUsageMsg( 'undo-failure' );
231 $params['text'] = $newContent->serialize( $params['contentformat'] );
233 // If no summary was given and we only undid one rev,
234 // use an autosummary
235 if ( is_null( $params['summary'] ) &&
236 $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo']
238 $params['summary'] = wfMessage( 'undo-summary' )
239 ->params ( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
243 // See if the MD5 hash checks out
244 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
245 $this->dieUsageMsg( 'hashcheckfailed' );
248 // EditPage wants to parse its stuff from a WebRequest
249 // That interface kind of sucks, but it's workable
250 $requestArray = array(
251 'wpTextbox1' => $params['text'],
252 'format' => $contentFormat,
253 'model' => $contentHandler->getModelID(),
254 'wpEditToken' => $params['token'],
255 'wpIgnoreBlankSummary' => '',
256 'wpIgnoreBlankArticle' => true
259 if ( !is_null( $params['summary'] ) ) {
260 $requestArray['wpSummary'] = $params['summary'];
263 if ( !is_null( $params['sectiontitle'] ) ) {
264 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
267 // TODO: Pass along information from 'undoafter' as well
268 if ( $params['undo'] > 0 ) {
269 $requestArray['wpUndidRevision'] = $params['undo'];
272 // Watch out for basetimestamp == ''
273 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
274 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
275 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
277 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
280 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
281 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
283 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
286 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
287 $requestArray['wpMinoredit'] = '';
290 if ( $params['recreate'] ) {
291 $requestArray['wpRecreate'] = '';
294 if ( !is_null( $params['section'] ) ) {
295 $section = $params['section'];
296 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
297 $this->dieUsage( "The section parameter must be a valid section id or 'new'", "invalidsection" );
299 $content = $pageObj->getContent();
300 if ( $section !== '0' && $section != 'new' && ( !$content ||
!$content->getSection( $section ) ) ) {
301 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
303 $requestArray['wpSection'] = $params['section'];
305 $requestArray['wpSection'] = '';
308 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
310 // Deprecated parameters
311 if ( $params['watch'] ) {
313 } elseif ( $params['unwatch'] ) {
318 $requestArray['wpWatchthis'] = '';
321 // Pass through anything else we might have been given, to support extensions
322 // This is kind of a hack but it's the best we can do to make extensions work
323 $requestArray +
= $this->getRequest()->getValues();
325 global $wgTitle, $wgRequest;
327 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
329 // Some functions depend on $wgTitle == $ep->mTitle
330 // TODO: Make them not or check if they still do
331 $wgTitle = $titleObj;
333 $articleContext = new RequestContext
;
334 $articleContext->setRequest( $req );
335 $articleContext->setWikiPage( $pageObj );
336 $articleContext->setUser( $this->getUser() );
338 /** @var $articleObject Article */
339 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
341 $ep = new EditPage( $articleObject );
343 // allow editing of non-textual content.
344 $ep->allowNonTextContent
= true;
346 $ep->setContextTitle( $titleObj );
347 $ep->importFormData( $req );
348 $content = $ep->textbox1
;
350 // The following is needed to give the hook the full content of the
351 // new revision rather than just the current section. (Bug 52077)
352 if ( !is_null( $params['section'] ) &&
353 $contentHandler->supportsSections() && $titleObj->exists()
355 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
356 // backwards compatibility with old forms/bots).
357 if ( $ep->sectiontitle
!== '' ) {
358 $sectionTitle = $ep->sectiontitle
;
360 $sectionTitle = $ep->summary
;
363 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
365 $fullContentObj = $articleObject->replaceSectionContent(
370 if ( $fullContentObj ) {
371 $content = $fullContentObj->serialize( $contentFormat );
373 // This most likely means we have an edit conflict which means that the edit
374 // wont succeed anyway.
375 $this->dieUsageMsg( 'editconflict' );
380 // Handle APIEditBeforeSave parameters
382 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
384 $r['result'] = 'Failure';
385 $apiResult->addValue( null, $this->getModuleName(), $r );
390 $this->dieUsageMsg( 'hookaborted' );
393 // Do the actual save
394 $oldRevId = $articleObject->getRevIdFetched();
396 // Fake $wgRequest for some hooks inside EditPage
397 // @todo FIXME: This interface SUCKS
398 $oldRequest = $wgRequest;
401 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
402 $wgRequest = $oldRequest;
404 switch ( $status->value
) {
405 case EditPage
::AS_HOOK_ERROR
:
406 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
407 $this->dieUsageMsg( 'hookaborted' );
409 case EditPage
::AS_PARSE_ERROR
:
410 $this->dieUsage( $status->getMessage(), 'parseerror' );
412 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
413 $this->dieUsageMsg( 'noimageredirect-anon' );
415 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
416 $this->dieUsageMsg( 'noimageredirect-logged' );
418 case EditPage
::AS_SPAM_ERROR
:
419 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
421 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
422 $this->dieUsageMsg( 'blockedtext' );
424 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
425 case EditPage
::AS_CONTENT_TOO_BIG
:
426 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
428 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
429 $this->dieUsageMsg( 'noedit-anon' );
431 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
432 $this->dieUsageMsg( 'noedit' );
434 case EditPage
::AS_READ_ONLY_PAGE
:
435 $this->dieReadOnly();
437 case EditPage
::AS_RATE_LIMITED
:
438 $this->dieUsageMsg( 'actionthrottledtext' );
440 case EditPage
::AS_ARTICLE_WAS_DELETED
:
441 $this->dieUsageMsg( 'wasdeleted' );
443 case EditPage
::AS_NO_CREATE_PERMISSION
:
444 $this->dieUsageMsg( 'nocreate-loggedin' );
446 case EditPage
::AS_BLANK_ARTICLE
:
447 $this->dieUsageMsg( 'blankpage' );
449 case EditPage
::AS_CONFLICT_DETECTED
:
450 $this->dieUsageMsg( 'editconflict' );
452 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
453 case EditPage
::AS_TEXTBOX_EMPTY
:
454 $this->dieUsageMsg( 'emptynewsection' );
456 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
460 case EditPage
::AS_SUCCESS_UPDATE
:
461 $r['result'] = 'Success';
462 $r['pageid'] = intval( $titleObj->getArticleID() );
463 $r['title'] = $titleObj->getPrefixedText();
464 $r['contentmodel'] = $titleObj->getContentModel();
465 $newRevId = $articleObject->getLatest();
466 if ( $newRevId == $oldRevId ) {
469 $r['oldrevid'] = intval( $oldRevId );
470 $r['newrevid'] = intval( $newRevId );
471 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
472 $pageObj->getTimestamp() );
476 case EditPage
::AS_SUMMARY_NEEDED
:
477 $this->dieUsageMsg( 'summaryrequired' );
479 case EditPage
::AS_END
:
481 // $status came from WikiPage::doEdit()
482 $errors = $status->getErrorsArray();
483 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
486 $apiResult->addValue( null, $this->getModuleName(), $r );
489 public function mustBePosted() {
493 public function isWriteMode() {
497 public function getDescription() {
498 return 'Create and edit pages.';
501 public function getPossibleErrors() {
502 return array_merge( parent
::getPossibleErrors(),
503 $this->getTitleOrPageIdErrorMessage(),
505 array( 'missingtext' ),
506 array( 'createonly-exists' ),
507 array( 'nocreate-missing' ),
508 array( 'nosuchrevid', 'undo' ),
509 array( 'nosuchrevid', 'undoafter' ),
510 array( 'revwrongpage', 'id', 'text' ),
511 array( 'undo-failure' ),
512 array( 'hashcheckfailed' ),
513 array( 'hookaborted' ),
514 array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
515 array( 'noimageredirect-anon' ),
516 array( 'noimageredirect-logged' ),
517 array( 'spamdetected', 'spam' ),
518 array( 'summaryrequired' ),
519 array( 'blockedtext' ),
520 array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ),
521 array( 'noedit-anon' ),
523 array( 'actionthrottledtext' ),
524 array( 'wasdeleted' ),
525 array( 'nocreate-loggedin' ),
526 array( 'blankpage' ),
527 array( 'editconflict' ),
528 array( 'emptynewsection' ),
529 array( 'unknownerror', 'retval' ),
530 array( 'code' => 'nosuchsection', 'info' => 'There is no such section.' ),
532 'code' => 'invalidsection',
533 'info' => 'The section parameter must be a valid section id or \'new\''
536 'code' => 'sectionsnotsupported',
537 'info' => 'Sections are not supported for this type of page.'
540 'code' => 'editnotsupported',
541 'info' => 'Editing of this type of page is not supported using the text based edit API.'
544 'code' => 'appendnotsupported',
545 'info' => 'This type of page can not be edited by appending or prepending text.' ),
547 'code' => 'redirect-appendonly',
548 'info' => 'You have attempted to edit using the "redirect"-following mode, which must be used in conjuction with section=new, prependtext, or appendtext.',
551 'code' => 'badformat',
552 'info' => 'The requested serialization format can not be applied to the page\'s content model'
554 array( 'customcssprotected' ),
555 array( 'customjsprotected' ),
560 public function getAllowedParams() {
563 ApiBase
::PARAM_TYPE
=> 'string',
566 ApiBase
::PARAM_TYPE
=> 'integer',
569 'sectiontitle' => array(
570 ApiBase
::PARAM_TYPE
=> 'string',
574 ApiBase
::PARAM_TYPE
=> 'string',
575 ApiBase
::PARAM_REQUIRED
=> true
581 'basetimestamp' => null,
582 'starttimestamp' => null,
584 'createonly' => false,
587 ApiBase
::PARAM_DFLT
=> false,
588 ApiBase
::PARAM_DEPRECATED
=> true,
591 ApiBase
::PARAM_DFLT
=> false,
592 ApiBase
::PARAM_DEPRECATED
=> true,
594 'watchlist' => array(
595 ApiBase
::PARAM_DFLT
=> 'preferences',
596 ApiBase
::PARAM_TYPE
=> array(
604 'prependtext' => null,
605 'appendtext' => null,
607 ApiBase
::PARAM_TYPE
=> 'integer'
609 'undoafter' => array(
610 ApiBase
::PARAM_TYPE
=> 'integer'
613 ApiBase
::PARAM_TYPE
=> 'boolean',
614 ApiBase
::PARAM_DFLT
=> false,
616 'contentformat' => array(
617 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
619 'contentmodel' => array(
620 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
625 public function getParamDescription() {
626 $p = $this->getModulePrefix();
629 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
630 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
631 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
632 'sectiontitle' => 'The title for a new section',
633 'text' => 'Page content',
635 'Edit token. You can get one of these through prop=info.',
636 "The token should always be sent as the last parameter, or at " .
637 "least, after the {$p}text parameter"
640 => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
641 'minor' => 'Minor edit',
642 'notminor' => 'Non-minor edit',
643 'bot' => 'Mark this edit as bot',
644 'basetimestamp' => array(
645 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
646 'Used to detect edit conflicts; leave unset to ignore conflicts'
648 'starttimestamp' => array(
649 'Timestamp when you obtained the edit token.',
650 'Used to detect edit conflicts; leave unset to ignore conflicts'
652 'recreate' => 'Override any errors about the article having been deleted in the meantime',
653 'createonly' => 'Don\'t edit the page if it exists already',
654 'nocreate' => 'Throw an error if the page doesn\'t exist',
655 'watch' => 'Add the page to your watchlist',
656 'unwatch' => 'Remove the page from your watchlist',
657 'watchlist' => 'Unconditionally add or remove the page from your ' .
658 'watchlist, use preferences or do not change watch',
660 "The MD5 hash of the {$p}text parameter, or the {$p}prependtext " .
661 "and {$p}appendtext parameters concatenated.",
662 'If set, the edit won\'t be done unless the hash is correct'
664 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
665 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
666 "Use {$p}section=new to append a new section" ),
667 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
668 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
669 'redirect' => 'Automatically resolve redirects',
670 'contentformat' => 'Content serialization format used for the input text',
671 'contentmodel' => 'Content model of the new content',
675 public function getResultProperties() {
680 ApiBase
::PROP_TYPE
=> array(
686 ApiBase
::PROP_TYPE
=> 'integer',
687 ApiBase
::PROP_NULLABLE
=> true
690 ApiBase
::PROP_TYPE
=> 'string',
691 ApiBase
::PROP_NULLABLE
=> true
693 'nochange' => 'boolean',
695 ApiBase
::PROP_TYPE
=> 'integer',
696 ApiBase
::PROP_NULLABLE
=> true
699 ApiBase
::PROP_TYPE
=> 'integer',
700 ApiBase
::PROP_NULLABLE
=> true
702 'newtimestamp' => array(
703 ApiBase
::PROP_TYPE
=> 'string',
704 ApiBase
::PROP_NULLABLE
=> true
710 public function needsToken() {
714 public function getTokenSalt() {
718 public function getExamples() {
720 'api.php?action=edit&title=Test&summary=test%20summary&' .
721 'text=article%20content&basetimestamp=20070824123454&token=%2B\\'
722 => 'Edit a page (anonymous user)',
723 'api.php?action=edit&title=Test&summary=NOTOC&minor=&' .
724 'prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
725 => 'Prepend __NOTOC__ to a page (anonymous user)',
726 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&' .
727 'basetimestamp=20070824123454&token=%2B\\'
728 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
732 public function getHelpUrls() {
733 return 'https://www.mediawiki.org/wiki/API:Edit';