3 use MediaWiki\Block\DatabaseBlock
;
6 * Tests for MediaWiki api.php?action=edit.
8 * @author Daniel Kinzler
16 class ApiEditPageTest
extends ApiTestCase
{
18 protected function setUp() {
21 $this->setMwGlobals( [
22 'wgExtraNamespaces' => [
24 12313 => 'Dummy_talk',
25 12314 => 'DummyNonText',
26 12315 => 'DummyNonText_talk',
28 'wgNamespaceContentModels' => [
30 12314 => 'testing-nontext',
33 $this->mergeMwGlobalArrayValue( 'wgContentHandlers', [
34 'testing' => 'DummyContentHandlerForTesting',
35 'testing-nontext' => 'DummyNonTextContentHandler',
36 'testing-serialize-error' => 'DummySerializeErrorContentHandler',
38 $this->tablesUsed
= array_merge(
40 [ 'change_tag', 'change_tag_def', 'logging' ]
44 public function testEdit() {
45 $name = 'Help:ApiEditPageTest_testEdit'; // assume Help namespace to default to wikitext
47 // -- test new page --------------------------------------------
48 $apiResult = $this->doApiRequestWithToken( [
51 'text' => 'some text',
53 $apiResult = $apiResult[0];
55 // Validate API result data
56 $this->assertArrayHasKey( 'edit', $apiResult );
57 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
58 $this->assertSame( 'Success', $apiResult['edit']['result'] );
60 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
61 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
63 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
65 // -- test existing page, no change ----------------------------
66 $data = $this->doApiRequestWithToken( [
69 'text' => 'some text',
72 $this->assertSame( 'Success', $data[0]['edit']['result'] );
74 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
75 $this->assertArrayHasKey( 'nochange', $data[0]['edit'] );
77 // -- test existing page, with change --------------------------
78 $data = $this->doApiRequestWithToken( [
81 'text' => 'different text'
84 $this->assertSame( 'Success', $data[0]['edit']['result'] );
86 $this->assertArrayNotHasKey( 'new', $data[0]['edit'] );
87 $this->assertArrayNotHasKey( 'nochange', $data[0]['edit'] );
89 $this->assertArrayHasKey( 'oldrevid', $data[0]['edit'] );
90 $this->assertArrayHasKey( 'newrevid', $data[0]['edit'] );
91 $this->assertNotEquals(
92 $data[0]['edit']['newrevid'],
93 $data[0]['edit']['oldrevid'],
94 "revision id should change after edit"
101 public static function provideEditAppend() {
104 'foo', 'append', 'bar', "foobar"
107 'foo', 'prepend', 'bar', "barfoo"
109 [ # 2: append to empty page
110 '', 'append', 'foo', "foo"
112 [ # 3: prepend to empty page
113 '', 'prepend', 'foo', "foo"
115 [ # 4: append to non-existing page
116 null, 'append', 'foo', "foo"
118 [ # 5: prepend to non-existing page
119 null, 'prepend', 'foo', "foo"
125 * @dataProvider provideEditAppend
127 public function testEditAppend( $text, $op, $append, $expected ) {
131 // assume NS_HELP defaults to wikitext
132 $name = "Help:ApiEditPageTest_testEditAppend_$count";
134 // -- create page (or not) -----------------------------------------
135 if ( $text !== null ) {
136 list( $re ) = $this->doApiRequestWithToken( [
139 'text' => $text, ] );
141 $this->assertSame( 'Success', $re['edit']['result'] ); // sanity
144 // -- try append/prepend --------------------------------------------
145 list( $re ) = $this->doApiRequestWithToken( [
148 $op . 'text' => $append, ] );
150 $this->assertSame( 'Success', $re['edit']['result'] );
152 // -- validate -----------------------------------------------------
153 $page = new WikiPage( Title
::newFromText( $name ) );
154 $content = $page->getContent();
155 $this->assertNotNull( $content, 'Page should have been created' );
157 $text = $content->getText();
159 $this->assertSame( $expected, $text );
163 * Test editing of sections
165 public function testEditSection() {
166 $name = 'Help:ApiEditPageTest_testEditSection';
167 $page = WikiPage
::factory( Title
::newFromText( $name ) );
168 $text = "==section 1==\ncontent 1\n==section 2==\ncontent2";
169 // Preload the page with some text
170 $page->doEditContent( ContentHandler
::makeContent( $text, $page->getTitle() ), 'summary' );
172 list( $re ) = $this->doApiRequestWithToken( [
176 'text' => "==section 1==\nnew content 1",
178 $this->assertSame( 'Success', $re['edit']['result'] );
179 $newtext = WikiPage
::factory( Title
::newFromText( $name ) )
180 ->getContent( Revision
::RAW
)
182 $this->assertSame( "==section 1==\nnew content 1\n\n==section 2==\ncontent2", $newtext );
184 // Test that we raise a 'nosuchsection' error
186 $this->doApiRequestWithToken( [
192 $this->fail( "Should have raised an ApiUsageException" );
193 } catch ( ApiUsageException
$e ) {
194 $this->assertTrue( self
::apiExceptionHasCode( $e, 'nosuchsection' ) );
199 * Test action=edit§ion=new
200 * Run it twice so we test adding a new section on a
201 * page that doesn't exist (T54830) and one that
204 public function testEditNewSection() {
205 $name = 'Help:ApiEditPageTest_testEditNewSection';
207 // Test on a page that does not already exist
208 $this->assertFalse( Title
::newFromText( $name )->exists() );
209 list( $re ) = $this->doApiRequestWithToken( [
214 'summary' => 'header',
217 $this->assertSame( 'Success', $re['edit']['result'] );
218 // Check the page text is correct
219 $text = WikiPage
::factory( Title
::newFromText( $name ) )
220 ->getContent( Revision
::RAW
)
222 $this->assertSame( "== header ==\n\ntest", $text );
224 // Now on one that does
225 $this->assertTrue( Title
::newFromText( $name )->exists() );
226 list( $re2 ) = $this->doApiRequestWithToken( [
231 'summary' => 'header',
234 $this->assertSame( 'Success', $re2['edit']['result'] );
235 $text = WikiPage
::factory( Title
::newFromText( $name ) )
236 ->getContent( Revision
::RAW
)
238 $this->assertSame( "== header ==\n\ntest\n\n== header ==\n\ntest", $text );
242 * Ensure we can edit through a redirect, if adding a section
244 public function testEdit_redirect() {
248 // assume NS_HELP defaults to wikitext
249 $name = "Help:ApiEditPageTest_testEdit_redirect_$count";
250 $title = Title
::newFromText( $name );
251 $page = WikiPage
::factory( $title );
253 $rname = "Help:ApiEditPageTest_testEdit_redirect_r$count";
254 $rtitle = Title
::newFromText( $rname );
255 $rpage = WikiPage
::factory( $rtitle );
257 // base edit for content
258 $page->doEditContent( new WikitextContent( "Foo" ),
259 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
260 $this->forceRevisionDate( $page, '20120101000000' );
261 $baseTime = $page->getRevision()->getTimestamp();
263 // base edit for redirect
264 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
265 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
266 $this->forceRevisionDate( $rpage, '20120101000000' );
268 // conflicting edit to redirect
269 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
270 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
271 $this->forceRevisionDate( $rpage, '20120101020202' );
273 // try to save edit, following the redirect
274 list( $re, , ) = $this->doApiRequestWithToken( [
277 'text' => 'nix bar!',
278 'basetimestamp' => $baseTime,
283 $this->assertSame( 'Success', $re['edit']['result'],
284 "no problems expected when following redirect" );
288 * Ensure we cannot edit through a redirect, if attempting to overwrite content
290 public function testEdit_redirectText() {
294 // assume NS_HELP defaults to wikitext
295 $name = "Help:ApiEditPageTest_testEdit_redirectText_$count";
296 $title = Title
::newFromText( $name );
297 $page = WikiPage
::factory( $title );
299 $rname = "Help:ApiEditPageTest_testEdit_redirectText_r$count";
300 $rtitle = Title
::newFromText( $rname );
301 $rpage = WikiPage
::factory( $rtitle );
303 // base edit for content
304 $page->doEditContent( new WikitextContent( "Foo" ),
305 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
306 $this->forceRevisionDate( $page, '20120101000000' );
307 $baseTime = $page->getRevision()->getTimestamp();
309 // base edit for redirect
310 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
311 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
312 $this->forceRevisionDate( $rpage, '20120101000000' );
314 // conflicting edit to redirect
315 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]\n\n[[Category:Test]]" ),
316 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
317 $this->forceRevisionDate( $rpage, '20120101020202' );
319 // try to save edit, following the redirect but without creating a section
321 $this->doApiRequestWithToken( [
324 'text' => 'nix bar!',
325 'basetimestamp' => $baseTime,
329 $this->fail( 'redirect-appendonly error expected' );
330 } catch ( ApiUsageException
$ex ) {
331 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'redirect-appendonly' ) );
335 public function testEditConflict() {
339 // assume NS_HELP defaults to wikitext
340 $name = "Help:ApiEditPageTest_testEditConflict_$count";
341 $title = Title
::newFromText( $name );
343 $page = WikiPage
::factory( $title );
346 $page->doEditContent( new WikitextContent( "Foo" ),
347 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
348 $this->forceRevisionDate( $page, '20120101000000' );
349 $baseTime = $page->getRevision()->getTimestamp();
352 $page->doEditContent( new WikitextContent( "Foo bar" ),
353 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
354 $this->forceRevisionDate( $page, '20120101020202' );
356 // try to save edit, expect conflict
358 $this->doApiRequestWithToken( [
361 'text' => 'nix bar!',
362 'basetimestamp' => $baseTime,
365 $this->fail( 'edit conflict expected' );
366 } catch ( ApiUsageException
$ex ) {
367 $this->assertTrue( self
::apiExceptionHasCode( $ex, 'editconflict' ) );
372 * Ensure that editing using section=new will prevent simple conflicts
374 public function testEditConflict_newSection() {
378 // assume NS_HELP defaults to wikitext
379 $name = "Help:ApiEditPageTest_testEditConflict_newSection_$count";
380 $title = Title
::newFromText( $name );
382 $page = WikiPage
::factory( $title );
385 $page->doEditContent( new WikitextContent( "Foo" ),
386 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
387 $this->forceRevisionDate( $page, '20120101000000' );
388 $baseTime = $page->getRevision()->getTimestamp();
391 $page->doEditContent( new WikitextContent( "Foo bar" ),
392 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
393 $this->forceRevisionDate( $page, '20120101020202' );
395 // try to save edit, expect no conflict
396 list( $re, , ) = $this->doApiRequestWithToken( [
399 'text' => 'nix bar!',
400 'basetimestamp' => $baseTime,
404 $this->assertSame( 'Success', $re['edit']['result'],
405 "no edit conflict expected here" );
408 public function testEditConflict_T43990() {
413 * T43990: if the target page has a newer revision than the redirect, then editing the
414 * redirect while specifying 'redirect' and *not* specifying 'basetimestamp' erroneously
415 * caused an edit conflict to be detected.
418 // assume NS_HELP defaults to wikitext
419 $name = "Help:ApiEditPageTest_testEditConflict_redirect_T43990_$count";
420 $title = Title
::newFromText( $name );
421 $page = WikiPage
::factory( $title );
423 $rname = "Help:ApiEditPageTest_testEditConflict_redirect_T43990_r$count";
424 $rtitle = Title
::newFromText( $rname );
425 $rpage = WikiPage
::factory( $rtitle );
427 // base edit for content
428 $page->doEditContent( new WikitextContent( "Foo" ),
429 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
430 $this->forceRevisionDate( $page, '20120101000000' );
432 // base edit for redirect
433 $rpage->doEditContent( new WikitextContent( "#REDIRECT [[$name]]" ),
434 "testing 1", EDIT_NEW
, false, self
::$users['sysop']->getUser() );
435 $this->forceRevisionDate( $rpage, '20120101000000' );
437 // new edit to content
438 $page->doEditContent( new WikitextContent( "Foo bar" ),
439 "testing 2", EDIT_UPDATE
, $page->getLatest(), self
::$users['uploader']->getUser() );
440 $this->forceRevisionDate( $rpage, '20120101020202' );
442 // try to save edit; should work, following the redirect.
443 list( $re, , ) = $this->doApiRequestWithToken( [
446 'text' => 'nix bar!',
451 $this->assertSame( 'Success', $re['edit']['result'],
452 "no edit conflict expected here" );
456 * @param WikiPage $page
457 * @param string|int $timestamp
459 protected function forceRevisionDate( WikiPage
$page, $timestamp ) {
460 $dbw = wfGetDB( DB_MASTER
);
462 $dbw->update( 'revision',
463 [ 'rev_timestamp' => $dbw->timestamp( $timestamp ) ],
464 [ 'rev_id' => $page->getLatest() ] );
469 public function testCheckDirectApiEditingDisallowed_forNonTextContent() {
470 $this->setExpectedException(
471 ApiUsageException
::class,
472 'Direct editing via API is not supported for content model ' .
473 'testing used by Dummy:ApiEditPageTest_nonTextPageEdit'
476 $this->doApiRequestWithToken( [
478 'title' => 'Dummy:ApiEditPageTest_nonTextPageEdit',
479 'text' => '{"animals":["kittens!"]}'
483 public function testSupportsDirectApiEditing_withContentHandlerOverride() {
484 $name = 'DummyNonText:ApiEditPageTest_testNonTextEdit';
485 $data = serialize( 'some bla bla text' );
487 $result = $this->doApiRequestWithToken( [
493 $apiResult = $result[0];
495 // Validate API result data
496 $this->assertArrayHasKey( 'edit', $apiResult );
497 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
498 $this->assertSame( 'Success', $apiResult['edit']['result'] );
500 $this->assertArrayHasKey( 'new', $apiResult['edit'] );
501 $this->assertArrayNotHasKey( 'nochange', $apiResult['edit'] );
503 $this->assertArrayHasKey( 'pageid', $apiResult['edit'] );
505 // validate resulting revision
506 $page = WikiPage
::factory( Title
::newFromText( $name ) );
507 $this->assertSame( "testing-nontext", $page->getContentModel() );
508 $this->assertSame( $data, $page->getContent()->serialize() );
512 * This test verifies that after changing the content model
513 * of a page, undoing that edit via the API will also
514 * undo the content model change.
516 public function testUndoAfterContentModelChange() {
517 $name = 'Help:' . __FUNCTION__
;
518 $uploader = self
::$users['uploader']->getUser();
519 $sysop = self
::$users['sysop']->getUser();
521 $apiResult = $this->doApiRequestWithToken( [
524 'text' => 'some text',
525 ], null, $sysop )[0];
528 $this->assertArrayHasKey( 'edit', $apiResult );
529 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
530 $this->assertSame( 'Success', $apiResult['edit']['result'] );
531 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
532 // Content model is wikitext
533 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
535 // Convert the page to JSON
536 $apiResult = $this->doApiRequestWithToken( [
540 'contentmodel' => 'json',
541 ], null, $uploader )[0];
544 $this->assertArrayHasKey( 'edit', $apiResult );
545 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
546 $this->assertSame( 'Success', $apiResult['edit']['result'] );
547 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
548 $this->assertSame( 'json', $apiResult['edit']['contentmodel'] );
550 $apiResult = $this->doApiRequestWithToken( [
553 'undo' => $apiResult['edit']['newrevid']
554 ], null, $sysop )[0];
557 $this->assertArrayHasKey( 'edit', $apiResult );
558 $this->assertArrayHasKey( 'result', $apiResult['edit'] );
559 $this->assertSame( 'Success', $apiResult['edit']['result'] );
560 $this->assertArrayHasKey( 'contentmodel', $apiResult['edit'] );
561 // Check that the contentmodel is back to wikitext now.
562 $this->assertSame( 'wikitext', $apiResult['edit']['contentmodel'] );
565 // The tests below are mostly not commented because they do exactly what
566 // you'd expect from the name.
568 public function testCorrectContentFormat() {
569 $name = 'Help:' . ucfirst( __FUNCTION__
);
571 $this->doApiRequestWithToken( [
574 'text' => 'some text',
575 'contentmodel' => 'wikitext',
576 'contentformat' => 'text/x-wiki',
579 $this->assertTrue( Title
::newFromText( $name )->exists() );
582 public function testUnsupportedContentFormat() {
583 $name = 'Help:' . ucfirst( __FUNCTION__
);
585 $this->setExpectedException( ApiUsageException
::class,
586 'Unrecognized value for parameter "contentformat": nonexistent format.' );
589 $this->doApiRequestWithToken( [
592 'text' => 'some text',
593 'contentformat' => 'nonexistent format',
596 $this->assertFalse( Title
::newFromText( $name )->exists() );
600 public function testMismatchedContentFormat() {
601 $name = 'Help:' . ucfirst( __FUNCTION__
);
603 $this->setExpectedException( ApiUsageException
::class,
604 'The requested format text/plain is not supported for content ' .
605 "model wikitext used by $name." );
608 $this->doApiRequestWithToken( [
611 'text' => 'some text',
612 'contentmodel' => 'wikitext',
613 'contentformat' => 'text/plain',
616 $this->assertFalse( Title
::newFromText( $name )->exists() );
620 public function testUndoToInvalidRev() {
621 $name = 'Help:' . ucfirst( __FUNCTION__
);
623 $revId = $this->editPage( $name, 'Some text' )->value
['revision']
627 $this->setExpectedException( ApiUsageException
::class,
628 "There is no revision with ID $revId." );
630 $this->doApiRequestWithToken( [
638 * Tests what happens if the undo parameter is a valid revision, but
639 * the undoafter parameter doesn't refer to a revision that exists in the
642 public function testUndoAfterToInvalidRev() {
643 // We can't just pick a large number for undoafter (as in
644 // testUndoToInvalidRev above), because then MediaWiki will helpfully
645 // assume we switched around undo and undoafter and we'll test the code
646 // path for undo being invalid, not undoafter. So instead we delete
647 // the revision from the database. In real life this case could come
648 // up if a revision number was skipped, e.g., if two transactions try
649 // to insert new revision rows at once and the first one to succeed
651 $name = 'Help:' . ucfirst( __FUNCTION__
);
652 $titleObj = Title
::newFromText( $name );
654 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
655 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
656 $revId3 = $this->editPage( $name, '3' )->value
['revision']->getId();
658 // Make the middle revision disappear
659 $dbw = wfGetDB( DB_MASTER
);
660 $dbw->delete( 'revision', [ 'rev_id' => $revId2 ], __METHOD__
);
661 $dbw->update( 'revision', [ 'rev_parent_id' => $revId1 ],
662 [ 'rev_id' => $revId3 ], __METHOD__
);
664 $this->setExpectedException( ApiUsageException
::class,
665 "There is no revision with ID $revId2." );
667 $this->doApiRequestWithToken( [
671 'undoafter' => $revId2,
676 * Tests what happens if the undo parameter is a valid revision, but
677 * undoafter is hidden (rev_deleted).
679 public function testUndoAfterToHiddenRev() {
680 $name = 'Help:' . ucfirst( __FUNCTION__
);
681 $titleObj = Title
::newFromText( $name );
683 $this->editPage( $name, '0' );
685 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
687 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
689 // Hide the middle revision
690 $list = RevisionDeleter
::createList( 'revision',
691 RequestContext
::getMain(), $titleObj, [ $revId1 ] );
692 $list->setVisibility( [
693 'value' => [ Revision
::DELETED_TEXT
=> 1 ],
694 'comment' => 'Bye-bye',
697 $this->setExpectedException( ApiUsageException
::class,
698 "There is no revision with ID $revId1." );
700 $this->doApiRequestWithToken( [
704 'undoafter' => $revId1,
709 * Test undo when a revision with a higher id has an earlier timestamp.
710 * This can happen if importing an old revision.
712 public function testUndoWithSwappedRevisions() {
713 $name = 'Help:' . ucfirst( __FUNCTION__
);
714 $titleObj = Title
::newFromText( $name );
716 $this->editPage( $name, '0' );
718 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
720 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
722 // Now monkey with the timestamp
723 $dbw = wfGetDB( DB_MASTER
);
726 [ 'rev_timestamp' => $dbw->timestamp( time() - 86400 ) ],
727 [ 'rev_id' => $revId1 ],
731 $this->doApiRequestWithToken( [
735 'undoafter' => $revId1,
738 $text = ( new WikiPage( $titleObj ) )->getContent()->getText();
740 // This is wrong! It should be 1. But let's test for our incorrect
741 // behavior for now, so if someone fixes it they'll fix the test as
742 // well to expect 1. If we disabled the test, it might stay disabled
743 // even once the bug is fixed, which would be a shame.
744 $this->assertSame( '2', $text );
747 public function testUndoWithConflicts() {
748 $name = 'Help:' . ucfirst( __FUNCTION__
);
750 $this->setExpectedException( ApiUsageException
::class,
751 'The edit could not be undone due to conflicting intermediate edits.' );
753 $this->editPage( $name, '1' );
755 $revId = $this->editPage( $name, '2' )->value
['revision']->getId();
757 $this->editPage( $name, '3' );
759 $this->doApiRequestWithToken( [
765 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
767 $this->assertSame( '3', $text );
771 * undoafter is supposed to be less than undo. If not, we reverse their
772 * meaning, so that the two are effectively interchangeable.
774 public function testReversedUndoAfter() {
775 $name = 'Help:' . ucfirst( __FUNCTION__
);
777 $this->editPage( $name, '0' );
778 $revId1 = $this->editPage( $name, '1' )->value
['revision']->getId();
779 $revId2 = $this->editPage( $name, '2' )->value
['revision']->getId();
781 $this->doApiRequestWithToken( [
785 'undoafter' => $revId2,
788 $text = ( new WikiPage( Title
::newFromText( $name ) ) )->getContent()
790 $this->assertSame( '1', $text );
793 public function testUndoToRevFromDifferentPage() {
794 $name = 'Help:' . ucfirst( __FUNCTION__
);
796 $this->editPage( "$name-1", 'Some text' );
797 $revId = $this->editPage( "$name-1", 'Some more text' )
798 ->value
['revision']->getId();
800 $this->editPage( "$name-2", 'Some text' );
802 $this->setExpectedException( ApiUsageException
::class,
803 "r$revId is not a revision of $name-2." );
805 $this->doApiRequestWithToken( [
807 'title' => "$name-2",
812 public function testUndoAfterToRevFromDifferentPage() {
813 $name = 'Help:' . ucfirst( __FUNCTION__
);
815 $revId1 = $this->editPage( "$name-1", 'Some text' )
816 ->value
['revision']->getId();
818 $revId2 = $this->editPage( "$name-2", 'Some text' )
819 ->value
['revision']->getId();
821 $this->setExpectedException( ApiUsageException
::class,
822 "r$revId1 is not a revision of $name-2." );
824 $this->doApiRequestWithToken( [
826 'title' => "$name-2",
828 'undoafter' => $revId1,
832 public function testMd5Text() {
833 $name = 'Help:' . ucfirst( __FUNCTION__
);
835 $this->assertFalse( Title
::newFromText( $name )->exists() );
837 $this->doApiRequestWithToken( [
840 'text' => 'Some text',
841 'md5' => md5( 'Some text' ),
844 $this->assertTrue( Title
::newFromText( $name )->exists() );
847 public function testMd5PrependText() {
848 $name = 'Help:' . ucfirst( __FUNCTION__
);
850 $this->editPage( $name, 'Some text' );
852 $this->doApiRequestWithToken( [
855 'prependtext' => 'Alert: ',
856 'md5' => md5( 'Alert: ' ),
859 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
860 ->getContent()->getText();
861 $this->assertSame( 'Alert: Some text', $text );
864 public function testMd5AppendText() {
865 $name = 'Help:' . ucfirst( __FUNCTION__
);
867 $this->editPage( $name, 'Some text' );
869 $this->doApiRequestWithToken( [
872 'appendtext' => ' is nice',
873 'md5' => md5( ' is nice' ),
876 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
877 ->getContent()->getText();
878 $this->assertSame( 'Some text is nice', $text );
881 public function testMd5PrependAndAppendText() {
882 $name = 'Help:' . ucfirst( __FUNCTION__
);
884 $this->editPage( $name, 'Some text' );
886 $this->doApiRequestWithToken( [
889 'prependtext' => 'Alert: ',
890 'appendtext' => ' is nice',
891 'md5' => md5( 'Alert: is nice' ),
894 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
895 ->getContent()->getText();
896 $this->assertSame( 'Alert: Some text is nice', $text );
899 public function testIncorrectMd5Text() {
900 $name = 'Help:' . ucfirst( __FUNCTION__
);
902 $this->setExpectedException( ApiUsageException
::class,
903 'The supplied MD5 hash was incorrect.' );
905 $this->doApiRequestWithToken( [
908 'text' => 'Some text',
913 public function testIncorrectMd5PrependText() {
914 $name = 'Help:' . ucfirst( __FUNCTION__
);
916 $this->setExpectedException( ApiUsageException
::class,
917 'The supplied MD5 hash was incorrect.' );
919 $this->doApiRequestWithToken( [
922 'prependtext' => 'Some ',
923 'appendtext' => 'text',
924 'md5' => md5( 'Some ' ),
928 public function testIncorrectMd5AppendText() {
929 $name = 'Help:' . ucfirst( __FUNCTION__
);
931 $this->setExpectedException( ApiUsageException
::class,
932 'The supplied MD5 hash was incorrect.' );
934 $this->doApiRequestWithToken( [
937 'prependtext' => 'Some ',
938 'appendtext' => 'text',
939 'md5' => md5( 'text' ),
943 public function testCreateOnly() {
944 $name = 'Help:' . ucfirst( __FUNCTION__
);
946 $this->setExpectedException( ApiUsageException
::class,
947 'The article you tried to create has been created already.' );
949 $this->editPage( $name, 'Some text' );
950 $this->assertTrue( Title
::newFromText( $name )->exists() );
953 $this->doApiRequestWithToken( [
956 'text' => 'Some more text',
960 // Validate that content was not changed
961 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
962 ->getContent()->getText();
964 $this->assertSame( 'Some text', $text );
968 public function testNoCreate() {
969 $name = 'Help:' . ucfirst( __FUNCTION__
);
971 $this->setExpectedException( ApiUsageException
::class,
972 "The page you specified doesn't exist." );
974 $this->assertFalse( Title
::newFromText( $name )->exists() );
977 $this->doApiRequestWithToken( [
980 'text' => 'Some text',
984 $this->assertFalse( Title
::newFromText( $name )->exists() );
989 * Appending/prepending is currently only supported for TextContent. We
990 * test this right now, and when support is added this test should be
991 * replaced by tests that the support is correct.
993 public function testAppendWithNonTextContentHandler() {
994 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
996 $this->setExpectedException( ApiUsageException
::class,
997 "Can't append to pages using content model testing-nontext." );
999 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
1000 function ( Title
$title, &$model ) use ( $name ) {
1001 if ( $title->getPrefixedText() === $name ) {
1002 $model = 'testing-nontext';
1008 $this->doApiRequestWithToken( [
1011 'appendtext' => 'Some text',
1015 public function testAppendInMediaWikiNamespace() {
1016 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1018 $this->assertFalse( Title
::newFromText( $name )->exists() );
1020 $this->doApiRequestWithToken( [
1023 'appendtext' => 'Some text',
1026 $this->assertTrue( Title
::newFromText( $name )->exists() );
1029 public function testAppendInMediaWikiNamespaceWithSerializationError() {
1030 $name = 'MediaWiki:' . ucfirst( __FUNCTION__
);
1032 $this->setExpectedException( ApiUsageException
::class,
1033 'Content serialization failed: Could not unserialize content' );
1035 $this->setTemporaryHook( 'ContentHandlerDefaultModelFor',
1036 function ( Title
$title, &$model ) use ( $name ) {
1037 if ( $title->getPrefixedText() === $name ) {
1038 $model = 'testing-serialize-error';
1044 $this->doApiRequestWithToken( [
1047 'appendtext' => 'Some text',
1051 public function testAppendNewSection() {
1052 $name = 'Help:' . ucfirst( __FUNCTION__
);
1054 $this->editPage( $name, 'Initial content' );
1056 $this->doApiRequestWithToken( [
1059 'appendtext' => '== New section ==',
1063 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1064 ->getContent()->getText();
1066 $this->assertSame( "Initial content\n\n== New section ==", $text );
1069 public function testAppendNewSectionWithInvalidContentModel() {
1070 $name = 'Help:' . ucfirst( __FUNCTION__
);
1072 $this->setExpectedException( ApiUsageException
::class,
1073 'Sections are not supported for content model text.' );
1075 $this->editPage( $name, 'Initial content' );
1077 $this->doApiRequestWithToken( [
1080 'appendtext' => '== New section ==',
1082 'contentmodel' => 'text',
1086 public function testAppendNewSectionWithTitle() {
1087 $name = 'Help:' . ucfirst( __FUNCTION__
);
1089 $this->editPage( $name, 'Initial content' );
1091 $this->doApiRequestWithToken( [
1094 'sectiontitle' => 'My section',
1095 'appendtext' => 'More content',
1099 $page = new WikiPage( Title
::newFromText( $name ) );
1101 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1102 $page->getContent()->getText() );
1103 $this->assertSame( '/* My section */ new section',
1104 $page->getRevision()->getComment() );
1107 public function testAppendNewSectionWithSummary() {
1108 $name = 'Help:' . ucfirst( __FUNCTION__
);
1110 $this->editPage( $name, 'Initial content' );
1112 $this->doApiRequestWithToken( [
1115 'appendtext' => 'More content',
1117 'summary' => 'Add new section',
1120 $page = new WikiPage( Title
::newFromText( $name ) );
1122 $this->assertSame( "Initial content\n\n== Add new section ==\n\nMore content",
1123 $page->getContent()->getText() );
1124 // EditPage actually assumes the summary is the section name here
1125 $this->assertSame( '/* Add new section */ new section',
1126 $page->getRevision()->getComment() );
1129 public function testAppendNewSectionWithTitleAndSummary() {
1130 $name = 'Help:' . ucfirst( __FUNCTION__
);
1132 $this->editPage( $name, 'Initial content' );
1134 $this->doApiRequestWithToken( [
1137 'sectiontitle' => 'My section',
1138 'appendtext' => 'More content',
1140 'summary' => 'Add new section',
1143 $page = new WikiPage( Title
::newFromText( $name ) );
1145 $this->assertSame( "Initial content\n\n== My section ==\n\nMore content",
1146 $page->getContent()->getText() );
1147 $this->assertSame( 'Add new section',
1148 $page->getRevision()->getComment() );
1151 public function testAppendToSection() {
1152 $name = 'Help:' . ucfirst( __FUNCTION__
);
1154 $this->editPage( $name, "== Section 1 ==\n\nContent\n\n" .
1155 "== Section 2 ==\n\nFascinating!" );
1157 $this->doApiRequestWithToken( [
1160 'appendtext' => ' and more content',
1164 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1165 ->getContent()->getText();
1167 $this->assertSame( "== Section 1 ==\n\nContent and more content\n\n" .
1168 "== Section 2 ==\n\nFascinating!", $text );
1171 public function testAppendToFirstSection() {
1172 $name = 'Help:' . ucfirst( __FUNCTION__
);
1174 $this->editPage( $name, "Content\n\n== Section 1 ==\n\nFascinating!" );
1176 $this->doApiRequestWithToken( [
1179 'appendtext' => ' and more content',
1183 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1184 ->getContent()->getText();
1186 $this->assertSame( "Content and more content\n\n== Section 1 ==\n\n" .
1187 "Fascinating!", $text );
1190 public function testAppendToNonexistentSection() {
1191 $name = 'Help:' . ucfirst( __FUNCTION__
);
1193 $this->setExpectedException( ApiUsageException
::class, 'There is no section 1.' );
1195 $this->editPage( $name, 'Content' );
1198 $this->doApiRequestWithToken( [
1201 'appendtext' => ' and more content',
1205 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1206 ->getContent()->getText();
1208 $this->assertSame( 'Content', $text );
1212 public function testEditMalformedSection() {
1213 $name = 'Help:' . ucfirst( __FUNCTION__
);
1215 $this->setExpectedException( ApiUsageException
::class,
1216 'The "section" parameter must be a valid section ID or "new".' );
1217 $this->editPage( $name, 'Content' );
1220 $this->doApiRequestWithToken( [
1223 'text' => 'Different content',
1224 'section' => 'It is unlikely that this is valid',
1227 $text = ( new WikiPage( Title
::newFromText( $name ) ) )
1228 ->getContent()->getText();
1230 $this->assertSame( 'Content', $text );
1234 public function testEditWithStartTimestamp() {
1235 $name = 'Help:' . ucfirst( __FUNCTION__
);
1236 $this->setExpectedException( ApiUsageException
::class,
1237 'The page has been deleted since you fetched its timestamp.' );
1239 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1241 $this->editPage( $name, 'Some text' );
1243 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1244 $pageObj->doDeleteArticle( 'Bye-bye' );
1246 $this->assertFalse( $pageObj->exists() );
1249 $this->doApiRequestWithToken( [
1252 'text' => 'Different text',
1253 'starttimestamp' => $startTime,
1256 $this->assertFalse( $pageObj->exists() );
1260 public function testEditMinor() {
1261 $name = 'Help:' . ucfirst( __FUNCTION__
);
1263 $this->editPage( $name, 'Some text' );
1265 $this->doApiRequestWithToken( [
1268 'text' => 'Different text',
1272 $revisionStore = \MediaWiki\MediaWikiServices
::getInstance()->getRevisionStore();
1273 $revision = $revisionStore->getRevisionByTitle( Title
::newFromText( $name ) );
1274 $this->assertTrue( $revision->isMinor() );
1277 public function testEditRecreate() {
1278 $name = 'Help:' . ucfirst( __FUNCTION__
);
1280 $startTime = MWTimestamp
::convert( TS_MW
, time() - 1 );
1282 $this->editPage( $name, 'Some text' );
1284 $pageObj = new WikiPage( Title
::newFromText( $name ) );
1285 $pageObj->doDeleteArticle( 'Bye-bye' );
1287 $this->assertFalse( $pageObj->exists() );
1289 $this->doApiRequestWithToken( [
1292 'text' => 'Different text',
1293 'starttimestamp' => $startTime,
1297 $this->assertTrue( Title
::newFromText( $name )->exists() );
1300 public function testEditWatch() {
1301 $name = 'Help:' . ucfirst( __FUNCTION__
);
1302 $user = self
::$users['sysop']->getUser();
1304 $this->doApiRequestWithToken( [
1307 'text' => 'Some text',
1311 $this->assertTrue( Title
::newFromText( $name )->exists() );
1312 $this->assertTrue( $user->isWatched( Title
::newFromText( $name ) ) );
1315 public function testEditUnwatch() {
1316 $name = 'Help:' . ucfirst( __FUNCTION__
);
1317 $user = self
::$users['sysop']->getUser();
1318 $titleObj = Title
::newFromText( $name );
1320 $user->addWatch( $titleObj );
1322 $this->assertFalse( $titleObj->exists() );
1323 $this->assertTrue( $user->isWatched( $titleObj ) );
1325 $this->doApiRequestWithToken( [
1328 'text' => 'Some text',
1332 $this->assertTrue( $titleObj->exists() );
1333 $this->assertFalse( $user->isWatched( $titleObj ) );
1336 public function testEditWithTag() {
1337 $name = 'Help:' . ucfirst( __FUNCTION__
);
1339 ChangeTags
::defineTag( 'custom tag' );
1341 $revId = $this->doApiRequestWithToken( [
1344 'text' => 'Some text',
1345 'tags' => 'custom tag',
1346 ] )[0]['edit']['newrevid'];
1348 $dbw = wfGetDB( DB_MASTER
);
1349 $this->assertSame( 'custom tag', $dbw->selectField(
1350 [ 'change_tag', 'change_tag_def' ],
1352 [ 'ct_rev_id' => $revId ],
1354 [ 'change_tag_def' => [ 'JOIN', 'ctd_id = ct_tag_id' ] ]
1359 public function testEditWithoutTagPermission() {
1360 $name = 'Help:' . ucfirst( __FUNCTION__
);
1362 $this->setExpectedException( ApiUsageException
::class,
1363 'You do not have permission to apply change tags along with your changes.' );
1365 $this->assertFalse( Title
::newFromText( $name )->exists() );
1367 ChangeTags
::defineTag( 'custom tag' );
1368 $this->setMwGlobals( 'wgRevokePermissions',
1369 [ 'user' => [ 'applychangetags' => true ] ] );
1372 $this->doApiRequestWithToken( [
1375 'text' => 'Some text',
1376 'tags' => 'custom tag',
1379 $this->assertFalse( Title
::newFromText( $name )->exists() );
1383 public function testEditAbortedByEditPageHookWithResult() {
1384 $name = 'Help:' . ucfirst( __FUNCTION__
);
1386 $this->setTemporaryHook( 'EditFilterMergedContent',
1387 function ( $unused1, $unused2, Status
$status ) {
1388 $status->apiHookResult
= [ 'msg' => 'A message for you!' ];
1392 $res = $this->doApiRequestWithToken( [
1395 'text' => 'Some text',
1398 $this->assertFalse( Title
::newFromText( $name )->exists() );
1399 $this->assertSame( [ 'edit' => [ 'msg' => 'A message for you!',
1400 'result' => 'Failure' ] ], $res[0] );
1403 public function testEditAbortedByEditPageHookWithNoResult() {
1404 $name = 'Help:' . ucfirst( __FUNCTION__
);
1406 $this->setExpectedException( ApiUsageException
::class,
1407 'The modification you tried to make was aborted by an extension.' );
1409 $this->setTemporaryHook( 'EditFilterMergedContent',
1416 $this->doApiRequestWithToken( [
1419 'text' => 'Some text',
1422 $this->assertFalse( Title
::newFromText( $name )->exists() );
1426 public function testEditWhileBlocked() {
1427 $name = 'Help:' . ucfirst( __FUNCTION__
);
1429 $this->assertNull( DatabaseBlock
::newFromTarget( '127.0.0.1' ), 'Sanity check' );
1431 $block = new DatabaseBlock( [
1432 'address' => self
::$users['sysop']->getUser()->getName(),
1433 'by' => self
::$users['sysop']->getUser()->getId(),
1434 'reason' => 'Capriciousness',
1435 'timestamp' => '19370101000000',
1436 'expiry' => 'infinity',
1437 'enableAutoblock' => true,
1442 $this->doApiRequestWithToken( [
1445 'text' => 'Some text',
1447 $this->fail( 'Expected exception not thrown' );
1448 } catch ( ApiUsageException
$ex ) {
1449 $this->assertSame( 'You have been blocked from editing.', $ex->getMessage() );
1450 $this->assertNotNull( DatabaseBlock
::newFromTarget( '127.0.0.1' ), 'Autoblock spread' );
1453 self
::$users['sysop']->getUser()->clearInstanceCache();
1457 public function testEditWhileReadOnly() {
1458 $name = 'Help:' . ucfirst( __FUNCTION__
);
1460 $this->setExpectedException( ApiUsageException
::class,
1461 'The wiki is currently in read-only mode.' );
1463 $svc = \MediaWiki\MediaWikiServices
::getInstance()->getReadOnlyMode();
1464 $svc->setReason( "Read-only for testing" );
1467 $this->doApiRequestWithToken( [
1470 'text' => 'Some text',
1473 $svc->setReason( false );
1477 public function testCreateImageRedirectAnon() {
1478 $name = 'File:' . ucfirst( __FUNCTION__
);
1480 $this->setExpectedException( ApiUsageException
::class,
1481 "Anonymous users can't create image redirects." );
1483 $this->doApiRequestWithToken( [
1486 'text' => '#REDIRECT [[File:Other file.png]]',
1487 ], null, new User() );
1490 public function testCreateImageRedirectLoggedIn() {
1491 $name = 'File:' . ucfirst( __FUNCTION__
);
1493 $this->setExpectedException( ApiUsageException
::class,
1494 "You don't have permission to create image redirects." );
1496 $this->setMwGlobals( 'wgRevokePermissions',
1497 [ 'user' => [ 'upload' => true ] ] );
1499 $this->doApiRequestWithToken( [
1502 'text' => '#REDIRECT [[File:Other file.png]]',
1506 public function testTooBigEdit() {
1507 $name = 'Help:' . ucfirst( __FUNCTION__
);
1509 $this->setExpectedException( ApiUsageException
::class,
1510 'The content you supplied exceeds the article size limit of 1 kilobyte.' );
1512 $this->setMwGlobals( 'wgMaxArticleSize', 1 );
1514 $text = str_repeat( '!', 1025 );
1516 $this->doApiRequestWithToken( [
1523 public function testProhibitedAnonymousEdit() {
1524 $name = 'Help:' . ucfirst( __FUNCTION__
);
1526 $this->setExpectedException( ApiUsageException
::class,
1527 'The action you have requested is limited to users in the group: ' );
1529 $this->setMwGlobals( 'wgRevokePermissions', [ '*' => [ 'edit' => true ] ] );
1531 $this->doApiRequestWithToken( [
1534 'text' => 'Some text',
1535 ], null, new User() );
1538 public function testProhibitedChangeContentModel() {
1539 $name = 'Help:' . ucfirst( __FUNCTION__
);
1541 $this->setExpectedException( ApiUsageException
::class,
1542 "You don't have permission to change the content model of a page." );
1544 $this->setMwGlobals( 'wgRevokePermissions',
1545 [ 'user' => [ 'editcontentmodel' => true ] ] );
1547 $this->doApiRequestWithToken( [
1550 'text' => 'Some text',
1551 'contentmodel' => 'json',