Debian Codegraph @

tests/phpunit/includes/editpage/EditPageTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Content\ContentHandler;
4 use MediaWiki\Content\TextContent;
5 use MediaWiki\Context\RequestContext;
6 use MediaWiki\Deferred\DeferredUpdates;
7 use MediaWiki\EditPage\EditPage;
8 use MediaWiki\MainConfigNames;
9 use MediaWiki\MainConfigSchema;
10 use MediaWiki\Request\FauxRequest;
11 use MediaWiki\Revision\RevisionRecord;
12 use MediaWiki\Status\Status;
13 use MediaWiki\Storage\EditResult;
14 use MediaWiki\Tests\User\TempUser\TempUserTestTrait;
15 use MediaWiki\Title\Title;
16 use MediaWiki\User\User;
17 use MediaWiki\User\UserIdentity;
18 use MediaWiki\Utils\MWTimestamp;
19 use Wikimedia\TestingAccessWrapper;
20
21 /**
22 * @group Editing
23 * @group Database
24 * @group medium
25 */
26 class EditPageTest extends MediaWikiLangTestCase {
27
28 use TempUserTestTrait;
29
30 /** @var User[] */
31 private static $editUsers;
32
33 protected function setUp(): void {
34 parent::setUp();
35
36 $this->overrideConfigValues( [
37 MainConfigNames::ExtraNamespaces => [
38 12312 => 'Dummy',
39 12313 => 'Dummy_talk',
40 ],
41 MainConfigNames::NamespaceContentModels => [ 12312 => 'testing' ],
42 MainConfigNames::ContentHandlers =>
43 [ 'testing' => 'DummyContentHandlerForTesting' ] +
44 MainConfigSchema::getDefaultValue( MainConfigNames::ContentHandlers ),
45 ] );
46
47 // Disable WAN cache to avoid edit conflicts in testUpdateNoMinor
48 $this->setMainCache( CACHE_NONE );
49 }
50
51 public function addDBDataOnce() {
52 $userFactory = $this->getServiceContainer()->getUserFactory();
53 self::$editUsers = [
54 'anon' => new User(),
55 'UTSysop' => $userFactory->newFromName( 'UTSysop' ),
56 'user' => $userFactory->newFromName( 'UTUser' ),
57 'Adam' => $userFactory->newFromName( 'Adam' ),
58 'Berta' => $userFactory->newFromName( 'Berta' ),
59 'Elmo' => $userFactory->newFromName( 'Elmo' ),
60 ];
61
62 foreach ( self::$editUsers as $key => $user ) {
63 if ( $key !== 'anon' ) {
64 $user->addToDatabase();
65 }
66 }
67
68 $groupManager = $this->getServiceContainer()->getUserGroupManager();
69 $groupManager->addUserToMultipleGroups(
70 self::$editUsers['UTSysop'], [ 'sysop', 'bureaucrat' ] );
71 }
72
73 /**
74 * @dataProvider provideExtractSectionTitle
75 * @covers \MediaWiki\EditPage\EditPage::extractSectionTitle
76 */
77 public function testExtractSectionTitle( $section, $title ) {
78 $this->assertEquals(
79 $title,
80 TestingAccessWrapper::newFromClass( EditPage::class )->extractSectionTitle( $section )
81 );
82 }
83
84 public static function provideExtractSectionTitle() {
85 return [
86 [
87 "== Test ==\n\nJust a test section.",
88 "Test"
89 ],
90 [
91 "An initial section, no header.",
92 false
93 ],
94 [
95 "An initial section with a fake heder (T34617)\n\n== Test == ??\nwtf",
96 false
97 ],
98 [
99 "== Section ==\nfollowed by a fake == Non-section == ??\nnoooo",
100 "Section"
101 ],
102 [
103 "== Section== \t\r\n followed by whitespace (T37051)",
104 'Section',
105 ],
106 ];
107 }
108
109 protected function forceRevisionDate( WikiPage $page, $timestamp ) {
110 $dbw = $this->getDb();
111
112 $dbw->newUpdateQueryBuilder()
113 ->update( 'revision' )
114 ->set( [ 'rev_timestamp' => $dbw->timestamp( $timestamp ) ] )
115 ->where( [ 'rev_id' => $page->getLatest() ] )
116 ->execute();
117
118 $page->clear();
119 }
120
121 /**
122 * User input text is passed to rtrim() by edit page. This is a simple
123 * wrapper around assertEquals() which calls rrtrim() to normalize the
124 * expected and actual texts.
125 * @param string $expected
126 * @param string $actual
127 * @param string $msg
128 */
129 protected function assertEditedTextEquals( $expected, $actual, $msg = '' ) {
130 $this->assertEquals( rtrim( $expected ), rtrim( $actual ), $msg );
131 }
132
133 /**
134 * Performs an edit and checks the result.
135 *
136 * @param string|Title $title The title of the page to edit
137 * @param string|null $baseText Some text to create the page with before attempting the edit.
138 * @param string $userKey The user to perform the edit as.
139 * @param array $edit An array of request parameters used to define the edit to perform.
140 * Some well known fields are:
141 * * wpTextbox1: the text to submit
142 * * wpSummary: the edit summary
143 * * wpEditToken: the edit token (will be inserted if not provided)
144 * * wpEdittime: timestamp of the edit's base revision (will be inserted
145 * if not provided)
146 * * editRevId: revision ID of the edit's base revision (optional)
147 * * wpStarttime: timestamp when the edit started (will be inserted if not provided)
148 * * wpSectionTitle: the section to edit
149 * * wpMinoredit: mark as minor edit
150 * * wpWatchthis: whether to watch the page
151 * @param int|null $expectedCode The expected result code (EditPage::AS_XXX constants).
152 * Set to null to skip the check.
153 * @param string|null $expectedText The text expected to be on the page after the edit.
154 * Set to null to skip the check.
155 * @param string|null $message An optional message to show along with any error message.
156 *
157 * @return WikiPage The page that was just edited, useful for getting the edit's rev_id, etc.
158 */
159 protected function assertEdit( $title, $baseText, $userKey, array $edit,
160 $expectedCode = null, $expectedText = null, $message = null
161 ) {
162 if ( is_string( $title ) ) {
163 $ns = $this->getDefaultWikitextNS();
164 $title = Title::newFromText( $title, $ns );
165 }
166 $this->assertNotNull( $title );
167
168 if ( !isset( self::$editUsers[$userKey] ) ) {
169 $this->fail( "User $userKey not registered in addDBDataOnce" );
170 }
171 $user = self::$editUsers[$userKey];
172
173 $wikiPageFactory = $this->getServiceContainer()->getWikiPageFactory();
174 $page = $wikiPageFactory->newFromTitle( $title );
175
176 if ( $baseText !== null ) {
177 $content = ContentHandler::makeContent( $baseText, $title );
178 $page->doUserEditContent( $content, $user, "base text for test" );
179 $this->forceRevisionDate( $page, '20120101000000' );
180
181 $page->clear();
182 $content = $page->getContent();
183
184 $this->assertInstanceOf( TextContent::class, $content );
185 $currentText = $content->getText();
186
187 # EditPage rtrim() the user input, so we alter our expected text
188 # to reflect that.
189 $this->assertEditedTextEquals( $baseText, $currentText );
190 }
191
192 if ( !isset( $edit['wpEditToken'] ) ) {
193 $edit['wpEditToken'] = $user->getEditToken();
194 }
195
196 if ( !isset( $edit['wpEdittime'] ) && !isset( $edit['editRevId'] ) ) {
197 $edit['wpEdittime'] = $page->exists() ? $page->getTimestamp() : '';
198 }
199
200 if ( !isset( $edit['wpStarttime'] ) ) {
201 $edit['wpStarttime'] = wfTimestampNow();
202 }
203
204 if ( !isset( $edit['wpUnicodeCheck'] ) ) {
205 $edit['wpUnicodeCheck'] = EditPage::UNICODE_CHECK;
206 }
207
208 $req = new FauxRequest( $edit, true ); // session ??
209
210 $context = new RequestContext();
211 $context->setRequest( $req );
212 $context->setTitle( $title );
213 $context->setUser( $user );
214 $article = new Article( $title );
215 $article->setContext( $context );
216 $ep = new EditPage( $article );
217 $ep->setContextTitle( $title );
218 $ep->importFormData( $req );
219
220 // this is where the edit happens!
221 // Note: don't want to use EditPage::AttemptSave, because it messes with $wgOut
222 // and throws exceptions like PermissionsError
223 $status = $ep->attemptSave( $result );
224
225 if ( $expectedCode !== null ) {
226 // check edit code
227 $this->assertEquals( $expectedCode, $status->value,
228 "Expected result code mismatch. $message" );
229 }
230
231 $page = $wikiPageFactory->newFromTitle( $title );
232
233 if ( $expectedText !== null ) {
234 // check resulting page text
235 $content = $page->getContent();
236 $text = ( $content instanceof TextContent ) ? $content->getText() : '';
237
238 # EditPage rtrim() the user input, so we alter our expected text
239 # to reflect that.
240 $this->assertEditedTextEquals( $expectedText, $text,
241 "Expected article text mismatch. $message" );
242 }
243
244 return $page;
245 }
246
247 public static function provideCreatePages() {
248 return [
249 [ 'expected article being created',
250 'EditPageTest_testCreatePage',
251 'user',
252 'Hello World!',
253 EditPage::AS_SUCCESS_NEW_ARTICLE,
254 'Hello World!'
255 ],
256 [ 'expected article not being created if empty',
257 'EditPageTest_testCreatePage',
258 'user',
259 '',
260 EditPage::AS_BLANK_ARTICLE,
261 null
262 ],
263 [ 'expected MediaWiki: page being created',
264 'MediaWiki:January',
265 'UTSysop',
266 'Not January',
267 EditPage::AS_SUCCESS_NEW_ARTICLE,
268 'Not January'
269 ],
270 [ 'expected not-registered MediaWiki: page not being created if empty',
271 'MediaWiki:EditPageTest_testCreatePage',
272 'UTSysop',
273 '',
274 EditPage::AS_BLANK_ARTICLE,
275 null
276 ],
277 [ 'expected registered MediaWiki: page being created even if empty',
278 'MediaWiki:January',
279 'UTSysop',
280 '',
281 EditPage::AS_SUCCESS_NEW_ARTICLE,
282 ''
283 ],
284 [ 'expected registered MediaWiki: page whose default content is empty'
285 . ' not being created if empty',
286 'MediaWiki:Ipb-default-expiry',
287 'UTSysop',
288 '',
289 EditPage::AS_BLANK_ARTICLE,
290 ''
291 ],
292 [ 'expected MediaWiki: page not being created if text equals default message',
293 'MediaWiki:January',
294 'UTSysop',
295 'January',
296 EditPage::AS_BLANK_ARTICLE,
297 null
298 ],
299 [ 'expected empty article being created',
300 'EditPageTest_testCreatePage',
301 'user',
302 '',
303 EditPage::AS_SUCCESS_NEW_ARTICLE,
304 '',
305 true
306 ],
307 ];
308 }
309
310 /**
311 * @dataProvider provideCreatePages
312 * @covers \MediaWiki\EditPage\EditPage
313 */
314 public function testCreatePage(
315 $desc, $pageTitle, $user, $editText, $expectedCode, $expectedText, $ignoreBlank = false
316 ) {
317 $checkId = null;
318
319 $this->setTemporaryHook(
320 'PageSaveComplete',
321 static function (
322 WikiPage $page, UserIdentity $user, string $summary,
323 int $flags, RevisionRecord $revisionRecord, EditResult $editResult
324 ) use ( &$checkId ) {
325 $checkId = $revisionRecord->getId();
326 // types/refs checked
327 }
328 );
329
330 $edit = [ 'wpTextbox1' => $editText ];
331 if ( $ignoreBlank ) {
332 $edit['wpIgnoreBlankArticle'] = 1;
333 }
334
335 $page = $this->assertEdit( $pageTitle, null, $user, $edit, $expectedCode, $expectedText, $desc );
336
337 if ( $expectedCode != EditPage::AS_BLANK_ARTICLE ) {
338 $latest = $page->getLatest();
339 $this->deletePage( $page );
340
341 $this->assertGreaterThan( 0, $latest, "Page revision ID updated in object" );
342 $this->assertEquals( $latest, $checkId, "Revision in Status for hook" );
343 }
344 }
345
346 /**
347 * @dataProvider provideCreatePages
348 * @covers \MediaWiki\EditPage\EditPage
349 */
350 public function testCreatePageTrx(
351 $desc, $pageTitle, $user, $editText, $expectedCode, $expectedText, $ignoreBlank = false
352 ) {
353 $checkIds = [];
354 $this->setTemporaryHook(
355 'PageSaveComplete',
356 static function (
357 WikiPage $page, UserIdentity $user, string $summary,
358 int $flags, RevisionRecord $revisionRecord, EditResult $editResult
359 ) use ( &$checkIds ) {
360 $checkIds[] = $revisionRecord->getId();
361 // types/refs checked
362 }
363 );
364
365 $this->getDb()->begin( __METHOD__ );
366
367 $edit = [ 'wpTextbox1' => $editText ];
368 if ( $ignoreBlank ) {
369 $edit['wpIgnoreBlankArticle'] = 1;
370 }
371
372 $page = $this->assertEdit(
373 $pageTitle, null, $user, $edit, $expectedCode, $expectedText, $desc );
374
375 $pageTitle2 = (string)$pageTitle . '/x';
376 $page2 = $this->assertEdit(
377 $pageTitle2, null, $user, $edit, $expectedCode, $expectedText, $desc );
378
379 $this->getDb()->commit( __METHOD__ );
380
381 $this->assertSame( 0, DeferredUpdates::pendingUpdatesCount(), 'No deferred updates' );
382
383 if ( $expectedCode != EditPage::AS_BLANK_ARTICLE ) {
384 $latest = $page->getLatest();
385 $this->deletePage( $page );
386
387 $this->assertGreaterThan( 0, $latest, "Page #1 revision ID updated in object" );
388 $this->assertEquals( $latest, $checkIds[0], "Revision #1 in Status for hook" );
389
390 $latest2 = $page2->getLatest();
391 $this->deletePage( $page2 );
392
393 $this->assertGreaterThan( 0, $latest2, "Page #2 revision ID updated in object" );
394 $this->assertEquals( $latest2, $checkIds[1], "Revision #2 in Status for hook" );
395 }
396 }
397
398 /**
399 * @covers \MediaWiki\EditPage\EditPage
400 */
401 public function testUpdatePage() {
402 $checkIds = [];
403 $this->setTemporaryHook(
404 'PageSaveComplete',
405 static function (
406 WikiPage $page, UserIdentity $user, string $summary,
407 int $flags, RevisionRecord $revisionRecord, EditResult $editResult
408 ) use ( &$checkIds ) {
409 $checkIds[] = $revisionRecord->getId();
410 // types/refs checked
411 }
412 );
413
414 $text = "one";
415 $edit = [
416 'wpTextbox1' => $text,
417 'wpSummary' => 'first update',
418 ];
419
420 $page = $this->assertEdit( 'EditPageTest_testUpdatePage', "zero", 'user', $edit,
421 EditPage::AS_SUCCESS_UPDATE, $text,
422 "expected successful update with given text" );
423 $this->assertGreaterThan( 0, $checkIds[0], "First event rev ID set" );
424
425 $this->forceRevisionDate( $page, '20120101000000' );
426
427 $text = "two";
428 $edit = [
429 'wpTextbox1' => $text,
430 'wpSummary' => 'second update',
431 ];
432
433 $this->assertEdit( 'EditPageTest_testUpdatePage', null, 'user', $edit,
434 EditPage::AS_SUCCESS_UPDATE, $text,
435 "expected successful update with given text" );
436 $this->assertGreaterThan( 0, $checkIds[1], "Second edit hook rev ID set" );
437 $this->assertGreaterThan( $checkIds[0], $checkIds[1], "Second event rev ID is higher" );
438 }
439
440 /**
441 * @covers \MediaWiki\EditPage\EditPage
442 */
443 public function testUpdateNoMinor() {
444 // Test that page creation can never be minor
445 $edit = [
446 'wpTextbox1' => 'testing',
447 'wpSummary' => 'first update',
448 'wpMinoredit' => 'minor'
449 ];
450
451 $page = $this->assertEdit( 'EditPageTest_testUpdateNoMinor', null, 'user', $edit,
452 EditPage::AS_SUCCESS_NEW_ARTICLE, 'testing', "expected successful update" );
453
454 $this->assertFalse(
455 $page->getRevisionRecord()->isMinor(),
456 'page creation should not be minor'
457 );
458
459 // Test that anons can't make an update minor
460 $this->forceRevisionDate( $page, '20120101000000' );
461
462 $edit = [
463 'wpTextbox1' => 'testing 2',
464 'wpSummary' => 'second update',
465 'wpMinoredit' => 'minor'
466 ];
467
468 // Next assertion uses an anon editor, so disable temp accounts
469 $this->disableAutoCreateTempUser();
470 $page = $this->assertEdit( 'EditPageTest_testUpdateNoMinor', null, 'anon', $edit,
471 EditPage::AS_SUCCESS_UPDATE, 'testing 2', "expected successful update" );
472
473 $this->assertFalse(
474 $page->getRevisionRecord()->isMinor(),
475 'anon edit should not be minor'
476 );
477
478 // Test that users can make an update minor
479 $this->forceRevisionDate( $page, '20120102000000' );
480
481 $edit = [
482 'wpTextbox1' => 'testing 3',
483 'wpSummary' => 'third update',
484 'wpMinoredit' => 'minor'
485 ];
486
487 $page = $this->assertEdit( 'EditPageTest_testUpdateNoMinor', null, 'user', $edit,
488 EditPage::AS_SUCCESS_UPDATE, 'testing 3', "expected successful update" );
489
490 $this->assertTrue(
491 $page->getRevisionRecord()->isMinor(),
492 'users can make edits minor'
493 );
494 }
495
496 /**
497 * @covers \MediaWiki\EditPage\EditPage
498 */
499 public function testUpdatePageTrx() {
500 $text = "one";
501 $edit = [
502 'wpTextbox1' => $text,
503 'wpSummary' => 'first update',
504 ];
505
506 $page = $this->assertEdit( 'EditPageTest_testTrxUpdatePage', "zero", 'user', $edit,
507 EditPage::AS_SUCCESS_UPDATE, $text,
508 "expected successful update with given text" );
509
510 $this->forceRevisionDate( $page, '20120101000000' );
511
512 $checkIds = [];
513 $this->setTemporaryHook(
514 'PageSaveComplete',
515 static function (
516 WikiPage $page, UserIdentity $user, string $summary,
517 int $flags, RevisionRecord $revisionRecord, EditResult $editResult
518 ) use ( &$checkIds ) {
519 $checkIds[] = $revisionRecord->getId();
520 // types/refs checked
521 }
522 );
523
524 $this->getDb()->begin( __METHOD__ );
525
526 $text = "two";
527 $edit = [
528 'wpTextbox1' => $text,
529 'wpSummary' => 'second update',
530 ];
531
532 $this->assertEdit( 'EditPageTest_testTrxUpdatePage', null, 'user', $edit,
533 EditPage::AS_SUCCESS_UPDATE, $text,
534 "expected successful update with given text" );
535
536 $text = "three";
537 $edit = [
538 'wpTextbox1' => $text,
539 'wpSummary' => 'third update',
540 ];
541
542 $this->assertEdit( 'EditPageTest_testTrxUpdatePage', null, 'user', $edit,
543 EditPage::AS_SUCCESS_UPDATE, $text,
544 "expected successful update with given text" );
545
546 $this->getDb()->commit( __METHOD__ );
547
548 $this->assertGreaterThan( 0, $checkIds[0], "First event rev ID set" );
549 $this->assertGreaterThan( 0, $checkIds[1], "Second edit hook rev ID set" );
550 $this->assertGreaterThan( $checkIds[0], $checkIds[1], "Second event rev ID is higher" );
551 }
552
553 public static function provideSectionEdit() {
554 $title = 'EditPageTest_testSectionEdit';
555 $title2 = Title::newFromText( __FUNCTION__ );
556 $title2->setContentModel( CONTENT_MODEL_CSS );
557 $text = 'Intro
558
559 == one ==
560 first section.
561
562 == two ==
563 second section.
564 ';
565
566 $sectionOne = '== one ==
567 hello
568 ';
569
570 $newSection = '== new section ==
571
572 hello
573 ';
574
575 $textWithNewSectionOne = preg_replace(
576 '/== one ==.*== two ==/ms',
577 "$sectionOne\n== two ==", $text
578 );
579
580 $textWithNewSectionAdded = "$text\n$newSection";
581
582 return [
583 [ # 0
584 $title,
585 $text,
586 '',
587 'hello',
588 'replace all',
589 'hello'
590 ],
591
592 [ # 1
593 $title,
594 $text,
595 '1',
596 $sectionOne,
597 'replace first section',
598 $textWithNewSectionOne,
599 ],
600
601 [ # 2
602 $title,
603 $text,
604 'new',
605 'hello',
606 'new section',
607 $textWithNewSectionAdded,
608 ],
609
610 [ # 3 Section edit not supported
611 $title2,
612 $text,
613 '1',
614 'hello',
615 '',
616 '',
617 ],
618 ];
619 }
620
621 /**
622 * @dataProvider provideSectionEdit
623 * @covers \MediaWiki\EditPage\EditPage
624 */
625 public function testSectionEdit( $title, $base, $section, $text, $summary, $expected ) {
626 $edit = [
627 'wpTextbox1' => $text,
628 'wpSummary' => $summary,
629 'wpSection' => $section,
630 ];
631
632 $msg = "expected successful update of section";
633 $result = EditPage::AS_SUCCESS_UPDATE;
634
635 if ( $title instanceof Title ) {
636 $result = null;
637 $this->expectException( ErrorPageError::class );
638 }
639 $this->assertEdit( $title, $base, 'user', $edit, $result, $expected, $msg );
640 }
641
642 public static function provideConflictDetection() {
643 yield 'no conflict detected' => [
644 'Adam',
645 [
646 'wpEdittime' => 2, // use the second edit's time
647 'editRevId' => 2, // use the second edit's revision ID
648 ],
649 EditPage::AS_SUCCESS_UPDATE,
650 'successful update expected'
651 ];
652
653 yield 'conflict detected based on wpEdittime' => [
654 'Adam',
655 [
656 'wpEdittime' => 1, // use the first edit's time
657 ],
658 EditPage::AS_CONFLICT_DETECTED,
659 'conflict expected'
660 ];
661
662 yield 'conflict detected based on editRevId' => [
663 'Adam',
664 [
665 'editRevId' => 1, // use the first edit's revision ID
666 ],
667 EditPage::AS_CONFLICT_DETECTED,
668 'conflict expected'
669 ];
670
671 yield 'conflict based on wpEdittime ignored for same user' => [
672 'Berta',
673 [
674 'wpEdittime' => 1, // use the first edit's time
675 ],
676 EditPage::AS_SUCCESS_UPDATE,
677 'successful update expected'
678 ];
679
680 yield 'conflict detected based on editRevId even for same user' => [
681 'Berta',
682 [
683 'editRevId' => 1, // use the first edit's revision ID
684 ],
685 EditPage::AS_CONFLICT_DETECTED,
686 'conflict expected'
687 ];
688 }
689
690 /**
691 * @dataProvider provideConflictDetection
692 * @covers \MediaWiki\EditPage\EditPage
693 */
694 public function testConflictDetection( $editUser, $newEdit, $expectedCode, $message ) {
695 // create page
696 $ns = $this->getDefaultWikitextNS();
697 $title = Title::newFromText( __METHOD__, $ns );
698 $wikiPageFactory = $this->getServiceContainer()->getWikiPageFactory();
699 $page = $wikiPageFactory->newFromTitle( $title );
700
701 if ( $page->exists() ) {
702 $this->deletePage( $page, "clean slate for testing" );
703 }
704
705 $elmosEdit['wpTextbox1'] = 'Elmo\'s text';
706 $bertasEdit['wpTextbox1'] = 'Berta\'s text';
707 $newEdit['wpTextbox1'] = 'new text';
708
709 $elmosEdit['wpSummary'] = 'Elmo\'s edit';
710 $bertasEdit['wpSummary'] = 'Bertas\'s edit';
711 $newEdit['wpSummary'] ??= 'new edit';
712
713 // first edit: Elmo
714 $page = $this->assertEdit( __METHOD__, null, 'Elmo', $elmosEdit,
715 EditPage::AS_SUCCESS_NEW_ARTICLE, null, 'expected successful creation' );
716
717 $this->forceRevisionDate( $page, '20120101000000' );
718 $rev1 = $page->getRevisionRecord();
719
720 // second edit: Berta
721 $page = $this->assertEdit( __METHOD__, null, 'Berta', $bertasEdit,
722 EditPage::AS_SUCCESS_UPDATE, null, 'expected successful update' );
723
724 $this->forceRevisionDate( $page, '20120101111111' );
725 $rev2 = $page->getRevisionRecord();
726
727 if ( !empty( $newEdit['editRevId'] ) ) {
728 $newEdit['editRevId'] = $newEdit['editRevId'] === 1 ? $rev1->getId() : $rev2->getId();
729 }
730
731 if ( !empty( $newEdit['wpEdittime'] ) ) {
732 $newEdit['wpEdittime'] =
733 $newEdit['wpEdittime'] === 1 ? $rev1->getTimestamp() : $rev2->getTimestamp();
734 }
735
736 // third edit
737 $this->assertEdit( __METHOD__, null, $editUser, $newEdit,
738 $expectedCode, null, $message );
739 }
740
741 public static function provideAutoMerge() {
742 $tests = [];
743
744 $tests[] = [ # 0: plain conflict
745 "Elmo", # base edit user
746 "one\n\ntwo\n\nthree\n",
747 [ # adam's edit
748 'wpTextbox1' => "ONE\n\ntwo\n\nthree\n",
749 ],
750 [ # berta's edit
751 'wpTextbox1' => "(one)\n\ntwo\n\nthree\n",
752 ],
753 EditPage::AS_CONFLICT_DETECTED, # expected code
754 "ONE\n\ntwo\n\nthree\n", # expected text
755 'expected edit conflict', # message
756 ];
757
758 $tests[] = [ # 1: successful merge
759 "Elmo", # base edit user
760 "one\n\ntwo\n\nthree\n",
761 [ # adam's edit
762 'wpStarttime' => 1,
763 'wpTextbox1' => "ONE\n\ntwo\n\nthree\n",
764 ],
765 [ # berta's edit
766 'wpStarttime' => 2,
767 'wpTextbox1' => "one\n\ntwo\n\nTHREE\n",
768 ],
769 EditPage::AS_SUCCESS_UPDATE, # expected code
770 "ONE\n\ntwo\n\nTHREE\n", # expected text
771 'expected automatic merge', # message
772 ];
773
774 $text = "Intro\n\n";
775 $text .= "== first section ==\n\n";
776 $text .= "one\n\ntwo\n\nthree\n\n";
777 $text .= "== second section ==\n\n";
778 $text .= "four\n\nfive\n\nsix\n\n";
779
780 // extract the first section.
781 $section = preg_replace( '/.*(== first section ==.*)== second section ==.*/sm', '$1', $text );
782
783 // generate expected text after merge
784 $expected = str_replace( 'one', 'ONE', str_replace( 'three', 'THREE', $text ) );
785
786 $tests[] = [ # 2: merge in section
787 "Elmo", # base edit user
788 $text,
789 [ # adam's edit
790 'wpTextbox1' => str_replace( 'one', 'ONE', $section ),
791 'wpSection' => '1'
792 ],
793 [ # berta's edit
794 'wpTextbox1' => str_replace( 'three', 'THREE', $section ),
795 'wpSection' => '1'
796 ],
797 EditPage::AS_SUCCESS_UPDATE, # expected code
798 $expected, # expected text
799 'expected automatic section merge', # message
800 ];
801
802 // see whether it makes a difference who did the base edit
803 $testsWithAdam = array_map( static function ( $test ) {
804 $test[0] = 'Adam'; // change base edit user
805 return $test;
806 }, $tests );
807
808 $testsWithBerta = array_map( static function ( $test ) {
809 $test[0] = 'Berta'; // change base edit user
810 return $test;
811 }, $tests );
812
813 return array_merge( $tests, $testsWithAdam, $testsWithBerta );
814 }
815
816 /**
817 * @dataProvider provideAutoMerge
818 * @covers \MediaWiki\EditPage\EditPage
819 */
820 public function testAutoMerge( $baseUser, $text, $adamsEdit, $bertasEdit,
821 $expectedCode, $expectedText, $message = null
822 ) {
823 $this->markTestSkippedIfNoDiff3();
824
825 // create page
826 $ns = $this->getDefaultWikitextNS();
827 $title = Title::makeTitle( $ns, 'EditPageTest_testAutoMerge' );
828 $wikiPageFactory = $this->getServiceContainer()->getWikiPageFactory();
829 $page = $wikiPageFactory->newFromTitle( $title );
830
831 if ( $page->exists() ) {
832 $this->deletePage( $page, "clean slate for testing" );
833 }
834
835 $baseEdit = [
836 'wpTextbox1' => $text,
837 ];
838
839 $page = $this->assertEdit( 'EditPageTest_testAutoMerge', null,
840 $baseUser, $baseEdit, null, null, __METHOD__ );
841
842 $this->forceRevisionDate( $page, '20120101000000' );
843
844 $edittime = $page->getTimestamp();
845 $revId = $page->getLatest();
846
847 $adamsEdit['wpSummary'] = 'Adam\'s edit';
848 $bertasEdit['wpSummary'] = 'Bertas\'s edit';
849
850 $adamsEdit['wpEdittime'] = $edittime;
851 $bertasEdit['wpEdittime'] = $edittime;
852
853 $adamsEdit['editRevId'] = $revId;
854 $bertasEdit['editRevId'] = $revId;
855
856 // first edit
857 $this->assertEdit( 'EditPageTest_testAutoMerge', null, 'Adam', $adamsEdit,
858 EditPage::AS_SUCCESS_UPDATE, null, "expected successful update" );
859
860 // second edit
861 $this->assertEdit( 'EditPageTest_testAutoMerge', null, 'Berta', $bertasEdit,
862 $expectedCode, $expectedText, $message );
863 }
864
865 /**
866 * @depends testAutoMerge
867 * @covers \MediaWiki\EditPage\EditPage
868 */
869 public function testCheckDirectEditingDisallowed_forNonTextContent() {
870 $user = self::$editUsers['user'];
871
872 $edit = [
873 'wpTextbox1' => serialize( 'non-text content' ),
874 'wpEditToken' => $user->getEditToken(),
875 'wpEdittime' => '',
876 'editRevId' => 0,
877 'wpStarttime' => wfTimestampNow(),
878 'wpUnicodeCheck' => EditPage::UNICODE_CHECK,
879 ];
880
881 $this->expectException( MWException::class );
882 $this->expectExceptionMessage( 'This content model is not supported: testing' );
883
884 $this->doEditDummyNonTextPage( $edit );
885 }
886
887 /** @covers \MediaWiki\EditPage\EditPage */
888 public function testShouldPreventChangingContentModelWhenUserCannotChangeModelForTitle() {
889 $this->setTemporaryHook( 'getUserPermissionsErrors',
890 static function ( Title $page, $user, $action, &$result ) {
891 if ( $action === 'editcontentmodel' &&
892 $page->getContentModel() === CONTENT_MODEL_WIKITEXT
893 ) {
894 $result = false;
895
896 return false;
897 }
898 } );
899
900 $user = self::$editUsers['user'];
901
902 $status = $this->doEditDummyNonTextPage( [
903 'wpTextbox1' => 'some text',
904 'wpEditToken' => $user->getEditToken(),
905 'wpEdittime' => '',
906 'editRevId' => 0,
907 'wpStarttime' => wfTimestampNow(),
908 'wpUnicodeCheck' => EditPage::UNICODE_CHECK,
909 'model' => CONTENT_MODEL_WIKITEXT,
910 'format' => CONTENT_FORMAT_WIKITEXT,
911 ] );
912
913 $this->assertStatusNotOK( $status );
914 $this->assertStatusValue( EditPage::AS_NO_CHANGE_CONTENT_MODEL, $status );
915 }
916
917 /** @covers \MediaWiki\EditPage\EditPage */
918 public function testShouldPreventChangingContentModelWhenUserCannotEditTargetTitle() {
919 $this->setTemporaryHook( 'getUserPermissionsErrors',
920 static function ( Title $page, $user, $action, &$result ) {
921 if ( $action === 'edit' && $page->getContentModel() === CONTENT_MODEL_WIKITEXT ) {
922 $result = false;
923 return false;
924 }
925 } );
926
927 $user = $this->getTestUser()->getUser();
928
929 $status = $this->doEditDummyNonTextPage( [
930 'wpTextbox1' => 'some text',
931 'wpEditToken' => $user->getEditToken(),
932 'wpEdittime' => '',
933 'editRevId' => 0,
934 'wpStarttime' => wfTimestampNow(),
935 'wpUnicodeCheck' => EditPage::UNICODE_CHECK,
936 'model' => CONTENT_MODEL_WIKITEXT,
937 'format' => CONTENT_FORMAT_WIKITEXT,
938 ] );
939
940 $this->assertStatusNotOK( $status );
941 $this->assertStatusValue( EditPage::AS_NO_CHANGE_CONTENT_MODEL, $status );
942 }
943
944 private function doEditDummyNonTextPage( array $edit ): Status {
945 $title = Title::newFromText( 'Dummy:NonTextPageForEditPage' );
946
947 $article = new Article( $title );
948 $article->getContext()->setTitle( $title );
949 $ep = new EditPage( $article );
950 $ep->setContextTitle( $title );
951
952 $req = new FauxRequest( $edit, true );
953 $ep->importFormData( $req );
954
955 return $ep->attemptSave( $result );
956 }
957
958 /**
959 * The watchlist expiry field should select the entered value on preview, rather than the
960 * calculated number of days till the expiry (as it shows on edit).
961 * @covers \MediaWiki\EditPage\EditPage::getCheckboxesDefinition()
962 * @dataProvider provideWatchlistExpiry()
963 */
964 public function testWatchlistExpiry( $existingExpiry, $postVal, $selected, $options ) {
965 // Set up config and fake current time.
966 $this->overrideConfigValue( MainConfigNames::WatchlistExpiry, true );
967 MWTimestamp::setFakeTime( '20200505120000' );
968 $user = $this->getTestUser()->getUser();
969 $this->assertTrue( $user->isRegistered() );
970
971 // Create the EditPage.
972 $title = Title::newFromText( __METHOD__ );
973 $context = new RequestContext();
974 $context->setUser( $user );
975 $context->setTitle( $title );
976 $article = new Article( $title );
977 $article->setContext( $context );
978 $ep = new EditPage( $article );
979 $this->getServiceContainer()->getWatchlistManager()
980 ->setWatch( (bool)$existingExpiry, $user, $title, $existingExpiry );
981
982 // Send the request.
983 $req = new FauxRequest( [], true );
984 $context->setRequest( $req );
985 $req->getSession()->setUser( $user );
986 $ep->importFormData( $req );
987 $def = $ep->getCheckboxesDefinition( [ 'watch' => true, 'wpWatchlistExpiry' => $postVal ] )['wpWatchlistExpiry'];
988
989 // Test selected and available options.
990 $this->assertSame( $selected, $def['default'] );
991 $dropdownOptions = [];
992 foreach ( $def['options'] as $option ) {
993 // Reformat dropdown options for easier test comparison.
994 $dropdownOptions[] = $option['data'];
995 }
996 $this->assertSame( $options, $dropdownOptions );
997 }
998
999 public static function provideWatchlistExpiry() {
1000 $standardOptions = [ 'infinite', '1 week', '1 month', '3 months', '6 months', '1 year' ];
1001 return [
1002 'not watched, request nothing' => [
1003 'existingExpiry' => '',
1004 'postVal' => '',
1005 'selected' => 'infinite',
1006 'options' => $standardOptions,
1007 ],
1008 'not watched' => [
1009 'existingExpiry' => '',
1010 'postVal' => '1 month',
1011 'result' => '1 month',
1012 'options' => $standardOptions,
1013 ],
1014 'watched with current selected' => [
1015 'existingExpiry' => '2020-05-05T12:00:01Z',
1016 'postVal' => '2020-05-05T12:00:01Z',
1017 'result' => '2020-05-05T12:00:01Z',
1018 'options' => array_merge( [ '2020-05-05T12:00:01Z' ], $standardOptions ),
1019 ],
1020 'watched with 1 week selected' => [
1021 'existingExpiry' => '2020-05-05T12:00:02Z',
1022 'postVal' => '1 week',
1023 'result' => '1 week',
1024 'options' => array_merge( [ '2020-05-05T12:00:02Z' ], $standardOptions ),
1025 ],
1026 ];
1027 }
1028
1029 /**
1030 * T277204
1031 * @covers \MediaWiki\EditPage\EditPage
1032 */
1033 public function testFalseyEditRevId() {
1034 $elmosEdit['wpTextbox1'] = 'Elmo\'s text';
1035 $bertasEdit['wpTextbox1'] = 'Berta\'s text';
1036
1037 $elmosEdit['wpSummary'] = 'Elmo\'s edit';
1038 $bertasEdit['wpSummary'] = 'Bertas\'s edit';
1039
1040 $bertasEdit['editRevId'] = 0;
1041
1042 $this->assertEdit( __METHOD__,
1043 null, 'Elmo', $elmosEdit,
1044 EditPage::AS_SUCCESS_NEW_ARTICLE, null, 'expected successful creation' );
1045
1046 // A successful update would probably be OK too. The important thing is
1047 // that it doesn't throw an exception.
1048 $this->assertEdit( __METHOD__, null, 'Berta', $bertasEdit,
1049 EditPage::AS_CONFLICT_DETECTED, null, 'expected successful update' );
1050 }
1051
1052 }