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' => ''
258 if ( !is_null( $params['summary'] ) ) {
259 $requestArray['wpSummary'] = $params['summary'];
262 if ( !is_null( $params['sectiontitle'] ) ) {
263 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
266 // TODO: Pass along information from 'undoafter' as well
267 if ( $params['undo'] > 0 ) {
268 $requestArray['wpUndidRevision'] = $params['undo'];
271 // Watch out for basetimestamp == ''
272 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
273 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
274 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
276 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
279 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
280 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
282 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
285 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
286 $requestArray['wpMinoredit'] = '';
289 if ( $params['recreate'] ) {
290 $requestArray['wpRecreate'] = '';
293 if ( !is_null( $params['section'] ) ) {
294 $section = $params['section'];
295 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
296 $this->dieUsage( "The section parameter must be a valid section id or 'new'", "invalidsection" );
298 $content = $pageObj->getContent();
299 if ( $section !== '0' && $section != 'new' && ( !$content ||
!$content->getSection( $section ) ) ) {
300 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
302 $requestArray['wpSection'] = $params['section'];
304 $requestArray['wpSection'] = '';
307 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
309 // Deprecated parameters
310 if ( $params['watch'] ) {
312 } elseif ( $params['unwatch'] ) {
317 $requestArray['wpWatchthis'] = '';
320 // Pass through anything else we might have been given, to support extensions
321 // This is kind of a hack but it's the best we can do to make extensions work
322 $requestArray +
= $this->getRequest()->getValues();
324 global $wgTitle, $wgRequest;
326 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
328 // Some functions depend on $wgTitle == $ep->mTitle
329 // TODO: Make them not or check if they still do
330 $wgTitle = $titleObj;
332 $articleContext = new RequestContext
;
333 $articleContext->setRequest( $req );
334 $articleContext->setWikiPage( $pageObj );
335 $articleContext->setUser( $this->getUser() );
337 /** @var $articleObject Article */
338 $articleObject = Article
::newFromWikiPage( $pageObj, $articleContext );
340 $ep = new EditPage( $articleObject );
342 // allow editing of non-textual content.
343 $ep->allowNonTextContent
= true;
345 $ep->setContextTitle( $titleObj );
346 $ep->importFormData( $req );
347 $content = $ep->textbox1
;
349 // The following is needed to give the hook the full content of the
350 // new revision rather than just the current section. (Bug 52077)
351 if ( !is_null( $params['section'] ) &&
352 $contentHandler->supportsSections() && $titleObj->exists()
354 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
355 // backwards compatibility with old forms/bots).
356 if ( $ep->sectiontitle
!== '' ) {
357 $sectionTitle = $ep->sectiontitle
;
359 $sectionTitle = $ep->summary
;
362 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
364 $fullContentObj = $articleObject->replaceSectionContent(
369 if ( $fullContentObj ) {
370 $content = $fullContentObj->serialize( $contentFormat );
372 // This most likely means we have an edit conflict which means that the edit
373 // wont succeed anyway.
374 $this->dieUsageMsg( 'editconflict' );
379 // Handle APIEditBeforeSave parameters
381 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
383 $r['result'] = 'Failure';
384 $apiResult->addValue( null, $this->getModuleName(), $r );
389 $this->dieUsageMsg( 'hookaborted' );
392 // Do the actual save
393 $oldRevId = $articleObject->getRevIdFetched();
395 // Fake $wgRequest for some hooks inside EditPage
396 // @todo FIXME: This interface SUCKS
397 $oldRequest = $wgRequest;
400 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
401 $wgRequest = $oldRequest;
403 switch ( $status->value
) {
404 case EditPage
::AS_HOOK_ERROR
:
405 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
406 $this->dieUsageMsg( 'hookaborted' );
408 case EditPage
::AS_PARSE_ERROR
:
409 $this->dieUsage( $status->getMessage(), 'parseerror' );
411 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
412 $this->dieUsageMsg( 'noimageredirect-anon' );
414 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
415 $this->dieUsageMsg( 'noimageredirect-logged' );
417 case EditPage
::AS_SPAM_ERROR
:
418 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
420 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
421 $this->dieUsageMsg( 'blockedtext' );
423 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
424 case EditPage
::AS_CONTENT_TOO_BIG
:
425 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
427 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
428 $this->dieUsageMsg( 'noedit-anon' );
430 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
431 $this->dieUsageMsg( 'noedit' );
433 case EditPage
::AS_READ_ONLY_PAGE
:
434 $this->dieReadOnly();
436 case EditPage
::AS_RATE_LIMITED
:
437 $this->dieUsageMsg( 'actionthrottledtext' );
439 case EditPage
::AS_ARTICLE_WAS_DELETED
:
440 $this->dieUsageMsg( 'wasdeleted' );
442 case EditPage
::AS_NO_CREATE_PERMISSION
:
443 $this->dieUsageMsg( 'nocreate-loggedin' );
445 case EditPage
::AS_BLANK_ARTICLE
:
446 $this->dieUsageMsg( 'blankpage' );
448 case EditPage
::AS_CONFLICT_DETECTED
:
449 $this->dieUsageMsg( 'editconflict' );
451 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
452 case EditPage
::AS_TEXTBOX_EMPTY
:
453 $this->dieUsageMsg( 'emptynewsection' );
455 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
459 case EditPage
::AS_SUCCESS_UPDATE
:
460 $r['result'] = 'Success';
461 $r['pageid'] = intval( $titleObj->getArticleID() );
462 $r['title'] = $titleObj->getPrefixedText();
463 $r['contentmodel'] = $titleObj->getContentModel();
464 $newRevId = $articleObject->getLatest();
465 if ( $newRevId == $oldRevId ) {
468 $r['oldrevid'] = intval( $oldRevId );
469 $r['newrevid'] = intval( $newRevId );
470 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
471 $pageObj->getTimestamp() );
475 case EditPage
::AS_SUMMARY_NEEDED
:
476 $this->dieUsageMsg( 'summaryrequired' );
478 case EditPage
::AS_END
:
480 // $status came from WikiPage::doEdit()
481 $errors = $status->getErrorsArray();
482 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
485 $apiResult->addValue( null, $this->getModuleName(), $r );
488 public function mustBePosted() {
492 public function isWriteMode() {
496 public function getDescription() {
497 return 'Create and edit pages.';
500 public function getPossibleErrors() {
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', $this->getConfig()->get( 'MaxArticleSize' ) ),
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 such section.' ),
531 'code' => 'invalidsection',
532 'info' => 'The section parameter must be a valid section id 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' => 'redirect-appendonly',
547 'info' => 'You have attempted to edit using the "redirect"-following mode, which must be used in conjuction with section=new, prependtext, or appendtext.',
550 'code' => 'badformat',
551 'info' => 'The requested serialization format can not be applied to the page\'s content model'
553 array( 'customcssprotected' ),
554 array( 'customjsprotected' ),
559 public function getAllowedParams() {
562 ApiBase
::PARAM_TYPE
=> 'string',
565 ApiBase
::PARAM_TYPE
=> 'integer',
568 'sectiontitle' => array(
569 ApiBase
::PARAM_TYPE
=> 'string',
573 ApiBase
::PARAM_TYPE
=> 'string',
574 ApiBase
::PARAM_REQUIRED
=> true
580 'basetimestamp' => null,
581 'starttimestamp' => null,
583 'createonly' => false,
586 ApiBase
::PARAM_DFLT
=> false,
587 ApiBase
::PARAM_DEPRECATED
=> true,
590 ApiBase
::PARAM_DFLT
=> false,
591 ApiBase
::PARAM_DEPRECATED
=> true,
593 'watchlist' => array(
594 ApiBase
::PARAM_DFLT
=> 'preferences',
595 ApiBase
::PARAM_TYPE
=> array(
603 'prependtext' => null,
604 'appendtext' => null,
606 ApiBase
::PARAM_TYPE
=> 'integer'
608 'undoafter' => array(
609 ApiBase
::PARAM_TYPE
=> 'integer'
612 ApiBase
::PARAM_TYPE
=> 'boolean',
613 ApiBase
::PARAM_DFLT
=> false,
615 'contentformat' => array(
616 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
618 'contentmodel' => array(
619 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
624 public function getParamDescription() {
625 $p = $this->getModulePrefix();
628 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
629 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
630 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
631 'sectiontitle' => 'The title for a new section',
632 'text' => 'Page content',
634 'Edit token. You can get one of these through prop=info.',
635 "The token should always be sent as the last parameter, or at " .
636 "least, after the {$p}text parameter"
639 => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
640 'minor' => 'Minor edit',
641 'notminor' => 'Non-minor edit',
642 'bot' => 'Mark this edit as bot',
643 'basetimestamp' => array(
644 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
645 'Used to detect edit conflicts; leave unset to ignore conflicts'
647 'starttimestamp' => array(
648 'Timestamp when you obtained the edit token.',
649 'Used to detect edit conflicts; leave unset to ignore conflicts'
651 'recreate' => 'Override any errors about the article having been deleted in the meantime',
652 'createonly' => 'Don\'t edit the page if it exists already',
653 'nocreate' => 'Throw an error if the page doesn\'t exist',
654 'watch' => 'Add the page to your watchlist',
655 'unwatch' => 'Remove the page from your watchlist',
656 'watchlist' => 'Unconditionally add or remove the page from your ' .
657 'watchlist, use preferences or do not change watch',
659 "The MD5 hash of the {$p}text parameter, or the {$p}prependtext " .
660 "and {$p}appendtext parameters concatenated.",
661 'If set, the edit won\'t be done unless the hash is correct'
663 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
664 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
665 "Use {$p}section=new to append a new section" ),
666 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
667 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
668 'redirect' => 'Automatically resolve redirects',
669 'contentformat' => 'Content serialization format used for the input text',
670 'contentmodel' => 'Content model of the new content',
674 public function getResultProperties() {
679 ApiBase
::PROP_TYPE
=> array(
685 ApiBase
::PROP_TYPE
=> 'integer',
686 ApiBase
::PROP_NULLABLE
=> true
689 ApiBase
::PROP_TYPE
=> 'string',
690 ApiBase
::PROP_NULLABLE
=> true
692 'nochange' => 'boolean',
694 ApiBase
::PROP_TYPE
=> 'integer',
695 ApiBase
::PROP_NULLABLE
=> true
698 ApiBase
::PROP_TYPE
=> 'integer',
699 ApiBase
::PROP_NULLABLE
=> true
701 'newtimestamp' => array(
702 ApiBase
::PROP_TYPE
=> 'string',
703 ApiBase
::PROP_NULLABLE
=> true
709 public function needsToken() {
713 public function getTokenSalt() {
717 public function getExamples() {
719 'api.php?action=edit&title=Test&summary=test%20summary&' .
720 'text=article%20content&basetimestamp=20070824123454&token=%2B\\'
721 => 'Edit a page (anonymous user)',
722 'api.php?action=edit&title=Test&summary=NOTOC&minor=&' .
723 'prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
724 => 'Prepend __NOTOC__ to a page (anonymous user)',
725 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&' .
726 'basetimestamp=20070824123454&token=%2B\\'
727 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
731 public function getHelpUrls() {
732 return 'https://www.mediawiki.org/wiki/API:Edit';