164b46644db25d539ea50297adba2914bf360193
[lhc/web/wiklou.git] / tests / phpunit / includes / user / UserTest.php
1 <?php
2
3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
5
6 use MediaWiki\Block\Restriction\PageRestriction;
7 use MediaWiki\Block\Restriction\NamespaceRestriction;
8 use MediaWiki\MediaWikiServices;
9 use MediaWiki\User\UserIdentityValue;
10 use Wikimedia\TestingAccessWrapper;
11
12 /**
13 * @group Database
14 */
15 class UserTest extends MediaWikiTestCase {
16
17 /** Constant for self::testIsBlockedFrom */
18 const USER_TALK_PAGE = '<user talk page>';
19
20 /**
21 * @var User
22 */
23 protected $user;
24
25 protected function setUp() {
26 parent::setUp();
27
28 $this->setMwGlobals( [
29 'wgGroupPermissions' => [],
30 'wgRevokePermissions' => [],
31 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD,
32 ] );
33 $this->overrideMwServices();
34
35 $this->setUpPermissionGlobals();
36
37 $this->user = $this->getTestUser( [ 'unittesters' ] )->getUser();
38 }
39
40 private function setUpPermissionGlobals() {
41 global $wgGroupPermissions, $wgRevokePermissions;
42
43 # Data for regular $wgGroupPermissions test
44 $wgGroupPermissions['unittesters'] = [
45 'test' => true,
46 'runtest' => true,
47 'writetest' => false,
48 'nukeworld' => false,
49 ];
50 $wgGroupPermissions['testwriters'] = [
51 'test' => true,
52 'writetest' => true,
53 'modifytest' => true,
54 ];
55
56 # Data for regular $wgRevokePermissions test
57 $wgRevokePermissions['formertesters'] = [
58 'runtest' => true,
59 ];
60
61 # For the options test
62 $wgGroupPermissions['*'] = [
63 'editmyoptions' => true,
64 ];
65 }
66
67 /**
68 * @covers User::getGroupPermissions
69 */
70 public function testGroupPermissions() {
71 $rights = User::getGroupPermissions( [ 'unittesters' ] );
72 $this->assertContains( 'runtest', $rights );
73 $this->assertNotContains( 'writetest', $rights );
74 $this->assertNotContains( 'modifytest', $rights );
75 $this->assertNotContains( 'nukeworld', $rights );
76
77 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
78 $this->assertContains( 'runtest', $rights );
79 $this->assertContains( 'writetest', $rights );
80 $this->assertContains( 'modifytest', $rights );
81 $this->assertNotContains( 'nukeworld', $rights );
82 }
83
84 /**
85 * @covers User::getGroupPermissions
86 */
87 public function testRevokePermissions() {
88 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
89 $this->assertNotContains( 'runtest', $rights );
90 $this->assertNotContains( 'writetest', $rights );
91 $this->assertNotContains( 'modifytest', $rights );
92 $this->assertNotContains( 'nukeworld', $rights );
93 }
94
95 /**
96 * @covers User::getRights
97 */
98 public function testUserPermissions() {
99 $rights = $this->user->getRights();
100 $this->assertContains( 'runtest', $rights );
101 $this->assertNotContains( 'writetest', $rights );
102 $this->assertNotContains( 'modifytest', $rights );
103 $this->assertNotContains( 'nukeworld', $rights );
104 }
105
106 /**
107 * @covers User::getRights
108 */
109 public function testUserGetRightsHooks() {
110 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
111 $userWrapper = TestingAccessWrapper::newFromObject( $user );
112
113 $rights = $user->getRights();
114 $this->assertContains( 'test', $rights, 'sanity check' );
115 $this->assertContains( 'runtest', $rights, 'sanity check' );
116 $this->assertContains( 'writetest', $rights, 'sanity check' );
117 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
118
119 // Add a hook manipluating the rights
120 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
121 $rights[] = 'nukeworld';
122 $rights = array_diff( $rights, [ 'writetest' ] );
123 } ] ] );
124
125 $userWrapper->mRights = null;
126 $rights = $user->getRights();
127 $this->assertContains( 'test', $rights );
128 $this->assertContains( 'runtest', $rights );
129 $this->assertNotContains( 'writetest', $rights );
130 $this->assertContains( 'nukeworld', $rights );
131
132 // Add a Session that limits rights
133 $mock = $this->getMockBuilder( stdClass::class )
134 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
135 ->getMock();
136 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
137 $mock->method( 'getSessionId' )->willReturn(
138 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
139 );
140 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
141 $mockRequest = $this->getMockBuilder( FauxRequest::class )
142 ->setMethods( [ 'getSession' ] )
143 ->getMock();
144 $mockRequest->method( 'getSession' )->willReturn( $session );
145 $userWrapper->mRequest = $mockRequest;
146
147 $userWrapper->mRights = null;
148 $rights = $user->getRights();
149 $this->assertContains( 'test', $rights );
150 $this->assertNotContains( 'runtest', $rights );
151 $this->assertNotContains( 'writetest', $rights );
152 $this->assertNotContains( 'nukeworld', $rights );
153 }
154
155 /**
156 * @dataProvider provideGetGroupsWithPermission
157 * @covers User::getGroupsWithPermission
158 */
159 public function testGetGroupsWithPermission( $expected, $right ) {
160 $result = User::getGroupsWithPermission( $right );
161 sort( $result );
162 sort( $expected );
163
164 $this->assertEquals( $expected, $result, "Groups with permission $right" );
165 }
166
167 public static function provideGetGroupsWithPermission() {
168 return [
169 [
170 [ 'unittesters', 'testwriters' ],
171 'test'
172 ],
173 [
174 [ 'unittesters' ],
175 'runtest'
176 ],
177 [
178 [ 'testwriters' ],
179 'writetest'
180 ],
181 [
182 [ 'testwriters' ],
183 'modifytest'
184 ],
185 ];
186 }
187
188 /**
189 * @dataProvider provideIPs
190 * @covers User::isIP
191 */
192 public function testIsIP( $value, $result, $message ) {
193 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
194 }
195
196 public static function provideIPs() {
197 return [
198 [ '', false, 'Empty string' ],
199 [ ' ', false, 'Blank space' ],
200 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
201 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
202 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
203 [ '203.0.113.0', true, 'IPv4 example' ],
204 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
205 // Not valid IPs but classified as such by MediaWiki for negated asserting
206 // of whether this might be the identifier of a logged-out user or whether
207 // to allow usernames like it.
208 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
209 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
210 ];
211 }
212
213 /**
214 * @dataProvider provideUserNames
215 * @covers User::isValidUserName
216 */
217 public function testIsValidUserName( $username, $result, $message ) {
218 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
219 }
220
221 public static function provideUserNames() {
222 return [
223 [ '', false, 'Empty string' ],
224 [ ' ', false, 'Blank space' ],
225 [ 'abcd', false, 'Starts with small letter' ],
226 [ 'Ab/cd', false, 'Contains slash' ],
227 [ 'Ab cd', true, 'Whitespace' ],
228 [ '192.168.1.1', false, 'IP' ],
229 [ '116.17.184.5/32', false, 'IP range' ],
230 [ '::e:f:2001/96', false, 'IPv6 range' ],
231 [ 'User:Abcd', false, 'Reserved Namespace' ],
232 [ '12abcd232', true, 'Starts with Numbers' ],
233 [ '?abcd', true, 'Start with ? mark' ],
234 [ '#abcd', false, 'Start with #' ],
235 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
236 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
237 [ 'Ab cd', false, ' Ideographic space' ],
238 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
239 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
240 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
241 ];
242 }
243
244 /**
245 * Test User::editCount
246 * @group medium
247 * @covers User::getEditCount
248 */
249 public function testGetEditCount() {
250 $user = $this->getMutableTestUser()->getUser();
251
252 // let the user have a few (3) edits
253 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
254 for ( $i = 0; $i < 3; $i++ ) {
255 $page->doEditContent(
256 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
257 'test',
258 0,
259 false,
260 $user
261 );
262 }
263
264 $this->assertEquals(
265 3,
266 $user->getEditCount(),
267 'After three edits, the user edit count should be 3'
268 );
269
270 // increase the edit count
271 $user->incEditCount();
272 $user->clearInstanceCache();
273
274 $this->assertEquals(
275 4,
276 $user->getEditCount(),
277 'After increasing the edit count manually, the user edit count should be 4'
278 );
279 }
280
281 /**
282 * Test User::editCount
283 * @group medium
284 * @covers User::getEditCount
285 */
286 public function testGetEditCountForAnons() {
287 $user = User::newFromName( 'Anonymous' );
288
289 $this->assertNull(
290 $user->getEditCount(),
291 'Edit count starts null for anonymous users.'
292 );
293
294 $user->incEditCount();
295
296 $this->assertNull(
297 $user->getEditCount(),
298 'Edit count remains null for anonymous users despite calls to increase it.'
299 );
300 }
301
302 /**
303 * Test User::editCount
304 * @group medium
305 * @covers User::incEditCount
306 */
307 public function testIncEditCount() {
308 $user = $this->getMutableTestUser()->getUser();
309 $user->incEditCount();
310
311 $reloadedUser = User::newFromId( $user->getId() );
312 $reloadedUser->incEditCount();
313
314 $this->assertEquals(
315 2,
316 $reloadedUser->getEditCount(),
317 'Increasing the edit count after a fresh load leaves the object up to date.'
318 );
319 }
320
321 /**
322 * Test changing user options.
323 * @covers User::setOption
324 * @covers User::getOption
325 */
326 public function testOptions() {
327 $user = $this->getMutableTestUser()->getUser();
328
329 $user->setOption( 'userjs-someoption', 'test' );
330 $user->setOption( 'rclimit', 200 );
331 $user->setOption( 'wpwatchlistdays', '0' );
332 $user->saveSettings();
333
334 $user = User::newFromName( $user->getName() );
335 $user->load( User::READ_LATEST );
336 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
337 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
338
339 $user = User::newFromName( $user->getName() );
340 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
341 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
342 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
343
344 // Check that an option saved as a string '0' is returned as an integer.
345 $user = User::newFromName( $user->getName() );
346 $user->load( User::READ_LATEST );
347 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
348 }
349
350 /**
351 * T39963
352 * Make sure defaults are loaded when setOption is called.
353 * @covers User::loadOptions
354 */
355 public function testAnonOptions() {
356 global $wgDefaultUserOptions;
357 $this->user->setOption( 'userjs-someoption', 'test' );
358 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
359 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
360 }
361
362 /**
363 * Test password validity checks. There are 3 checks in core,
364 * - ensure the password meets the minimal length
365 * - ensure the password is not the same as the username
366 * - ensure the username/password combo isn't forbidden
367 * @covers User::checkPasswordValidity()
368 * @covers User::getPasswordValidity()
369 * @covers User::isValidPassword()
370 */
371 public function testCheckPasswordValidity() {
372 $this->setMwGlobals( [
373 'wgPasswordPolicy' => [
374 'policies' => [
375 'sysop' => [
376 'MinimalPasswordLength' => 8,
377 'MinimumPasswordLengthToLogin' => 1,
378 'PasswordCannotMatchUsername' => 1,
379 ],
380 'default' => [
381 'MinimalPasswordLength' => 6,
382 'PasswordCannotMatchUsername' => true,
383 'PasswordCannotMatchBlacklist' => true,
384 'MaximalPasswordLength' => 40,
385 ],
386 ],
387 'checks' => [
388 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
389 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
390 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
391 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
392 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
393 ],
394 ],
395 ] );
396 $this->hideDeprecated( 'User::getPasswordValidity' );
397
398 $user = static::getTestUser()->getUser();
399
400 // Sanity
401 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
402
403 // Minimum length
404 $this->assertFalse( $user->isValidPassword( 'a' ) );
405 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
406 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
407 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
408
409 // Maximum length
410 $longPass = str_repeat( 'a', 41 );
411 $this->assertFalse( $user->isValidPassword( $longPass ) );
412 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
413 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
414 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
415
416 // Matches username
417 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
418 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
419 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
420
421 // On the forbidden list
422 $user = User::newFromName( 'Useruser' );
423 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
424 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
425 }
426
427 /**
428 * @covers User::getCanonicalName()
429 * @dataProvider provideGetCanonicalName
430 */
431 public function testGetCanonicalName( $name, $expectedArray ) {
432 // fake interwiki map for the 'Interwiki prefix' testcase
433 $this->mergeMwGlobalArrayValue( 'wgHooks', [
434 'InterwikiLoadPrefix' => [
435 function ( $prefix, &$iwdata ) {
436 if ( $prefix === 'interwiki' ) {
437 $iwdata = [
438 'iw_url' => 'http://example.com/',
439 'iw_local' => 0,
440 'iw_trans' => 0,
441 ];
442 return false;
443 }
444 },
445 ],
446 ] );
447
448 foreach ( $expectedArray as $validate => $expected ) {
449 $this->assertEquals(
450 $expected,
451 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
452 }
453 }
454
455 public static function provideGetCanonicalName() {
456 return [
457 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
458 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
459 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
460 'valid' => false, 'false' => 'Talk:Username' ] ],
461 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
462 'valid' => false, 'false' => 'Interwiki:Username' ] ],
463 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
464 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
465 'usable' => 'Multi spaces' ] ],
466 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
467 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
468 'valid' => false, 'false' => 'In[]valid' ] ],
469 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
470 'false' => 'With / slash' ] ],
471 ];
472 }
473
474 /**
475 * @covers User::equals
476 */
477 public function testEquals() {
478 $first = $this->getMutableTestUser()->getUser();
479 $second = User::newFromName( $first->getName() );
480
481 $this->assertTrue( $first->equals( $first ) );
482 $this->assertTrue( $first->equals( $second ) );
483 $this->assertTrue( $second->equals( $first ) );
484
485 $third = $this->getMutableTestUser()->getUser();
486 $fourth = $this->getMutableTestUser()->getUser();
487
488 $this->assertFalse( $third->equals( $fourth ) );
489 $this->assertFalse( $fourth->equals( $third ) );
490
491 // Test users loaded from db with id
492 $user = $this->getMutableTestUser()->getUser();
493 $fifth = User::newFromId( $user->getId() );
494 $sixth = User::newFromName( $user->getName() );
495 $this->assertTrue( $fifth->equals( $sixth ) );
496 }
497
498 /**
499 * @covers User::getId
500 */
501 public function testGetId() {
502 $user = static::getTestUser()->getUser();
503 $this->assertTrue( $user->getId() > 0 );
504 }
505
506 /**
507 * @covers User::isLoggedIn
508 * @covers User::isAnon
509 */
510 public function testLoggedIn() {
511 $user = $this->getMutableTestUser()->getUser();
512 $this->assertTrue( $user->isLoggedIn() );
513 $this->assertFalse( $user->isAnon() );
514
515 // Non-existent users are perceived as anonymous
516 $user = User::newFromName( 'UTNonexistent' );
517 $this->assertFalse( $user->isLoggedIn() );
518 $this->assertTrue( $user->isAnon() );
519
520 $user = new User;
521 $this->assertFalse( $user->isLoggedIn() );
522 $this->assertTrue( $user->isAnon() );
523 }
524
525 /**
526 * @covers User::checkAndSetTouched
527 */
528 public function testCheckAndSetTouched() {
529 $user = $this->getMutableTestUser()->getUser();
530 $user = TestingAccessWrapper::newFromObject( $user );
531 $this->assertTrue( $user->isLoggedIn() );
532
533 $touched = $user->getDBTouched();
534 $this->assertTrue(
535 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
536 $this->assertGreaterThan(
537 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
538
539 $touched = $user->getDBTouched();
540 $this->assertTrue(
541 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
542 $this->assertGreaterThan(
543 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
544 }
545
546 /**
547 * @covers User::findUsersByGroup
548 */
549 public function testFindUsersByGroup() {
550 // FIXME: fails under postgres
551 $this->markTestSkippedIfDbType( 'postgres' );
552
553 $users = User::findUsersByGroup( [] );
554 $this->assertEquals( 0, iterator_count( $users ) );
555
556 $users = User::findUsersByGroup( 'foo' );
557 $this->assertEquals( 0, iterator_count( $users ) );
558
559 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
560 $users = User::findUsersByGroup( 'foo' );
561 $this->assertEquals( 1, iterator_count( $users ) );
562 $users->rewind();
563 $this->assertTrue( $user->equals( $users->current() ) );
564
565 // arguments have OR relationship
566 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
567 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
568 $this->assertEquals( 2, iterator_count( $users ) );
569 $users->rewind();
570 $this->assertTrue( $user->equals( $users->current() ) );
571 $users->next();
572 $this->assertTrue( $user2->equals( $users->current() ) );
573
574 // users are not duplicated
575 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
576 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
577 $this->assertEquals( 1, iterator_count( $users ) );
578 $users->rewind();
579 $this->assertTrue( $user->equals( $users->current() ) );
580 }
581
582 /**
583 * When a user is autoblocked a cookie is set with which to track them
584 * in case they log out and change IP addresses.
585 * @link https://phabricator.wikimedia.org/T5233
586 * @covers User::trackBlockWithCookie
587 */
588 public function testAutoblockCookies() {
589 // Set up the bits of global configuration that we use.
590 $this->setMwGlobals( [
591 'wgCookieSetOnAutoblock' => true,
592 'wgCookiePrefix' => 'wmsitetitle',
593 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
594 ] );
595
596 // Unregister the hooks for proper unit testing
597 $this->mergeMwGlobalArrayValue( 'wgHooks', [
598 'PerformRetroactiveAutoblock' => []
599 ] );
600
601 // 1. Log in a test user, and block them.
602 $user1tmp = $this->getTestUser()->getUser();
603 $request1 = new FauxRequest();
604 $request1->getSession()->setUser( $user1tmp );
605 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
606 $block = new Block( [
607 'enableAutoblock' => true,
608 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
609 ] );
610 $block->setBlocker( $this->getTestSysop()->getUser() );
611 $block->setTarget( $user1tmp );
612 $res = $block->insert();
613 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
614 $user1 = User::newFromSession( $request1 );
615 $user1->mBlock = $block;
616 $user1->load();
617
618 // Confirm that the block has been applied as required.
619 $this->assertTrue( $user1->isLoggedIn() );
620 $this->assertTrue( $user1->isBlocked() );
621 $this->assertEquals( Block::TYPE_USER, $block->getType() );
622 $this->assertTrue( $block->isAutoblocking() );
623 $this->assertGreaterThanOrEqual( 1, $block->getId() );
624
625 // Test for the desired cookie name, value, and expiry.
626 $cookies = $request1->response()->getCookies();
627 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
628 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
629 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
630 $this->assertEquals( $block->getId(), $cookieValue );
631
632 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
633 $request2 = new FauxRequest();
634 $request2->setCookie( 'BlockID', $block->getCookieValue() );
635 $user2 = User::newFromSession( $request2 );
636 $user2->load();
637 $this->assertNotEquals( $user1->getId(), $user2->getId() );
638 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
639 $this->assertTrue( $user2->isAnon() );
640 $this->assertFalse( $user2->isLoggedIn() );
641 $this->assertTrue( $user2->isBlocked() );
642 // Non-strict type-check.
643 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
644 // Can't directly compare the objects because of member type differences.
645 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
646 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
647 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
648
649 // 3. Finally, set up a request as a new user, and the block should still be applied.
650 $user3tmp = $this->getTestUser()->getUser();
651 $request3 = new FauxRequest();
652 $request3->getSession()->setUser( $user3tmp );
653 $request3->setCookie( 'BlockID', $block->getId() );
654 $user3 = User::newFromSession( $request3 );
655 $user3->load();
656 $this->assertTrue( $user3->isLoggedIn() );
657 $this->assertTrue( $user3->isBlocked() );
658 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
659
660 // Clean up.
661 $block->delete();
662 }
663
664 /**
665 * Make sure that no cookie is set to track autoblocked users
666 * when $wgCookieSetOnAutoblock is false.
667 * @covers User::trackBlockWithCookie
668 */
669 public function testAutoblockCookiesDisabled() {
670 // Set up the bits of global configuration that we use.
671 $this->setMwGlobals( [
672 'wgCookieSetOnAutoblock' => false,
673 'wgCookiePrefix' => 'wm_no_cookies',
674 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
675 ] );
676
677 // Unregister the hooks for proper unit testing
678 $this->mergeMwGlobalArrayValue( 'wgHooks', [
679 'PerformRetroactiveAutoblock' => []
680 ] );
681
682 // 1. Log in a test user, and block them.
683 $testUser = $this->getTestUser()->getUser();
684 $request1 = new FauxRequest();
685 $request1->getSession()->setUser( $testUser );
686 $block = new Block( [ 'enableAutoblock' => true ] );
687 $block->setBlocker( $this->getTestSysop()->getUser() );
688 $block->setTarget( $testUser );
689 $res = $block->insert();
690 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
691 $user = User::newFromSession( $request1 );
692 $user->mBlock = $block;
693 $user->load();
694
695 // 2. Test that the cookie IS NOT present.
696 $this->assertTrue( $user->isLoggedIn() );
697 $this->assertTrue( $user->isBlocked() );
698 $this->assertEquals( Block::TYPE_USER, $block->getType() );
699 $this->assertTrue( $block->isAutoblocking() );
700 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
701 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
702 $cookies = $request1->response()->getCookies();
703 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
704
705 // Clean up.
706 $block->delete();
707 }
708
709 /**
710 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
711 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
712 * the cookie's should change with it.
713 * @covers User::trackBlockWithCookie
714 */
715 public function testAutoblockCookieInfiniteExpiry() {
716 $this->setMwGlobals( [
717 'wgCookieSetOnAutoblock' => true,
718 'wgCookiePrefix' => 'wm_infinite_block',
719 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
720 ] );
721
722 // Unregister the hooks for proper unit testing
723 $this->mergeMwGlobalArrayValue( 'wgHooks', [
724 'PerformRetroactiveAutoblock' => []
725 ] );
726
727 // 1. Log in a test user, and block them indefinitely.
728 $user1Tmp = $this->getTestUser()->getUser();
729 $request1 = new FauxRequest();
730 $request1->getSession()->setUser( $user1Tmp );
731 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
732 $block->setBlocker( $this->getTestSysop()->getUser() );
733 $block->setTarget( $user1Tmp );
734 $res = $block->insert();
735 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
736 $user1 = User::newFromSession( $request1 );
737 $user1->mBlock = $block;
738 $user1->load();
739
740 // 2. Test the cookie's expiry timestamp.
741 $this->assertTrue( $user1->isLoggedIn() );
742 $this->assertTrue( $user1->isBlocked() );
743 $this->assertEquals( Block::TYPE_USER, $block->getType() );
744 $this->assertTrue( $block->isAutoblocking() );
745 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
746 $cookies = $request1->response()->getCookies();
747 // Test the cookie's expiry to the nearest minute.
748 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
749 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
750 // Check for expiry dates in a 10-second window, to account for slow testing.
751 $this->assertEquals(
752 $expOneDay,
753 $cookies['wm_infinite_blockBlockID']['expire'],
754 'Expiry date',
755 5.0
756 );
757
758 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
759 $newExpiry = wfTimestamp() + 2 * 60 * 60;
760 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
761 $block->update();
762 $user2tmp = $this->getTestUser()->getUser();
763 $request2 = new FauxRequest();
764 $request2->getSession()->setUser( $user2tmp );
765 $user2 = User::newFromSession( $request2 );
766 $user2->mBlock = $block;
767 $user2->load();
768 $cookies = $request2->response()->getCookies();
769 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
770 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
771
772 // Clean up.
773 $block->delete();
774 }
775
776 /**
777 * @covers User::getBlockedStatus
778 */
779 public function testSoftBlockRanges() {
780 global $wgUser;
781
782 $this->setMwGlobals( [
783 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
784 'wgUser' => null,
785 ] );
786
787 // IP isn't in $wgSoftBlockRanges
788 $request = new FauxRequest();
789 $request->setIP( '192.168.0.1' );
790 $wgUser = User::newFromSession( $request );
791 $this->assertNull( $wgUser->getBlock() );
792
793 // IP is in $wgSoftBlockRanges
794 $request = new FauxRequest();
795 $request->setIP( '10.20.30.40' );
796 $wgUser = User::newFromSession( $request );
797 $block = $wgUser->getBlock();
798 $this->assertInstanceOf( Block::class, $block );
799 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
800
801 // Make sure the block is really soft
802 $request->getSession()->setUser( $this->getTestUser()->getUser() );
803 $wgUser = User::newFromSession( $request );
804 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
805 $this->assertNull( $wgUser->getBlock() );
806 }
807
808 /**
809 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
810 * @covers User::trackBlockWithCookie
811 */
812 public function testAutoblockCookieInauthentic() {
813 // Set up the bits of global configuration that we use.
814 $this->setMwGlobals( [
815 'wgCookieSetOnAutoblock' => true,
816 'wgCookiePrefix' => 'wmsitetitle',
817 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
818 ] );
819
820 // Unregister the hooks for proper unit testing
821 $this->mergeMwGlobalArrayValue( 'wgHooks', [
822 'PerformRetroactiveAutoblock' => []
823 ] );
824
825 // 1. Log in a blocked test user.
826 $user1tmp = $this->getTestUser()->getUser();
827 $request1 = new FauxRequest();
828 $request1->getSession()->setUser( $user1tmp );
829 $block = new Block( [ 'enableAutoblock' => true ] );
830 $block->setBlocker( $this->getTestSysop()->getUser() );
831 $block->setTarget( $user1tmp );
832 $res = $block->insert();
833 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
834 $user1 = User::newFromSession( $request1 );
835 $user1->mBlock = $block;
836 $user1->load();
837
838 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
839 // user not blocked.
840 $request2 = new FauxRequest();
841 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
842 $user2 = User::newFromSession( $request2 );
843 $user2->load();
844 $this->assertTrue( $user2->isAnon() );
845 $this->assertFalse( $user2->isLoggedIn() );
846 $this->assertFalse( $user2->isBlocked() );
847
848 // Clean up.
849 $block->delete();
850 }
851
852 /**
853 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
854 * This checks that a non-authenticated cookie still works.
855 * @covers User::trackBlockWithCookie
856 */
857 public function testAutoblockCookieNoSecretKey() {
858 // Set up the bits of global configuration that we use.
859 $this->setMwGlobals( [
860 'wgCookieSetOnAutoblock' => true,
861 'wgCookiePrefix' => 'wmsitetitle',
862 'wgSecretKey' => null,
863 ] );
864
865 // Unregister the hooks for proper unit testing
866 $this->mergeMwGlobalArrayValue( 'wgHooks', [
867 'PerformRetroactiveAutoblock' => []
868 ] );
869
870 // 1. Log in a blocked test user.
871 $user1tmp = $this->getTestUser()->getUser();
872 $request1 = new FauxRequest();
873 $request1->getSession()->setUser( $user1tmp );
874 $block = new Block( [ 'enableAutoblock' => true ] );
875 $block->setBlocker( $this->getTestSysop()->getUser() );
876 $block->setTarget( $user1tmp );
877 $res = $block->insert();
878 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
879 $user1 = User::newFromSession( $request1 );
880 $user1->mBlock = $block;
881 $user1->load();
882 $this->assertTrue( $user1->isBlocked() );
883
884 // 2. Create a new request, set the cookie to just the block ID, and the user should
885 // still get blocked when they log in again.
886 $request2 = new FauxRequest();
887 $request2->setCookie( 'BlockID', $block->getId() );
888 $user2 = User::newFromSession( $request2 );
889 $user2->load();
890 $this->assertNotEquals( $user1->getId(), $user2->getId() );
891 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
892 $this->assertTrue( $user2->isAnon() );
893 $this->assertFalse( $user2->isLoggedIn() );
894 $this->assertTrue( $user2->isBlocked() );
895 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
896
897 // Clean up.
898 $block->delete();
899 }
900
901 /**
902 * @covers User::isPingLimitable
903 */
904 public function testIsPingLimitable() {
905 $request = new FauxRequest();
906 $request->setIP( '1.2.3.4' );
907 $user = User::newFromSession( $request );
908
909 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
910 $this->assertTrue( $user->isPingLimitable() );
911
912 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
913 $this->assertFalse( $user->isPingLimitable() );
914
915 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
916 $this->assertFalse( $user->isPingLimitable() );
917
918 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
919 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
920 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
921 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
922 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
923 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
924 }
925
926 public function provideExperienceLevel() {
927 return [
928 [ 2, 2, 'newcomer' ],
929 [ 12, 3, 'newcomer' ],
930 [ 8, 5, 'newcomer' ],
931 [ 15, 10, 'learner' ],
932 [ 450, 20, 'learner' ],
933 [ 460, 33, 'learner' ],
934 [ 525, 28, 'learner' ],
935 [ 538, 33, 'experienced' ],
936 ];
937 }
938
939 /**
940 * @covers User::getExperienceLevel
941 * @dataProvider provideExperienceLevel
942 */
943 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
944 $this->setMwGlobals( [
945 'wgLearnerEdits' => 10,
946 'wgLearnerMemberSince' => 4,
947 'wgExperiencedUserEdits' => 500,
948 'wgExperiencedUserMemberSince' => 30,
949 ] );
950
951 $db = wfGetDB( DB_MASTER );
952 $userQuery = User::getQueryInfo();
953 $row = $db->selectRow(
954 $userQuery['tables'],
955 $userQuery['fields'],
956 [ 'user_id' => $this->getTestUser()->getUser()->getId() ],
957 __METHOD__,
958 [],
959 $userQuery['joins']
960 );
961 $row->user_editcount = $editCount;
962 $row->user_registration = $db->timestamp( time() - $memberSince * 86400 );
963 $user = User::newFromRow( $row );
964
965 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
966 }
967
968 /**
969 * @covers User::getExperienceLevel
970 */
971 public function testExperienceLevelAnon() {
972 $user = User::newFromName( '10.11.12.13', false );
973
974 $this->assertFalse( $user->getExperienceLevel() );
975 }
976
977 public static function provideIsLocallBlockedProxy() {
978 return [
979 [ '1.2.3.4', '1.2.3.4' ],
980 [ '1.2.3.4', '1.2.3.0/16' ],
981 ];
982 }
983
984 /**
985 * @dataProvider provideIsLocallBlockedProxy
986 * @covers User::isLocallyBlockedProxy
987 */
988 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
989 $this->setMwGlobals(
990 'wgProxyList', []
991 );
992 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
993
994 $this->setMwGlobals(
995 'wgProxyList',
996 [
997 $blockListEntry
998 ]
999 );
1000 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1001
1002 $this->setMwGlobals(
1003 'wgProxyList',
1004 [
1005 'test' => $blockListEntry
1006 ]
1007 );
1008 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1009
1010 $this->hideDeprecated(
1011 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1012 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1013 );
1014 $this->setMwGlobals(
1015 'wgProxyList',
1016 [
1017 $blockListEntry => 'test'
1018 ]
1019 );
1020 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1021 }
1022
1023 /**
1024 * @covers User::newFromActorId
1025 */
1026 public function testActorId() {
1027 $domain = MediaWikiServices::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1028 $this->hideDeprecated( 'User::selectFields' );
1029
1030 // Newly-created user has an actor ID
1031 $user = User::createNew( 'UserTestActorId1' );
1032 $id = $user->getId();
1033 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1034
1035 $user = User::newFromName( 'UserTestActorId2' );
1036 $user->addToDatabase();
1037 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1038
1039 $user = User::newFromName( 'UserTestActorId1' );
1040 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1041
1042 $user = User::newFromId( $id );
1043 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1044
1045 $user2 = User::newFromActorId( $user->getActorId() );
1046 $this->assertEquals( $user->getId(), $user2->getId(),
1047 'User::newFromActorId works for an existing user' );
1048
1049 $row = $this->db->selectRow( 'user', User::selectFields(), [ 'user_id' => $id ], __METHOD__ );
1050 $user = User::newFromRow( $row );
1051 $this->assertTrue( $user->getActorId() > 0,
1052 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1053
1054 $this->db->delete( 'actor', [ 'actor_user' => $id ], __METHOD__ );
1055 User::purge( $domain, $id );
1056 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1057 ObjectCache::getMainWANInstance()->clearProcessCache();
1058
1059 $user = User::newFromId( $id );
1060 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1061 $this->assertTrue( $user->getActorId( $this->db ) > 0, 'Actor ID can be created if none in db' );
1062
1063 $user->setName( 'UserTestActorId4-renamed' );
1064 $user->saveSettings();
1065 $this->assertEquals(
1066 $user->getName(),
1067 $this->db->selectField(
1068 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1069 ),
1070 'User::saveSettings updates actor table for name change'
1071 );
1072
1073 // For sanity
1074 $ip = '192.168.12.34';
1075 $this->db->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__ );
1076
1077 $user = User::newFromName( $ip, false );
1078 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1079 $this->assertTrue( $user->getActorId( $this->db ) > 0,
1080 'Actor ID can be created for an anonymous user' );
1081
1082 $user = User::newFromName( $ip, false );
1083 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1084 $user2 = User::newFromActorId( $user->getActorId() );
1085 $this->assertEquals( $user->getName(), $user2->getName(),
1086 'User::newFromActorId works for an anonymous user' );
1087 }
1088
1089 /**
1090 * @covers User::newFromAnyId
1091 */
1092 public function testNewFromAnyId() {
1093 // Registered user
1094 $user = $this->getTestUser()->getUser();
1095 for ( $i = 1; $i <= 7; $i++ ) {
1096 $test = User::newFromAnyId(
1097 ( $i & 1 ) ? $user->getId() : null,
1098 ( $i & 2 ) ? $user->getName() : null,
1099 ( $i & 4 ) ? $user->getActorId() : null
1100 );
1101 $this->assertSame( $user->getId(), $test->getId() );
1102 $this->assertSame( $user->getName(), $test->getName() );
1103 $this->assertSame( $user->getActorId(), $test->getActorId() );
1104 }
1105
1106 // Anon user. Can't load by only user ID when that's 0.
1107 $user = User::newFromName( '192.168.12.34', false );
1108 $user->getActorId( $this->db ); // Make sure an actor ID exists
1109
1110 $test = User::newFromAnyId( null, '192.168.12.34', null );
1111 $this->assertSame( $user->getId(), $test->getId() );
1112 $this->assertSame( $user->getName(), $test->getName() );
1113 $this->assertSame( $user->getActorId(), $test->getActorId() );
1114 $test = User::newFromAnyId( null, null, $user->getActorId() );
1115 $this->assertSame( $user->getId(), $test->getId() );
1116 $this->assertSame( $user->getName(), $test->getName() );
1117 $this->assertSame( $user->getActorId(), $test->getActorId() );
1118
1119 // Bogus data should still "work" as long as nothing triggers a ->load(),
1120 // and accessing the specified data shouldn't do that.
1121 $test = User::newFromAnyId( 123456, 'Bogus', 654321 );
1122 $this->assertSame( 123456, $test->getId() );
1123 $this->assertSame( 'Bogus', $test->getName() );
1124 $this->assertSame( 654321, $test->getActorId() );
1125
1126 // Exceptional cases
1127 try {
1128 User::newFromAnyId( null, null, null );
1129 $this->fail( 'Expected exception not thrown' );
1130 } catch ( InvalidArgumentException $ex ) {
1131 }
1132 try {
1133 User::newFromAnyId( 0, null, 0 );
1134 $this->fail( 'Expected exception not thrown' );
1135 } catch ( InvalidArgumentException $ex ) {
1136 }
1137 }
1138
1139 /**
1140 * @covers User::newFromIdentity
1141 */
1142 public function testNewFromIdentity() {
1143 // Registered user
1144 $user = $this->getTestUser()->getUser();
1145
1146 $this->assertSame( $user, User::newFromIdentity( $user ) );
1147
1148 // ID only
1149 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1150 $result = User::newFromIdentity( $identity );
1151 $this->assertInstanceOf( User::class, $result );
1152 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1153 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1154 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1155
1156 // Name only
1157 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1158 $result = User::newFromIdentity( $identity );
1159 $this->assertInstanceOf( User::class, $result );
1160 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1161 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1162 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1163
1164 // Actor only
1165 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1166 $result = User::newFromIdentity( $identity );
1167 $this->assertInstanceOf( User::class, $result );
1168 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1169 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1170 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1171 }
1172
1173 /**
1174 * @covers User::getBlockedStatus
1175 * @covers User::getBlock
1176 * @covers User::blockedBy
1177 * @covers User::blockedFor
1178 * @covers User::isHidden
1179 * @covers User::isBlockedFrom
1180 */
1181 public function testBlockInstanceCache() {
1182 // First, check the user isn't blocked
1183 $user = $this->getMutableTestUser()->getUser();
1184 $ut = Title::makeTitle( NS_USER_TALK, $user->getName() );
1185 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1186 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1187 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1188 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1189 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1190
1191 // Block the user
1192 $blocker = $this->getTestSysop()->getUser();
1193 $block = new Block( [
1194 'hideName' => true,
1195 'allowUsertalk' => false,
1196 'reason' => 'Because',
1197 ] );
1198 $block->setTarget( $user );
1199 $block->setBlocker( $blocker );
1200 $res = $block->insert();
1201 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1202
1203 // Clear cache and confirm it loaded the block properly
1204 $user->clearInstanceCache();
1205 $this->assertInstanceOf( Block::class, $user->getBlock( false ) );
1206 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1207 $this->assertSame( 'Because', $user->blockedFor() );
1208 $this->assertTrue( (bool)$user->isHidden() );
1209 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1210
1211 // Unblock
1212 $block->delete();
1213
1214 // Clear cache and confirm it loaded the not-blocked properly
1215 $user->clearInstanceCache();
1216 $this->assertNull( $user->getBlock( false ) );
1217 $this->assertSame( '', $user->blockedBy() );
1218 $this->assertSame( '', $user->blockedFor() );
1219 $this->assertFalse( (bool)$user->isHidden() );
1220 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1221 }
1222
1223 /**
1224 * @covers User::isBlockedFrom
1225 * @dataProvider provideIsBlockedFrom
1226 * @param string|null $title Title to test.
1227 * @param bool $expect Expected result from User::isBlockedFrom()
1228 * @param array $options Additional test options:
1229 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1230 * - 'allowUsertalk': (bool, default false) Passed to Block::__construct()
1231 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1232 */
1233 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1234 $this->setMwGlobals( [
1235 'wgBlockAllowsUTEdit' => $options['blockAllowsUTEdit'] ?? true,
1236 ] );
1237
1238 $user = $this->getTestUser()->getUser();
1239
1240 if ( $title === self::USER_TALK_PAGE ) {
1241 $title = $user->getTalkPage();
1242 } else {
1243 $title = Title::newFromText( $title );
1244 }
1245
1246 $restrictions = [];
1247 foreach ( $options['pageRestrictions'] ?? [] as $pagestr ) {
1248 $page = $this->getExistingTestPage(
1249 $pagestr === self::USER_TALK_PAGE ? $user->getTalkPage() : $pagestr
1250 );
1251 $restrictions[] = new PageRestriction( 0, $page->getId() );
1252 }
1253 foreach ( $options['namespaceRestrictions'] ?? [] as $ns ) {
1254 $restrictions[] = new NamespaceRestriction( 0, $ns );
1255 }
1256
1257 $block = new Block( [
1258 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
1259 'allowUsertalk' => $options['allowUsertalk'] ?? false,
1260 'sitewide' => !$restrictions,
1261 ] );
1262 $block->setTarget( $user );
1263 $block->setBlocker( $this->getTestSysop()->getUser() );
1264 if ( $restrictions ) {
1265 $block->setRestrictions( $restrictions );
1266 }
1267 $block->insert();
1268
1269 try {
1270 $this->assertSame( $expect, $user->isBlockedFrom( $title ) );
1271 } finally {
1272 $block->delete();
1273 }
1274 }
1275
1276 public static function provideIsBlockedFrom() {
1277 return [
1278 'Sitewide block, basic operation' => [ 'Test page', true ],
1279 'Sitewide block, not allowing user talk' => [
1280 self::USER_TALK_PAGE, true, [
1281 'allowUsertalk' => false,
1282 ]
1283 ],
1284 'Sitewide block, allowing user talk' => [
1285 self::USER_TALK_PAGE, false, [
1286 'allowUsertalk' => true,
1287 ]
1288 ],
1289 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1290 self::USER_TALK_PAGE, true, [
1291 'allowUsertalk' => true,
1292 'blockAllowsUTEdit' => false,
1293 ]
1294 ],
1295 'Partial block, blocking the page' => [
1296 'Test page', true, [
1297 'pageRestrictions' => [ 'Test page' ],
1298 ]
1299 ],
1300 'Partial block, not blocking the page' => [
1301 'Test page 2', false, [
1302 'pageRestrictions' => [ 'Test page' ],
1303 ]
1304 ],
1305 'Partial block, not allowing user talk but user talk page is not blocked' => [
1306 self::USER_TALK_PAGE, false, [
1307 'allowUsertalk' => false,
1308 'pageRestrictions' => [ 'Test page' ],
1309 ]
1310 ],
1311 'Partial block, allowing user talk but user talk page is blocked' => [
1312 self::USER_TALK_PAGE, true, [
1313 'allowUsertalk' => true,
1314 'pageRestrictions' => [ self::USER_TALK_PAGE ],
1315 ]
1316 ],
1317 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1318 self::USER_TALK_PAGE, false, [
1319 'allowUsertalk' => false,
1320 'pageRestrictions' => [ 'Test page' ],
1321 'blockAllowsUTEdit' => false,
1322 ]
1323 ],
1324 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1325 self::USER_TALK_PAGE, true, [
1326 'allowUsertalk' => true,
1327 'pageRestrictions' => [ self::USER_TALK_PAGE ],
1328 'blockAllowsUTEdit' => false,
1329 ]
1330 ],
1331 'Partial user talk namespace block, not allowing user talk' => [
1332 self::USER_TALK_PAGE, true, [
1333 'allowUsertalk' => false,
1334 'namespaceRestrictions' => [ NS_USER_TALK ],
1335 ]
1336 ],
1337 'Partial user talk namespace block, allowing user talk' => [
1338 self::USER_TALK_PAGE, false, [
1339 'allowUsertalk' => true,
1340 'namespaceRestrictions' => [ NS_USER_TALK ],
1341 ]
1342 ],
1343 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1344 self::USER_TALK_PAGE, true, [
1345 'allowUsertalk' => true,
1346 'namespaceRestrictions' => [ NS_USER_TALK ],
1347 'blockAllowsUTEdit' => false,
1348 ]
1349 ],
1350 ];
1351 }
1352
1353 /**
1354 * Block cookie should be set for IP Blocks if
1355 * wgCookieSetOnIpBlock is set to true
1356 * @covers User::trackBlockWithCookie
1357 */
1358 public function testIpBlockCookieSet() {
1359 $this->setMwGlobals( [
1360 'wgCookieSetOnIpBlock' => true,
1361 'wgCookiePrefix' => 'wiki',
1362 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1363 ] );
1364
1365 // setup block
1366 $block = new Block( [
1367 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1368 ] );
1369 $block->setTarget( '1.2.3.4' );
1370 $block->setBlocker( $this->getTestSysop()->getUser() );
1371 $block->insert();
1372
1373 // setup request
1374 $request = new FauxRequest();
1375 $request->setIP( '1.2.3.4' );
1376
1377 // get user
1378 $user = User::newFromSession( $request );
1379 $user->trackBlockWithCookie();
1380
1381 // test cookie was set
1382 $cookies = $request->response()->getCookies();
1383 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1384
1385 // clean up
1386 $block->delete();
1387 }
1388
1389 /**
1390 * Block cookie should NOT be set when wgCookieSetOnIpBlock
1391 * is disabled
1392 * @covers User::trackBlockWithCookie
1393 */
1394 public function testIpBlockCookieNotSet() {
1395 $this->setMwGlobals( [
1396 'wgCookieSetOnIpBlock' => false,
1397 'wgCookiePrefix' => 'wiki',
1398 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1399 ] );
1400
1401 // setup block
1402 $block = new Block( [
1403 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1404 ] );
1405 $block->setTarget( '1.2.3.4' );
1406 $block->setBlocker( $this->getTestSysop()->getUser() );
1407 $block->insert();
1408
1409 // setup request
1410 $request = new FauxRequest();
1411 $request->setIP( '1.2.3.4' );
1412
1413 // get user
1414 $user = User::newFromSession( $request );
1415 $user->trackBlockWithCookie();
1416
1417 // test cookie was not set
1418 $cookies = $request->response()->getCookies();
1419 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1420
1421 // clean up
1422 $block->delete();
1423 }
1424
1425 /**
1426 * When an ip user is blocked and then they log in, cookie block
1427 * should be invalid and the cookie removed.
1428 * @covers User::trackBlockWithCookie
1429 */
1430 public function testIpBlockCookieIgnoredWhenUserLoggedIn() {
1431 $this->setMwGlobals( [
1432 'wgAutoblockExpiry' => 8000,
1433 'wgCookieSetOnIpBlock' => true,
1434 'wgCookiePrefix' => 'wiki',
1435 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1436 ] );
1437
1438 // setup block
1439 $block = new Block( [
1440 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
1441 ] );
1442 $block->setTarget( '1.2.3.4' );
1443 $block->setBlocker( $this->getTestSysop()->getUser() );
1444 $block->insert();
1445
1446 // setup request
1447 $request = new FauxRequest();
1448 $request->setIP( '1.2.3.4' );
1449 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1450 $request->setCookie( 'BlockID', $block->getCookieValue() );
1451
1452 // setup user
1453 $user = User::newFromSession( $request );
1454
1455 // logged in users should be inmune to cookie block of type ip/range
1456 $this->assertFalse( $user->isBlocked() );
1457
1458 // cookie is being cleared
1459 $cookies = $request->response()->getCookies();
1460 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1461
1462 // clean up
1463 $block->delete();
1464 }
1465
1466 /**
1467 * @covers User::getFirstEditTimestamp
1468 * @covers User::getLatestEditTimestamp
1469 */
1470 public function testGetFirstLatestEditTimestamp() {
1471 $clock = MWTimestamp::convert( TS_UNIX, '20100101000000' );
1472 MWTimestamp::setFakeTime( function () use ( &$clock ) {
1473 return $clock += 1000;
1474 } );
1475 try {
1476 $user = $this->getTestUser()->getUser();
1477 $firstRevision = self::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'one', 'test' );
1478 $secondRevision = self::makeEdit( $user, 'Help:UserTest_GetEditTimestamp', 'two', 'test' );
1479 // Sanity check: revisions timestamp are different
1480 $this->assertNotEquals( $firstRevision->getTimestamp(), $secondRevision->getTimestamp() );
1481
1482 $this->assertEquals( $firstRevision->getTimestamp(), $user->getFirstEditTimestamp() );
1483 $this->assertEquals( $secondRevision->getTimestamp(), $user->getLatestEditTimestamp() );
1484 } finally {
1485 MWTimestamp::setFakeTime( false );
1486 }
1487 }
1488
1489 /**
1490 * @param User $user
1491 * @param string $title
1492 * @param string $content
1493 * @param string $comment
1494 * @return \MediaWiki\Revision\RevisionRecord|null
1495 */
1496 private static function makeEdit( User $user, $title, $content, $comment ) {
1497 $page = WikiPage::factory( Title::newFromText( $title ) );
1498 $content = ContentHandler::makeContent( $content, $page->getTitle() );
1499 $updater = $page->newPageUpdater( $user );
1500 $updater->setContent( 'main', $content );
1501 return $updater->saveRevision( CommentStoreComment::newUnsavedComment( $comment ) );
1502 }
1503 }