Merge "Diff and history link separated via CSS"
[lhc/web/wiklou.git] / tests / phpunit / includes / BlockTest.php
1 <?php
2
3 use MediaWiki\Block\BlockRestriction;
4 use MediaWiki\Block\Restriction\PageRestriction;
5
6 /**
7 * @group Database
8 * @group Blocking
9 */
10 class BlockTest extends MediaWikiLangTestCase {
11
12 /**
13 * @return User
14 */
15 private function getUserForBlocking() {
16 $testUser = $this->getMutableTestUser();
17 $user = $testUser->getUser();
18 $user->addToDatabase();
19 TestUser::setPasswordForUser( $user, 'UTBlockeePassword' );
20 $user->saveSettings();
21 return $user;
22 }
23
24 /**
25 * @param User $user
26 *
27 * @return Block
28 * @throws MWException
29 */
30 private function addBlockForUser( User $user ) {
31 // Delete the last round's block if it's still there
32 $oldBlock = Block::newFromTarget( $user->getName() );
33 if ( $oldBlock ) {
34 // An old block will prevent our new one from saving.
35 $oldBlock->delete();
36 }
37
38 $blockOptions = [
39 'address' => $user->getName(),
40 'user' => $user->getId(),
41 'by' => $this->getTestSysop()->getUser()->getId(),
42 'reason' => 'Parce que',
43 'expiry' => time() + 100500,
44 ];
45 $block = new Block( $blockOptions );
46
47 $block->insert();
48 // save up ID for use in assertion. Since ID is an autoincrement,
49 // its value might change depending on the order the tests are run.
50 // ApiBlockTest insert its own blocks!
51 if ( !$block->getId() ) {
52 throw new MWException( "Failed to insert block for BlockTest; old leftover block remaining?" );
53 }
54
55 $this->addXffBlocks();
56
57 return $block;
58 }
59
60 /**
61 * @covers Block::newFromTarget
62 */
63 public function testINewFromTargetReturnsCorrectBlock() {
64 $user = $this->getUserForBlocking();
65 $block = $this->addBlockForUser( $user );
66
67 $this->assertTrue(
68 $block->equals( Block::newFromTarget( $user->getName() ) ),
69 "newFromTarget() returns the same block as the one that was made"
70 );
71 }
72
73 /**
74 * @covers Block::newFromID
75 */
76 public function testINewFromIDReturnsCorrectBlock() {
77 $user = $this->getUserForBlocking();
78 $block = $this->addBlockForUser( $user );
79
80 $this->assertTrue(
81 $block->equals( Block::newFromID( $block->getId() ) ),
82 "newFromID() returns the same block as the one that was made"
83 );
84 }
85
86 /**
87 * per T28425
88 * @covers Block::__construct
89 */
90 public function testT28425BlockTimestampDefaultsToTime() {
91 $user = $this->getUserForBlocking();
92 $block = $this->addBlockForUser( $user );
93 $madeAt = wfTimestamp( TS_MW );
94
95 // delta to stop one-off errors when things happen to go over a second mark.
96 $delta = abs( $madeAt - $block->mTimestamp );
97 $this->assertLessThan(
98 2,
99 $delta,
100 "If no timestamp is specified, the block is recorded as time()"
101 );
102 }
103
104 /**
105 * CheckUser since being changed to use Block::newFromTarget started failing
106 * because the new function didn't accept empty strings like Block::load()
107 * had. Regression T31116.
108 *
109 * @dataProvider provideT31116Data
110 * @covers Block::newFromTarget
111 */
112 public function testT31116NewFromTargetWithEmptyIp( $vagueTarget ) {
113 $user = $this->getUserForBlocking();
114 $initialBlock = $this->addBlockForUser( $user );
115 $block = Block::newFromTarget( $user->getName(), $vagueTarget );
116
117 $this->assertTrue(
118 $initialBlock->equals( $block ),
119 "newFromTarget() returns the same block as the one that was made when "
120 . "given empty vagueTarget param " . var_export( $vagueTarget, true )
121 );
122 }
123
124 public static function provideT31116Data() {
125 return [
126 [ null ],
127 [ '' ],
128 [ false ]
129 ];
130 }
131
132 /**
133 * @covers Block::prevents
134 */
135 public function testBlockedUserCanNotCreateAccount() {
136 $username = 'BlockedUserToCreateAccountWith';
137 $u = User::newFromName( $username );
138 $u->addToDatabase();
139 $userId = $u->getId();
140 $this->assertNotEquals( 0, $userId, 'sanity' );
141 TestUser::setPasswordForUser( $u, 'NotRandomPass' );
142 unset( $u );
143
144 // Sanity check
145 $this->assertNull(
146 Block::newFromTarget( $username ),
147 "$username should not be blocked"
148 );
149
150 // Reload user
151 $u = User::newFromName( $username );
152 $this->assertFalse(
153 $u->isBlockedFromCreateAccount(),
154 "Our sandbox user should be able to create account before being blocked"
155 );
156
157 // Foreign perspective (blockee not on current wiki)...
158 $blockOptions = [
159 'address' => $username,
160 'user' => $userId,
161 'reason' => 'crosswiki block...',
162 'timestamp' => wfTimestampNow(),
163 'expiry' => $this->db->getInfinity(),
164 'createAccount' => true,
165 'enableAutoblock' => true,
166 'hideName' => true,
167 'blockEmail' => true,
168 'byText' => 'm>MetaWikiUser',
169 ];
170 $block = new Block( $blockOptions );
171 $block->insert();
172
173 // Reload block from DB
174 $userBlock = Block::newFromTarget( $username );
175 $this->assertTrue(
176 (bool)$block->prevents( 'createaccount' ),
177 "Block object in DB should prevents 'createaccount'"
178 );
179
180 $this->assertInstanceOf(
181 Block::class,
182 $userBlock,
183 "'$username' block block object should be existent"
184 );
185
186 // Reload user
187 $u = User::newFromName( $username );
188 $this->assertTrue(
189 (bool)$u->isBlockedFromCreateAccount(),
190 "Our sandbox user '$username' should NOT be able to create account"
191 );
192 }
193
194 /**
195 * @covers Block::insert
196 */
197 public function testCrappyCrossWikiBlocks() {
198 // Delete the last round's block if it's still there
199 $oldBlock = Block::newFromTarget( 'UserOnForeignWiki' );
200 if ( $oldBlock ) {
201 // An old block will prevent our new one from saving.
202 $oldBlock->delete();
203 }
204
205 // Local perspective (blockee on current wiki)...
206 $user = User::newFromName( 'UserOnForeignWiki' );
207 $user->addToDatabase();
208 $userId = $user->getId();
209 $this->assertNotEquals( 0, $userId, 'sanity' );
210
211 // Foreign perspective (blockee not on current wiki)...
212 $blockOptions = [
213 'address' => 'UserOnForeignWiki',
214 'user' => $user->getId(),
215 'reason' => 'crosswiki block...',
216 'timestamp' => wfTimestampNow(),
217 'expiry' => $this->db->getInfinity(),
218 'createAccount' => true,
219 'enableAutoblock' => true,
220 'hideName' => true,
221 'blockEmail' => true,
222 'byText' => 'Meta>MetaWikiUser',
223 ];
224 $block = new Block( $blockOptions );
225
226 $res = $block->insert( $this->db );
227 $this->assertTrue( (bool)$res['id'], 'Block succeeded' );
228
229 $user = null; // clear
230
231 $block = Block::newFromID( $res['id'] );
232 $this->assertEquals(
233 'UserOnForeignWiki',
234 $block->getTarget()->getName(),
235 'Correct blockee name'
236 );
237 $this->assertEquals( $userId, $block->getTarget()->getId(), 'Correct blockee id' );
238 $this->assertEquals( 'Meta>MetaWikiUser', $block->getBlocker()->getName(),
239 'Correct blocker name' );
240 $this->assertEquals( 'Meta>MetaWikiUser', $block->getByName(), 'Correct blocker name' );
241 $this->assertEquals( 0, $block->getBy(), 'Correct blocker id' );
242 }
243
244 protected function addXffBlocks() {
245 static $inited = false;
246
247 if ( $inited ) {
248 return;
249 }
250
251 $inited = true;
252
253 $blockList = [
254 [ 'target' => '70.2.0.0/16',
255 'type' => Block::TYPE_RANGE,
256 'desc' => 'Range Hardblock',
257 'ACDisable' => false,
258 'isHardblock' => true,
259 'isAutoBlocking' => false,
260 ],
261 [ 'target' => '2001:4860:4001::/48',
262 'type' => Block::TYPE_RANGE,
263 'desc' => 'Range6 Hardblock',
264 'ACDisable' => false,
265 'isHardblock' => true,
266 'isAutoBlocking' => false,
267 ],
268 [ 'target' => '60.2.0.0/16',
269 'type' => Block::TYPE_RANGE,
270 'desc' => 'Range Softblock with AC Disabled',
271 'ACDisable' => true,
272 'isHardblock' => false,
273 'isAutoBlocking' => false,
274 ],
275 [ 'target' => '50.2.0.0/16',
276 'type' => Block::TYPE_RANGE,
277 'desc' => 'Range Softblock',
278 'ACDisable' => false,
279 'isHardblock' => false,
280 'isAutoBlocking' => false,
281 ],
282 [ 'target' => '50.1.1.1',
283 'type' => Block::TYPE_IP,
284 'desc' => 'Exact Softblock',
285 'ACDisable' => false,
286 'isHardblock' => false,
287 'isAutoBlocking' => false,
288 ],
289 ];
290
291 $blocker = $this->getTestUser()->getUser();
292 foreach ( $blockList as $insBlock ) {
293 $target = $insBlock['target'];
294
295 if ( $insBlock['type'] === Block::TYPE_IP ) {
296 $target = User::newFromName( IP::sanitizeIP( $target ), false )->getName();
297 } elseif ( $insBlock['type'] === Block::TYPE_RANGE ) {
298 $target = IP::sanitizeRange( $target );
299 }
300
301 $block = new Block();
302 $block->setTarget( $target );
303 $block->setBlocker( $blocker );
304 $block->mReason = $insBlock['desc'];
305 $block->mExpiry = 'infinity';
306 $block->prevents( 'createaccount', $insBlock['ACDisable'] );
307 $block->isHardblock( $insBlock['isHardblock'] );
308 $block->isAutoblocking( $insBlock['isAutoBlocking'] );
309 $block->insert();
310 }
311 }
312
313 public static function providerXff() {
314 return [
315 [ 'xff' => '1.2.3.4, 70.2.1.1, 60.2.1.1, 2.3.4.5',
316 'count' => 2,
317 'result' => 'Range Hardblock'
318 ],
319 [ 'xff' => '1.2.3.4, 50.2.1.1, 60.2.1.1, 2.3.4.5',
320 'count' => 2,
321 'result' => 'Range Softblock with AC Disabled'
322 ],
323 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.1.1.1, 2.3.4.5',
324 'count' => 2,
325 'result' => 'Exact Softblock'
326 ],
327 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.2.1.1, 50.1.1.1, 2.3.4.5',
328 'count' => 3,
329 'result' => 'Exact Softblock'
330 ],
331 [ 'xff' => '1.2.3.4, 70.2.1.1, 50.2.1.1, 2.3.4.5',
332 'count' => 2,
333 'result' => 'Range Hardblock'
334 ],
335 [ 'xff' => '1.2.3.4, 70.2.1.1, 60.2.1.1, 2.3.4.5',
336 'count' => 2,
337 'result' => 'Range Hardblock'
338 ],
339 [ 'xff' => '50.2.1.1, 60.2.1.1, 2.3.4.5',
340 'count' => 2,
341 'result' => 'Range Softblock with AC Disabled'
342 ],
343 [ 'xff' => '1.2.3.4, 50.1.1.1, 60.2.1.1, 2.3.4.5',
344 'count' => 2,
345 'result' => 'Exact Softblock'
346 ],
347 [ 'xff' => '1.2.3.4, <$A_BUNCH-OF{INVALID}TEXT\>, 60.2.1.1, 2.3.4.5',
348 'count' => 1,
349 'result' => 'Range Softblock with AC Disabled'
350 ],
351 [ 'xff' => '1.2.3.4, 50.2.1.1, 2001:4860:4001:802::1003, 2.3.4.5',
352 'count' => 2,
353 'result' => 'Range6 Hardblock'
354 ],
355 ];
356 }
357
358 /**
359 * @dataProvider providerXff
360 * @covers Block::getBlocksForIPList
361 * @covers Block::chooseBlock
362 */
363 public function testBlocksOnXff( $xff, $exCount, $exResult ) {
364 $user = $this->getUserForBlocking();
365 $this->addBlockForUser( $user );
366
367 $list = array_map( 'trim', explode( ',', $xff ) );
368 $xffblocks = Block::getBlocksForIPList( $list, true );
369 $this->assertEquals( $exCount, count( $xffblocks ), 'Number of blocks for ' . $xff );
370 $block = Block::chooseBlock( $xffblocks, $list );
371 $this->assertEquals( $exResult, $block->mReason, 'Correct block type for XFF header ' . $xff );
372 }
373
374 /**
375 * @covers Block::__construct
376 */
377 public function testDeprecatedConstructor() {
378 $this->hideDeprecated( 'Block::__construct with multiple arguments' );
379 $username = 'UnthinkablySecretRandomUsername';
380 $reason = 'being irrational';
381
382 # Set up the target
383 $u = User::newFromName( $username );
384 if ( $u->getId() == 0 ) {
385 $u->addToDatabase();
386 TestUser::setPasswordForUser( $u, 'TotallyObvious' );
387 }
388 unset( $u );
389
390 # Make sure the user isn't blocked
391 $this->assertNull(
392 Block::newFromTarget( $username ),
393 "$username should not be blocked"
394 );
395
396 # Perform the block
397 $block = new Block(
398 /* address */ $username,
399 /* user */ 0,
400 /* by */ $this->getTestSysop()->getUser()->getId(),
401 /* reason */ $reason,
402 /* timestamp */ 0,
403 /* auto */ false,
404 /* expiry */ 0
405 );
406 $block->insert();
407
408 # Check target
409 $this->assertEquals(
410 $block->getTarget()->getName(),
411 $username,
412 "Target should be set properly"
413 );
414
415 # Check supplied parameter
416 $this->assertEquals(
417 $block->mReason,
418 $reason,
419 "Reason should be non-default"
420 );
421
422 # Check default parameter
423 $this->assertFalse(
424 (bool)$block->prevents( 'createaccount' ),
425 "Account creation should not be blocked by default"
426 );
427 }
428
429 /**
430 * @covers Block::getSystemBlockType
431 * @covers Block::insert
432 * @covers Block::doAutoblock
433 */
434 public function testSystemBlocks() {
435 $user = $this->getUserForBlocking();
436 $this->addBlockForUser( $user );
437
438 $blockOptions = [
439 'address' => $user->getName(),
440 'reason' => 'test system block',
441 'timestamp' => wfTimestampNow(),
442 'expiry' => $this->db->getInfinity(),
443 'byText' => 'MediaWiki default',
444 'systemBlock' => 'test',
445 'enableAutoblock' => true,
446 ];
447 $block = new Block( $blockOptions );
448
449 $this->assertSame( 'test', $block->getSystemBlockType() );
450
451 try {
452 $block->insert();
453 $this->fail( 'Expected exception not thrown' );
454 } catch ( MWException $ex ) {
455 $this->assertSame( 'Cannot insert a system block into the database', $ex->getMessage() );
456 }
457
458 try {
459 $block->doAutoblock( '192.0.2.2' );
460 $this->fail( 'Expected exception not thrown' );
461 } catch ( MWException $ex ) {
462 $this->assertSame( 'Cannot autoblock from a system block', $ex->getMessage() );
463 }
464 }
465
466 /**
467 * @covers Block::newFromRow
468 */
469 public function testNewFromRow() {
470 $badActor = $this->getTestUser()->getUser();
471 $sysop = $this->getTestSysop()->getUser();
472
473 $block = new Block( [
474 'address' => $badActor->getName(),
475 'user' => $badActor->getId(),
476 'by' => $sysop->getId(),
477 'expiry' => 'infinity',
478 ] );
479 $block->insert();
480
481 $blockQuery = Block::getQueryInfo();
482 $row = $this->db->select(
483 $blockQuery['tables'],
484 $blockQuery['fields'],
485 [
486 'ipb_id' => $block->getId(),
487 ],
488 __METHOD__,
489 [],
490 $blockQuery['joins']
491 )->fetchObject();
492
493 $block = Block::newFromRow( $row );
494 $this->assertInstanceOf( Block::class, $block );
495 $this->assertEquals( $block->getBy(), $sysop->getId() );
496 $this->assertEquals( $block->getTarget()->getName(), $badActor->getName() );
497 $block->delete();
498 }
499
500 /**
501 * @covers Block::equals
502 */
503 public function testEquals() {
504 $block = new Block();
505
506 $this->assertTrue( $block->equals( $block ) );
507
508 $partial = new Block( [
509 'sitewide' => false,
510 ] );
511 $this->assertFalse( $block->equals( $partial ) );
512 }
513
514 /**
515 * @covers Block::isSitewide
516 */
517 public function testIsSitewide() {
518 $block = new Block();
519 $this->assertTrue( $block->isSitewide() );
520
521 $block = new Block( [
522 'sitewide' => true,
523 ] );
524 $this->assertTrue( $block->isSitewide() );
525
526 $block = new Block( [
527 'sitewide' => false,
528 ] );
529 $this->assertFalse( $block->isSitewide() );
530
531 $block = new Block( [
532 'sitewide' => false,
533 ] );
534 $block->isSitewide( true );
535 $this->assertTrue( $block->isSitewide() );
536 }
537
538 /**
539 * @covers Block::getRestrictions
540 * @covers Block::setRestrictions
541 */
542 public function testRestrictions() {
543 $block = new Block();
544 $restrictions = [
545 new PageRestriction( 0, 1 )
546 ];
547 $block->setRestrictions( $restrictions );
548
549 $this->assertSame( $restrictions, $block->getRestrictions() );
550 }
551
552 /**
553 * @covers Block::getRestrictions
554 * @covers Block::insert
555 */
556 public function testRestrictionsFromDatabase() {
557 $badActor = $this->getTestUser()->getUser();
558 $sysop = $this->getTestSysop()->getUser();
559
560 $block = new Block( [
561 'address' => $badActor->getName(),
562 'user' => $badActor->getId(),
563 'by' => $sysop->getId(),
564 'expiry' => 'infinity',
565 ] );
566 $page = $this->getExistingTestPage( 'Foo' );
567 $restriction = new PageRestriction( 0, $page->getId() );
568 $block->setRestrictions( [ $restriction ] );
569 $block->insert();
570
571 // Refresh the block from the database.
572 $block = Block::newFromID( $block->getId() );
573 $restrictions = $block->getRestrictions();
574 $this->assertCount( 1, $restrictions );
575 $this->assertTrue( $restriction->equals( $restrictions[0] ) );
576 $block->delete();
577 }
578
579 /**
580 * @covers Block::insert
581 */
582 public function testInsertExistingBlock() {
583 $badActor = $this->getTestUser()->getUser();
584 $sysop = $this->getTestSysop()->getUser();
585
586 $block = new Block( [
587 'address' => $badActor->getName(),
588 'user' => $badActor->getId(),
589 'by' => $sysop->getId(),
590 'expiry' => 'infinity',
591 ] );
592 $page = $this->getExistingTestPage( 'Foo' );
593 $restriction = new PageRestriction( 0, $page->getId() );
594 $block->setRestrictions( [ $restriction ] );
595 $block->insert();
596
597 // Insert the block again, which should result in a failur
598 $result = $block->insert();
599
600 $this->assertFalse( $result );
601
602 // Ensure that there are no restrictions where the blockId is 0.
603 $count = $this->db->selectRowCount(
604 'ipblocks_restrictions',
605 '*',
606 [ 'ir_ipb_id' => 0 ],
607 __METHOD__
608 );
609 $this->assertSame( 0, $count );
610
611 $block->delete();
612 }
613
614 /**
615 * @covers Block::preventsEdit
616 */
617 public function testPreventsEditReturnsTrueOnSitewideBlock() {
618 $user = $this->getTestUser()->getUser();
619 $block = new Block( [
620 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
621 'allowUsertalk' => true,
622 'sitewide' => true
623 ] );
624
625 $block->setTarget( $user );
626 $block->setBlocker( $this->getTestSysop()->getUser() );
627 $block->insert();
628
629 $title = $this->getExistingTestPage( 'Foo' )->getTitle();
630
631 $this->assertTrue( $block->preventsEdit( $title ) );
632
633 $block->delete();
634 }
635
636 /**
637 * @covers Block::preventsEdit
638 */
639 public function testPreventsEditOnPartialBlock() {
640 $user = $this->getTestUser()->getUser();
641 $block = new Block( [
642 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
643 'allowUsertalk' => true,
644 'sitewide' => false
645 ] );
646
647 $block->setTarget( $user );
648 $block->setBlocker( $this->getTestSysop()->getUser() );
649 $block->insert();
650
651 $pageFoo = $this->getExistingTestPage( 'Foo' );
652 $pageBar = $this->getExistingTestPage( 'Bar' );
653
654 $pageRestriction = new PageRestriction( $block->getId(), $pageFoo->getId() );
655 BlockRestriction::insert( [ $pageRestriction ] );
656
657 $this->assertTrue( $block->preventsEdit( $pageFoo->getTitle() ) );
658 $this->assertFalse( $block->preventsEdit( $pageBar->getTitle() ) );
659
660 $block->delete();
661 }
662
663 /**
664 * @covers Block::preventsEdit
665 * @dataProvider preventsEditOnUserTalkProvider
666 */
667 public function testPreventsEditOnUserTalkPage(
668 $allowUsertalk, $sitewide, $result, $blockAllowsUTEdit = true
669 ) {
670 $this->setMwGlobals( [
671 'wgBlockAllowsUTEdit' => $blockAllowsUTEdit,
672 ] );
673
674 $user = $this->getTestUser()->getUser();
675 $block = new Block( [
676 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
677 'allowUsertalk' => $allowUsertalk,
678 'sitewide' => $sitewide
679 ] );
680
681 $block->setTarget( $user );
682 $block->setBlocker( $this->getTestSysop()->getUser() );
683 $block->insert();
684
685 $this->assertEquals( $result, $block->preventsEdit( $user->getTalkPage() ) );
686 $block->delete();
687 }
688
689 public function preventsEditOnUserTalkProvider() {
690 return [
691 [
692 'allowUsertalk' => false,
693 'sitewide' => true,
694 'result' => true,
695 ],
696 [
697 'allowUsertalk' => true,
698 'sitewide' => true,
699 'result' => false,
700 ],
701 [
702 'allowUsertalk' => true,
703 'sitewide' => false,
704 'result' => false,
705 ],
706 [
707 'allowUsertalk' => false,
708 'sitewide' => false,
709 'result' => true,
710 ],
711 [
712 'allowUsertalk' => true,
713 'sitewide' => true,
714 'result' => true,
715 'blockAllowsUTEdit' => false
716 ],
717 [
718 'allowUsertalk' => true,
719 'sitewide' => false,
720 'result' => true,
721 'blockAllowsUTEdit' => false
722 ],
723 ];
724 }
725 }