MediaWiki REL1_32
UserTest.php
Go to the documentation of this file.
1<?php
2
3define( 'NS_UNITTEST', 5600 );
4define( 'NS_UNITTEST_TALK', 5601 );
5
8use Wikimedia\TestingAccessWrapper;
9
17 protected $user;
18
19 protected function setUp() {
20 parent::setUp();
21
22 $this->setMwGlobals( [
23 'wgGroupPermissions' => [],
24 'wgRevokePermissions' => [],
25 'wgActorTableSchemaMigrationStage' => SCHEMA_COMPAT_WRITE_BOTH | SCHEMA_COMPAT_READ_OLD,
26 ] );
27 $this->overrideMwServices();
28
30
31 $this->user = $this->getTestUser( [ 'unittesters' ] )->getUser();
32 }
33
34 private function setUpPermissionGlobals() {
36
37 # Data for regular $wgGroupPermissions test
38 $wgGroupPermissions['unittesters'] = [
39 'test' => true,
40 'runtest' => true,
41 'writetest' => false,
42 'nukeworld' => false,
43 ];
44 $wgGroupPermissions['testwriters'] = [
45 'test' => true,
46 'writetest' => true,
47 'modifytest' => true,
48 ];
49
50 # Data for regular $wgRevokePermissions test
51 $wgRevokePermissions['formertesters'] = [
52 'runtest' => true,
53 ];
54
55 # For the options test
56 $wgGroupPermissions['*'] = [
57 'editmyoptions' => true,
58 ];
59 }
60
64 public function testGroupPermissions() {
65 $rights = User::getGroupPermissions( [ 'unittesters' ] );
66 $this->assertContains( 'runtest', $rights );
67 $this->assertNotContains( 'writetest', $rights );
68 $this->assertNotContains( 'modifytest', $rights );
69 $this->assertNotContains( 'nukeworld', $rights );
70
71 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
72 $this->assertContains( 'runtest', $rights );
73 $this->assertContains( 'writetest', $rights );
74 $this->assertContains( 'modifytest', $rights );
75 $this->assertNotContains( 'nukeworld', $rights );
76 }
77
81 public function testRevokePermissions() {
82 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
83 $this->assertNotContains( 'runtest', $rights );
84 $this->assertNotContains( 'writetest', $rights );
85 $this->assertNotContains( 'modifytest', $rights );
86 $this->assertNotContains( 'nukeworld', $rights );
87 }
88
92 public function testUserPermissions() {
93 $rights = $this->user->getRights();
94 $this->assertContains( 'runtest', $rights );
95 $this->assertNotContains( 'writetest', $rights );
96 $this->assertNotContains( 'modifytest', $rights );
97 $this->assertNotContains( 'nukeworld', $rights );
98 }
99
103 public function testUserGetRightsHooks() {
104 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
105 $userWrapper = TestingAccessWrapper::newFromObject( $user );
106
107 $rights = $user->getRights();
108 $this->assertContains( 'test', $rights, 'sanity check' );
109 $this->assertContains( 'runtest', $rights, 'sanity check' );
110 $this->assertContains( 'writetest', $rights, 'sanity check' );
111 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
112
113 // Add a hook manipluating the rights
114 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
115 $rights[] = 'nukeworld';
116 $rights = array_diff( $rights, [ 'writetest' ] );
117 } ] ] );
118
119 $userWrapper->mRights = null;
120 $rights = $user->getRights();
121 $this->assertContains( 'test', $rights );
122 $this->assertContains( 'runtest', $rights );
123 $this->assertNotContains( 'writetest', $rights );
124 $this->assertContains( 'nukeworld', $rights );
125
126 // Add a Session that limits rights
127 $mock = $this->getMockBuilder( stdClass::class )
128 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
129 ->getMock();
130 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
131 $mock->method( 'getSessionId' )->willReturn(
132 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
133 );
134 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
135 $mockRequest = $this->getMockBuilder( FauxRequest::class )
136 ->setMethods( [ 'getSession' ] )
137 ->getMock();
138 $mockRequest->method( 'getSession' )->willReturn( $session );
139 $userWrapper->mRequest = $mockRequest;
140
141 $userWrapper->mRights = null;
142 $rights = $user->getRights();
143 $this->assertContains( 'test', $rights );
144 $this->assertNotContains( 'runtest', $rights );
145 $this->assertNotContains( 'writetest', $rights );
146 $this->assertNotContains( 'nukeworld', $rights );
147 }
148
153 public function testGetGroupsWithPermission( $expected, $right ) {
155 sort( $result );
156 sort( $expected );
157
158 $this->assertEquals( $expected, $result, "Groups with permission $right" );
159 }
160
161 public static function provideGetGroupsWithPermission() {
162 return [
163 [
164 [ 'unittesters', 'testwriters' ],
165 'test'
166 ],
167 [
168 [ 'unittesters' ],
169 'runtest'
170 ],
171 [
172 [ 'testwriters' ],
173 'writetest'
174 ],
175 [
176 [ 'testwriters' ],
177 'modifytest'
178 ],
179 ];
180 }
181
186 public function testIsIP( $value, $result, $message ) {
187 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
188 }
189
190 public static function provideIPs() {
191 return [
192 [ '', false, 'Empty string' ],
193 [ ' ', false, 'Blank space' ],
194 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
195 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
196 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
197 [ '203.0.113.0', true, 'IPv4 example' ],
198 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
199 // Not valid IPs but classified as such by MediaWiki for negated asserting
200 // of whether this might be the identifier of a logged-out user or whether
201 // to allow usernames like it.
202 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
203 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
204 ];
205 }
206
211 public function testIsValidUserName( $username, $result, $message ) {
212 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
213 }
214
215 public static function provideUserNames() {
216 return [
217 [ '', false, 'Empty string' ],
218 [ ' ', false, 'Blank space' ],
219 [ 'abcd', false, 'Starts with small letter' ],
220 [ 'Ab/cd', false, 'Contains slash' ],
221 [ 'Ab cd', true, 'Whitespace' ],
222 [ '192.168.1.1', false, 'IP' ],
223 [ '116.17.184.5/32', false, 'IP range' ],
224 [ '::e:f:2001/96', false, 'IPv6 range' ],
225 [ 'User:Abcd', false, 'Reserved Namespace' ],
226 [ '12abcd232', true, 'Starts with Numbers' ],
227 [ '?abcd', true, 'Start with ? mark' ],
228 [ '#abcd', false, 'Start with #' ],
229 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
230 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
231 [ 'Ab cd', false, ' Ideographic space' ],
232 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
233 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
234 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
235 ];
236 }
237
243 public function testGetEditCount() {
244 $user = $this->getMutableTestUser()->getUser();
245
246 // let the user have a few (3) edits
247 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
248 for ( $i = 0; $i < 3; $i++ ) {
249 $page->doEditContent(
250 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
251 'test',
252 0,
253 false,
254 $user
255 );
256 }
257
258 $this->assertEquals(
259 3,
261 'After three edits, the user edit count should be 3'
262 );
263
264 // increase the edit count
266
267 $this->assertEquals(
268 4,
270 'After increasing the edit count manually, the user edit count should be 4'
271 );
272 }
273
279 public function testGetEditCountForAnons() {
280 $user = User::newFromName( 'Anonymous' );
281
282 $this->assertNull(
284 'Edit count starts null for anonymous users.'
285 );
286
288
289 $this->assertNull(
291 'Edit count remains null for anonymous users despite calls to increase it.'
292 );
293 }
294
300 public function testIncEditCount() {
301 $user = $this->getMutableTestUser()->getUser();
303
304 $reloadedUser = User::newFromId( $user->getId() );
305 $reloadedUser->incEditCount();
306
307 $this->assertEquals(
308 2,
309 $reloadedUser->getEditCount(),
310 'Increasing the edit count after a fresh load leaves the object up to date.'
311 );
312 }
313
319 public function testOptions() {
320 $user = $this->getMutableTestUser()->getUser();
321
322 $user->setOption( 'userjs-someoption', 'test' );
323 $user->setOption( 'rclimit', 200 );
324 $user->setOption( 'wpwatchlistdays', '0' );
326
328 $user->load( User::READ_LATEST );
329 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
330 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
331
333 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
334 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
335 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
336
337 // Check that an option saved as a string '0' is returned as an integer.
339 $user->load( User::READ_LATEST );
340 $this->assertSame( 0, $user->getOption( 'wpwatchlistdays' ) );
341 }
342
348 public function testAnonOptions() {
350 $this->user->setOption( 'userjs-someoption', 'test' );
351 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
352 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
353 }
354
364 public function testCheckPasswordValidity() {
365 $this->setMwGlobals( [
366 'wgPasswordPolicy' => [
367 'policies' => [
368 'sysop' => [
369 'MinimalPasswordLength' => 8,
370 'MinimumPasswordLengthToLogin' => 1,
371 'PasswordCannotMatchUsername' => 1,
372 ],
373 'default' => [
374 'MinimalPasswordLength' => 6,
375 'PasswordCannotMatchUsername' => true,
376 'PasswordCannotMatchBlacklist' => true,
377 'MaximalPasswordLength' => 40,
378 ],
379 ],
380 'checks' => [
381 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
382 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
383 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
384 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
385 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
386 ],
387 ],
388 ] );
389
390 $user = static::getTestUser()->getUser();
391
392 // Sanity
393 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
394
395 // Minimum length
396 $this->assertFalse( $user->isValidPassword( 'a' ) );
397 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
398 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
399 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
400
401 // Maximum length
402 $longPass = str_repeat( 'a', 41 );
403 $this->assertFalse( $user->isValidPassword( $longPass ) );
404 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
405 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
406 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
407
408 // Matches username
409 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
410 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
411 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
412
413 // On the forbidden list
414 $user = User::newFromName( 'Useruser' );
415 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
416 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
417 }
418
423 public function testGetCanonicalName( $name, $expectedArray ) {
424 // fake interwiki map for the 'Interwiki prefix' testcase
425 $this->mergeMwGlobalArrayValue( 'wgHooks', [
426 'InterwikiLoadPrefix' => [
427 function ( $prefix, &$iwdata ) {
428 if ( $prefix === 'interwiki' ) {
429 $iwdata = [
430 'iw_url' => 'http://example.com/',
431 'iw_local' => 0,
432 'iw_trans' => 0,
433 ];
434 return false;
435 }
436 },
437 ],
438 ] );
439
440 foreach ( $expectedArray as $validate => $expected ) {
441 $this->assertEquals(
442 $expected,
443 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
444 }
445 }
446
447 public static function provideGetCanonicalName() {
448 return [
449 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
450 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
451 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
452 'valid' => false, 'false' => 'Talk:Username' ] ],
453 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
454 'valid' => false, 'false' => 'Interwiki:Username' ] ],
455 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
456 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
457 'usable' => 'Multi spaces' ] ],
458 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
459 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
460 'valid' => false, 'false' => 'In[]valid' ] ],
461 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
462 'false' => 'With / slash' ] ],
463 ];
464 }
465
469 public function testEquals() {
470 $first = $this->getMutableTestUser()->getUser();
471 $second = User::newFromName( $first->getName() );
472
473 $this->assertTrue( $first->equals( $first ) );
474 $this->assertTrue( $first->equals( $second ) );
475 $this->assertTrue( $second->equals( $first ) );
476
477 $third = $this->getMutableTestUser()->getUser();
478 $fourth = $this->getMutableTestUser()->getUser();
479
480 $this->assertFalse( $third->equals( $fourth ) );
481 $this->assertFalse( $fourth->equals( $third ) );
482
483 // Test users loaded from db with id
484 $user = $this->getMutableTestUser()->getUser();
485 $fifth = User::newFromId( $user->getId() );
486 $sixth = User::newFromName( $user->getName() );
487 $this->assertTrue( $fifth->equals( $sixth ) );
488 }
489
493 public function testGetId() {
494 $user = static::getTestUser()->getUser();
495 $this->assertTrue( $user->getId() > 0 );
496 }
497
502 public function testLoggedIn() {
503 $user = $this->getMutableTestUser()->getUser();
504 $this->assertTrue( $user->isLoggedIn() );
505 $this->assertFalse( $user->isAnon() );
506
507 // Non-existent users are perceived as anonymous
508 $user = User::newFromName( 'UTNonexistent' );
509 $this->assertFalse( $user->isLoggedIn() );
510 $this->assertTrue( $user->isAnon() );
511
512 $user = new User;
513 $this->assertFalse( $user->isLoggedIn() );
514 $this->assertTrue( $user->isAnon() );
515 }
516
520 public function testCheckAndSetTouched() {
521 $user = $this->getMutableTestUser()->getUser();
522 $user = TestingAccessWrapper::newFromObject( $user );
523 $this->assertTrue( $user->isLoggedIn() );
524
525 $touched = $user->getDBTouched();
526 $this->assertTrue(
527 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed" );
528 $this->assertGreaterThan(
529 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
530
531 $touched = $user->getDBTouched();
532 $this->assertTrue(
533 $user->checkAndSetTouched(), "checkAndSetTouched() succedeed #2" );
534 $this->assertGreaterThan(
535 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
536 }
537
541 public function testFindUsersByGroup() {
542 // FIXME: fails under postgres
543 $this->markTestSkippedIfDbType( 'postgres' );
544
546 $this->assertEquals( 0, iterator_count( $users ) );
547
549 $this->assertEquals( 0, iterator_count( $users ) );
550
551 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
553 $this->assertEquals( 1, iterator_count( $users ) );
554 $users->rewind();
555 $this->assertTrue( $user->equals( $users->current() ) );
556
557 // arguments have OR relationship
558 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
559 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
560 $this->assertEquals( 2, iterator_count( $users ) );
561 $users->rewind();
562 $this->assertTrue( $user->equals( $users->current() ) );
563 $users->next();
564 $this->assertTrue( $user2->equals( $users->current() ) );
565
566 // users are not duplicated
567 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
568 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
569 $this->assertEquals( 1, iterator_count( $users ) );
570 $users->rewind();
571 $this->assertTrue( $user->equals( $users->current() ) );
572 }
573
579 public function testAutoblockCookies() {
580 // Set up the bits of global configuration that we use.
581 $this->setMwGlobals( [
582 'wgCookieSetOnAutoblock' => true,
583 'wgCookiePrefix' => 'wmsitetitle',
584 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
585 ] );
586
587 // Unregister the hooks for proper unit testing
588 $this->mergeMwGlobalArrayValue( 'wgHooks', [
589 'PerformRetroactiveAutoblock' => []
590 ] );
591
592 // 1. Log in a test user, and block them.
593 $userBlocker = $this->getTestSysop()->getUser();
594 $user1tmp = $this->getTestUser()->getUser();
595 $request1 = new FauxRequest();
596 $request1->getSession()->setUser( $user1tmp );
597 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
598 $block = new Block( [
599 'enableAutoblock' => true,
600 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
601 ] );
602 $block->setBlocker( $this->getTestSysop()->getUser() );
603 $block->setTarget( $user1tmp );
604 $block->setBlocker( $userBlocker );
605 $res = $block->insert();
606 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
607 $user1 = User::newFromSession( $request1 );
608 $user1->mBlock = $block;
609 $user1->load();
610
611 // Confirm that the block has been applied as required.
612 $this->assertTrue( $user1->isLoggedIn() );
613 $this->assertTrue( $user1->isBlocked() );
614 $this->assertEquals( Block::TYPE_USER, $block->getType() );
615 $this->assertTrue( $block->isAutoblocking() );
616 $this->assertGreaterThanOrEqual( 1, $block->getId() );
617
618 // Test for the desired cookie name, value, and expiry.
619 $cookies = $request1->response()->getCookies();
620 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
621 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
622 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
623 $this->assertEquals( $block->getId(), $cookieValue );
624
625 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
626 $request2 = new FauxRequest();
627 $request2->setCookie( 'BlockID', $block->getCookieValue() );
628 $user2 = User::newFromSession( $request2 );
629 $user2->load();
630 $this->assertNotEquals( $user1->getId(), $user2->getId() );
631 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
632 $this->assertTrue( $user2->isAnon() );
633 $this->assertFalse( $user2->isLoggedIn() );
634 $this->assertTrue( $user2->isBlocked() );
635 // Non-strict type-check.
636 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
637 // Can't directly compare the objects because of member type differences.
638 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
639 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
640 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
641
642 // 3. Finally, set up a request as a new user, and the block should still be applied.
643 $user3tmp = $this->getTestUser()->getUser();
644 $request3 = new FauxRequest();
645 $request3->getSession()->setUser( $user3tmp );
646 $request3->setCookie( 'BlockID', $block->getId() );
647 $user3 = User::newFromSession( $request3 );
648 $user3->load();
649 $this->assertTrue( $user3->isLoggedIn() );
650 $this->assertTrue( $user3->isBlocked() );
651 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
652
653 // Clean up.
654 $block->delete();
655 }
656
662 // Set up the bits of global configuration that we use.
663 $this->setMwGlobals( [
664 'wgCookieSetOnAutoblock' => false,
665 'wgCookiePrefix' => 'wm_no_cookies',
666 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
667 ] );
668
669 // Unregister the hooks for proper unit testing
670 $this->mergeMwGlobalArrayValue( 'wgHooks', [
671 'PerformRetroactiveAutoblock' => []
672 ] );
673
674 // 1. Log in a test user, and block them.
675 $userBlocker = $this->getTestSysop()->getUser();
676 $testUser = $this->getTestUser()->getUser();
677 $request1 = new FauxRequest();
678 $request1->getSession()->setUser( $testUser );
679 $block = new Block( [ 'enableAutoblock' => true ] );
680 $block->setBlocker( $this->getTestSysop()->getUser() );
681 $block->setTarget( $testUser );
682 $block->setBlocker( $userBlocker );
683 $res = $block->insert();
684 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
685 $user = User::newFromSession( $request1 );
686 $user->mBlock = $block;
687 $user->load();
688
689 // 2. Test that the cookie IS NOT present.
690 $this->assertTrue( $user->isLoggedIn() );
691 $this->assertTrue( $user->isBlocked() );
692 $this->assertEquals( Block::TYPE_USER, $block->getType() );
693 $this->assertTrue( $block->isAutoblocking() );
694 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
695 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
696 $cookies = $request1->response()->getCookies();
697 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
698
699 // Clean up.
700 $block->delete();
701 }
702
709 $this->setMwGlobals( [
710 'wgCookieSetOnAutoblock' => true,
711 'wgCookiePrefix' => 'wm_infinite_block',
712 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
713 ] );
714
715 // Unregister the hooks for proper unit testing
716 $this->mergeMwGlobalArrayValue( 'wgHooks', [
717 'PerformRetroactiveAutoblock' => []
718 ] );
719
720 // 1. Log in a test user, and block them indefinitely.
721 $userBlocker = $this->getTestSysop()->getUser();
722 $user1Tmp = $this->getTestUser()->getUser();
723 $request1 = new FauxRequest();
724 $request1->getSession()->setUser( $user1Tmp );
725 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
726 $block->setBlocker( $this->getTestSysop()->getUser() );
727 $block->setTarget( $user1Tmp );
728 $block->setBlocker( $userBlocker );
729 $res = $block->insert();
730 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
731 $user1 = User::newFromSession( $request1 );
732 $user1->mBlock = $block;
733 $user1->load();
734
735 // 2. Test the cookie's expiry timestamp.
736 $this->assertTrue( $user1->isLoggedIn() );
737 $this->assertTrue( $user1->isBlocked() );
738 $this->assertEquals( Block::TYPE_USER, $block->getType() );
739 $this->assertTrue( $block->isAutoblocking() );
740 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
741 $cookies = $request1->response()->getCookies();
742 // Test the cookie's expiry to the nearest minute.
743 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
744 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
745 // Check for expiry dates in a 10-second window, to account for slow testing.
746 $this->assertEquals(
747 $expOneDay,
748 $cookies['wm_infinite_blockBlockID']['expire'],
749 'Expiry date',
750 5.0
751 );
752
753 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
754 $newExpiry = wfTimestamp() + 2 * 60 * 60;
755 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
756 $block->update();
757 $user2tmp = $this->getTestUser()->getUser();
758 $request2 = new FauxRequest();
759 $request2->getSession()->setUser( $user2tmp );
760 $user2 = User::newFromSession( $request2 );
761 $user2->mBlock = $block;
762 $user2->load();
763 $cookies = $request2->response()->getCookies();
764 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
765 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
766
767 // Clean up.
768 $block->delete();
769 }
770
771 public function testSoftBlockRanges() {
772 $setSessionUser = function ( User $user, WebRequest $request ) {
773 $this->setMwGlobals( 'wgUser', $user );
774 RequestContext::getMain()->setUser( $user );
775 RequestContext::getMain()->setRequest( $request );
776 TestingAccessWrapper::newFromObject( $user )->mRequest = $request;
777 $request->getSession()->setUser( $user );
778 };
779 $this->setMwGlobals( 'wgSoftBlockRanges', [ '10.0.0.0/8' ] );
780
781 // IP isn't in $wgSoftBlockRanges
782 $wgUser = new User();
783 $request = new FauxRequest();
784 $request->setIP( '192.168.0.1' );
785 $setSessionUser( $wgUser, $request );
786 $this->assertNull( $wgUser->getBlock() );
787
788 // IP is in $wgSoftBlockRanges
789 $wgUser = new User();
790 $request = new FauxRequest();
791 $request->setIP( '10.20.30.40' );
792 $setSessionUser( $wgUser, $request );
793 $block = $wgUser->getBlock();
794 $this->assertInstanceOf( Block::class, $block );
795 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
796
797 // Make sure the block is really soft
798 $wgUser = $this->getTestUser()->getUser();
799 $request = new FauxRequest();
800 $request->setIP( '10.20.30.40' );
801 $setSessionUser( $wgUser, $request );
802 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
803 $this->assertNull( $wgUser->getBlock() );
804 }
805
810 // Set up the bits of global configuration that we use.
811 $this->setMwGlobals( [
812 'wgCookieSetOnAutoblock' => true,
813 'wgCookiePrefix' => 'wmsitetitle',
814 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
815 ] );
816
817 // Unregister the hooks for proper unit testing
818 $this->mergeMwGlobalArrayValue( 'wgHooks', [
819 'PerformRetroactiveAutoblock' => []
820 ] );
821
822 // 1. Log in a blocked test user.
823 $userBlocker = $this->getTestSysop()->getUser();
824 $user1tmp = $this->getTestUser()->getUser();
825 $request1 = new FauxRequest();
826 $request1->getSession()->setUser( $user1tmp );
827 $block = new Block( [ 'enableAutoblock' => true ] );
828 $block->setBlocker( $this->getTestSysop()->getUser() );
829 $block->setTarget( $user1tmp );
830 $block->setBlocker( $userBlocker );
831 $res = $block->insert();
832 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
833 $user1 = User::newFromSession( $request1 );
834 $user1->mBlock = $block;
835 $user1->load();
836
837 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
838 // user not blocked.
839 $request2 = new FauxRequest();
840 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
841 $user2 = User::newFromSession( $request2 );
842 $user2->load();
843 $this->assertTrue( $user2->isAnon() );
844 $this->assertFalse( $user2->isLoggedIn() );
845 $this->assertFalse( $user2->isBlocked() );
846
847 // Clean up.
848 $block->delete();
849 }
850
856 // Set up the bits of global configuration that we use.
857 $this->setMwGlobals( [
858 'wgCookieSetOnAutoblock' => true,
859 'wgCookiePrefix' => 'wmsitetitle',
860 'wgSecretKey' => null,
861 ] );
862
863 // Unregister the hooks for proper unit testing
864 $this->mergeMwGlobalArrayValue( 'wgHooks', [
865 'PerformRetroactiveAutoblock' => []
866 ] );
867
868 // 1. Log in a blocked test user.
869 $userBlocker = $this->getTestSysop()->getUser();
870 $user1tmp = $this->getTestUser()->getUser();
871 $request1 = new FauxRequest();
872 $request1->getSession()->setUser( $user1tmp );
873 $block = new Block( [ 'enableAutoblock' => true ] );
874 $block->setBlocker( $this->getTestSysop()->getUser() );
875 $block->setTarget( $user1tmp );
876 $block->setBlocker( $userBlocker );
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
904 public function testIsPingLimitable() {
905 $request = new FauxRequest();
906 $request->setIP( '1.2.3.4' );
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
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
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
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 public function testActorId() {
1024 $domain = MediaWikiServices::getInstance()->getDBLoadBalancer()->getLocalDomainID();
1025 $this->hideDeprecated( 'User::selectFields' );
1026
1027 // Newly-created user has an actor ID
1028 $user = User::createNew( 'UserTestActorId1' );
1029 $id = $user->getId();
1030 $this->assertTrue( $user->getActorId() > 0, 'User::createNew sets an actor ID' );
1031
1032 $user = User::newFromName( 'UserTestActorId2' );
1034 $this->assertTrue( $user->getActorId() > 0, 'User::addToDatabase sets an actor ID' );
1035
1036 $user = User::newFromName( 'UserTestActorId1' );
1037 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by name' );
1038
1039 $user = User::newFromId( $id );
1040 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be retrieved for user loaded by ID' );
1041
1042 $user2 = User::newFromActorId( $user->getActorId() );
1043 $this->assertEquals( $user->getId(), $user2->getId(),
1044 'User::newFromActorId works for an existing user' );
1045
1046 $row = $this->db->selectRow( 'user', User::selectFields(), [ 'user_id' => $id ], __METHOD__ );
1047 $user = User::newFromRow( $row );
1048 $this->assertTrue( $user->getActorId() > 0,
1049 'Actor ID can be retrieved for user loaded with User::selectFields()' );
1050
1051 $this->db->delete( 'actor', [ 'actor_user' => $id ], __METHOD__ );
1052 User::purge( $domain, $id );
1053 // Because WANObjectCache->delete() stupidly doesn't delete from the process cache.
1054 ObjectCache::getMainWANInstance()->clearProcessCache();
1055
1056 $user = User::newFromId( $id );
1057 $this->assertFalse( $user->getActorId() > 0, 'No Actor ID by default if none in database' );
1058 $this->assertTrue( $user->getActorId( $this->db ) > 0, 'Actor ID can be created if none in db' );
1059
1060 $user->setName( 'UserTestActorId4-renamed' );
1062 $this->assertEquals(
1063 $user->getName(),
1064 $this->db->selectField(
1065 'actor', 'actor_name', [ 'actor_id' => $user->getActorId() ], __METHOD__
1066 ),
1067 'User::saveSettings updates actor table for name change'
1068 );
1069
1070 // For sanity
1071 $ip = '192.168.12.34';
1072 $this->db->delete( 'actor', [ 'actor_name' => $ip ], __METHOD__ );
1073
1074 $user = User::newFromName( $ip, false );
1075 $this->assertFalse( $user->getActorId() > 0, 'Anonymous user has no actor ID by default' );
1076 $this->assertTrue( $user->getActorId( $this->db ) > 0,
1077 'Actor ID can be created for an anonymous user' );
1078
1079 $user = User::newFromName( $ip, false );
1080 $this->assertTrue( $user->getActorId() > 0, 'Actor ID can be loaded for an anonymous user' );
1081 $user2 = User::newFromActorId( $user->getActorId() );
1082 $this->assertEquals( $user->getName(), $user2->getName(),
1083 'User::newFromActorId works for an anonymous user' );
1084 }
1085
1086 public function testNewFromAnyId() {
1087 // Registered user
1088 $user = $this->getTestUser()->getUser();
1089 for ( $i = 1; $i <= 7; $i++ ) {
1090 $test = User::newFromAnyId(
1091 ( $i & 1 ) ? $user->getId() : null,
1092 ( $i & 2 ) ? $user->getName() : null,
1093 ( $i & 4 ) ? $user->getActorId() : null
1094 );
1095 $this->assertSame( $user->getId(), $test->getId() );
1096 $this->assertSame( $user->getName(), $test->getName() );
1097 $this->assertSame( $user->getActorId(), $test->getActorId() );
1098 }
1099
1100 // Anon user. Can't load by only user ID when that's 0.
1101 $user = User::newFromName( '192.168.12.34', false );
1102 $user->getActorId( $this->db ); // Make sure an actor ID exists
1103
1104 $test = User::newFromAnyId( null, '192.168.12.34', null );
1105 $this->assertSame( $user->getId(), $test->getId() );
1106 $this->assertSame( $user->getName(), $test->getName() );
1107 $this->assertSame( $user->getActorId(), $test->getActorId() );
1108 $test = User::newFromAnyId( null, null, $user->getActorId() );
1109 $this->assertSame( $user->getId(), $test->getId() );
1110 $this->assertSame( $user->getName(), $test->getName() );
1111 $this->assertSame( $user->getActorId(), $test->getActorId() );
1112
1113 // Bogus data should still "work" as long as nothing triggers a ->load(),
1114 // and accessing the specified data shouldn't do that.
1115 $test = User::newFromAnyId( 123456, 'Bogus', 654321 );
1116 $this->assertSame( 123456, $test->getId() );
1117 $this->assertSame( 'Bogus', $test->getName() );
1118 $this->assertSame( 654321, $test->getActorId() );
1119
1120 // Exceptional cases
1121 try {
1122 User::newFromAnyId( null, null, null );
1123 $this->fail( 'Expected exception not thrown' );
1124 } catch ( InvalidArgumentException $ex ) {
1125 }
1126 try {
1127 User::newFromAnyId( 0, null, 0 );
1128 $this->fail( 'Expected exception not thrown' );
1129 } catch ( InvalidArgumentException $ex ) {
1130 }
1131 }
1132
1136 public function testNewFromIdentity() {
1137 // Registered user
1138 $user = $this->getTestUser()->getUser();
1139
1140 $this->assertSame( $user, User::newFromIdentity( $user ) );
1141
1142 // ID only
1143 $identity = new UserIdentityValue( $user->getId(), '', 0 );
1144 $result = User::newFromIdentity( $identity );
1145 $this->assertInstanceOf( User::class, $result );
1146 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1147 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1148 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1149
1150 // Name only
1151 $identity = new UserIdentityValue( 0, $user->getName(), 0 );
1152 $result = User::newFromIdentity( $identity );
1153 $this->assertInstanceOf( User::class, $result );
1154 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1155 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1156 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1157
1158 // Actor only
1159 $identity = new UserIdentityValue( 0, '', $user->getActorId() );
1160 $result = User::newFromIdentity( $identity );
1161 $this->assertInstanceOf( User::class, $result );
1162 $this->assertSame( $user->getId(), $result->getId(), 'ID' );
1163 $this->assertSame( $user->getName(), $result->getName(), 'Name' );
1164 $this->assertSame( $user->getActorId(), $result->getActorId(), 'Actor' );
1165 }
1166
1175 public function testBlockInstanceCache() {
1176 // First, check the user isn't blocked
1177 $user = $this->getMutableTestUser()->getUser();
1178 $ut = Title::makeTitle( NS_USER_TALK, $user->getName() );
1179 $this->assertNull( $user->getBlock( false ), 'sanity check' );
1180 $this->assertSame( '', $user->blockedBy(), 'sanity check' );
1181 $this->assertSame( '', $user->blockedFor(), 'sanity check' );
1182 $this->assertFalse( (bool)$user->isHidden(), 'sanity check' );
1183 $this->assertFalse( $user->isBlockedFrom( $ut ), 'sanity check' );
1184
1185 // Block the user
1186 $blocker = $this->getTestSysop()->getUser();
1187 $block = new Block( [
1188 'hideName' => true,
1189 'allowUsertalk' => false,
1190 'reason' => 'Because',
1191 ] );
1192 $block->setTarget( $user );
1193 $block->setBlocker( $blocker );
1194 $res = $block->insert();
1195 $this->assertTrue( (bool)$res['id'], 'sanity check: Failed to insert block' );
1196
1197 // Clear cache and confirm it loaded the block properly
1199 $this->assertInstanceOf( Block::class, $user->getBlock( false ) );
1200 $this->assertSame( $blocker->getName(), $user->blockedBy() );
1201 $this->assertSame( 'Because', $user->blockedFor() );
1202 $this->assertTrue( (bool)$user->isHidden() );
1203 $this->assertTrue( $user->isBlockedFrom( $ut ) );
1204
1205 // Unblock
1206 $block->delete();
1207
1208 // Clear cache and confirm it loaded the not-blocked properly
1210 $this->assertNull( $user->getBlock( false ) );
1211 $this->assertSame( '', $user->blockedBy() );
1212 $this->assertSame( '', $user->blockedFor() );
1213 $this->assertFalse( (bool)$user->isHidden() );
1214 $this->assertFalse( $user->isBlockedFrom( $ut ) );
1215 }
1216
1221 public function testIpBlockCookieSet() {
1222 $this->setMwGlobals( [
1223 'wgCookieSetOnIpBlock' => true,
1224 'wgCookiePrefix' => 'wiki',
1225 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1226 ] );
1227
1228 // setup block
1229 $block = new Block( [
1230 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1231 ] );
1232 $block->setTarget( '1.2.3.4' );
1233 $block->setBlocker( $this->getTestSysop()->getUser() );
1234 $block->insert();
1235
1236 // setup request
1237 $request = new FauxRequest();
1238 $request->setIP( '1.2.3.4' );
1239
1240 // get user
1243
1244 // test cookie was set
1245 $cookies = $request->response()->getCookies();
1246 $this->assertArrayHasKey( 'wikiBlockID', $cookies );
1247
1248 // clean up
1249 $block->delete();
1250 }
1251
1256 public function testIpBlockCookieNotSet() {
1257 $this->setMwGlobals( [
1258 'wgCookieSetOnIpBlock' => false,
1259 'wgCookiePrefix' => 'wiki',
1260 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1261 ] );
1262
1263 // setup block
1264 $block = new Block( [
1265 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 5 * 60 * 60 ) ),
1266 ] );
1267 $block->setTarget( '1.2.3.4' );
1268 $block->setBlocker( $this->getTestSysop()->getUser() );
1269 $block->insert();
1270
1271 // setup request
1272 $request = new FauxRequest();
1273 $request->setIP( '1.2.3.4' );
1274
1275 // get user
1278
1279 // test cookie was not set
1280 $cookies = $request->response()->getCookies();
1281 $this->assertArrayNotHasKey( 'wikiBlockID', $cookies );
1282
1283 // clean up
1284 $block->delete();
1285 }
1286
1292 $this->setMwGlobals( [
1293 'wgAutoblockExpiry' => 8000,
1294 'wgCookieSetOnIpBlock' => true,
1295 'wgCookiePrefix' => 'wiki',
1296 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
1297 ] );
1298
1299 // setup block
1300 $block = new Block( [
1301 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
1302 ] );
1303 $block->setTarget( '1.2.3.4' );
1304 $block->setBlocker( $this->getTestSysop()->getUser() );
1305 $block->insert();
1306
1307 // setup request
1308 $request = new FauxRequest();
1309 $request->setIP( '1.2.3.4' );
1310 $request->getSession()->setUser( $this->getTestUser()->getUser() );
1311 $request->setCookie( 'BlockID', $block->getCookieValue() );
1312
1313 // setup user
1315
1316 // logged in users should be inmune to cookie block of type ip/range
1317 $this->assertFalse( $user->isBlocked() );
1318
1319 // cookie is being cleared
1320 $cookies = $request->response()->getCookies();
1321 $this->assertEquals( '', $cookies['wikiBlockID']['value'] );
1322
1323 // clean up
1324 $block->delete();
1325 }
1326}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgDefaultUserOptions
Settings added to this array will override the default globals for the user preferences used by anony...
$wgGroupPermissions
Permission keys given to users in each group.
$wgRevokePermissions
Permission keys revoked from users in each group.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
Definition Block.php:1589
const TYPE_USER
Definition Block.php:83
WebRequest clone which takes values from a provided array.
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format.
static TestUser[] $users
Database $db
Primary database.
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
markTestSkippedIfDbType( $type)
Skip the test if using the specified database type.
static getTestSysop()
Convenience method for getting an immutable admin test user.
overrideMwServices(Config $configOverrides=null, array $services=[])
Stashes the global instance of MediaWikiServices, and installs a new one, allowing test cases to over...
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
hideDeprecated( $function)
Don't throw a warning if $function is deprecated and called later.
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Value object representing a user's identity.
Database.
Definition UserTest.php:13
testUserPermissions()
User::getRights.
Definition UserTest.php:92
testGetGroupsWithPermission( $expected, $right)
provideGetGroupsWithPermission User::getGroupsWithPermission
Definition UserTest.php:153
testIpBlockCookieSet()
Block cookie should be set for IP Blocks if wgCookieSetOnIpBlock is set to true.
testExperienceLevelAnon()
User::getExperienceLevel.
Definition UserTest.php:971
testUserGetRightsHooks()
User::getRights.
Definition UserTest.php:103
testOptions()
Test changing user options.
Definition UserTest.php:319
testGetCanonicalName( $name, $expectedArray)
User::getCanonicalName() provideGetCanonicalName.
Definition UserTest.php:423
User $user
Definition UserTest.php:17
testNewFromAnyId()
testAutoblockCookies()
When a user is autoblocked a cookie is set with which to track them in case they log out and change I...
Definition UserTest.php:579
testAutoblockCookieInfiniteExpiry()
When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie should ma...
Definition UserTest.php:708
testAutoblockCookieInauthentic()
Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
Definition UserTest.php:809
testExperienceLevel( $editCount, $memberSince, $expLevel)
User::getExperienceLevel provideExperienceLevel.
Definition UserTest.php:943
testIsPingLimitable()
User::isPingLimitable.
Definition UserTest.php:904
static provideGetGroupsWithPermission()
Definition UserTest.php:161
testIsValidUserName( $username, $result, $message)
provideUserNames User::isValidUserName
Definition UserTest.php:211
testIsIP( $value, $result, $message)
provideIPs User::isIP
Definition UserTest.php:186
testGetEditCount()
Test User::editCount medium User::getEditCount.
Definition UserTest.php:243
testAutoblockCookieNoSecretKey()
The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
Definition UserTest.php:855
testSoftBlockRanges()
Definition UserTest.php:771
static provideGetCanonicalName()
Definition UserTest.php:447
testAnonOptions()
T39963 Make sure defaults are loaded when setOption is called.
Definition UserTest.php:348
setUpPermissionGlobals()
Definition UserTest.php:34
testIncEditCount()
Test User::editCount medium User::incEditCount.
Definition UserTest.php:300
testIpBlockCookieIgnoredWhenUserLoggedIn()
When an ip user is blocked and then they log in, cookie block should be invalid and the cookie remove...
testIpBlockCookieNotSet()
Block cookie should NOT be set when wgCookieSetOnIpBlock is disabled.
testGetEditCountForAnons()
Test User::editCount medium User::getEditCount.
Definition UserTest.php:279
testRevokePermissions()
User::getGroupPermissions.
Definition UserTest.php:81
static provideIsLocallBlockedProxy()
Definition UserTest.php:977
provideExperienceLevel()
Definition UserTest.php:926
testGetId()
User::getId.
Definition UserTest.php:493
testNewFromIdentity()
User::newFromIdentity.
testEquals()
User::equals.
Definition UserTest.php:469
testCheckPasswordValidity()
Test password validity checks.
Definition UserTest.php:364
testIsLocallyBlockedProxy( $ip, $blockListEntry)
provideIsLocallBlockedProxy User::isLocallyBlockedProxy
Definition UserTest.php:988
testBlockInstanceCache()
User::getBlockedStatus User::getBlock User::blockedBy User::blockedFor User::isHidden User::isBlocked...
testCheckAndSetTouched()
User::checkAndSetTouched.
Definition UserTest.php:520
testLoggedIn()
User::isLoggedIn User::isAnon.
Definition UserTest.php:502
testAutoblockCookiesDisabled()
Make sure that no cookie is set to track autoblocked users when $wgCookieSetOnAutoblock is false.
Definition UserTest.php:661
testGroupPermissions()
User::getGroupPermissions.
Definition UserTest.php:64
static provideIPs()
Definition UserTest.php:190
testFindUsersByGroup()
User::findUsersByGroup.
Definition UserTest.php:541
static provideUserNames()
Definition UserTest.php:215
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
getPasswordValidity( $password)
Given unvalidated password input, return error message on failure.
Definition User.php:1162
getName()
Get the user name, or the IP of an anonymous user.
Definition User.php:2462
addToDatabase()
Add this existing user object to the database.
Definition User.php:4377
isBlocked( $bFromSlave=true)
Check if user is blocked.
Definition User.php:2280
getExperienceLevel()
Compute experienced level based on edit count and registration date.
Definition User.php:4065
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition User.php:592
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new user object.
Definition User.php:5654
equals(UserIdentity $user)
Checks if two user objects point to the same user.
Definition User.php:5740
getDBTouched()
Get the user_touched timestamp field (time of last DB updates)
Definition User.php:2873
setName( $str)
Set the user name.
Definition User.php:2489
getId()
Get the user's ID.
Definition User.php:2437
static isLocallyBlockedProxy( $ip)
Check if an IP address is in the local proxy list.
Definition User.php:2067
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
Definition User.php:682
static purge( $wikiId, $userId)
Definition User.php:494
clearInstanceCache( $reloadFrom=false)
Clear various cached data stored in this object.
Definition User.php:1748
trackBlockWithCookie()
Set the 'BlockID' cookie depending on block type and user authentication status.
Definition User.php:1402
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition User.php:3171
isPingLimitable()
Is this user subject to rate limiting?
Definition User.php:2113
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
Definition User.php:1238
static newFromRow( $row, $data=null)
Create a new user object from a user row.
Definition User.php:778
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition User.php:615
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition User.php:4990
static getGroupPermissions( $groups)
Get the permissions associated with a given list of groups.
Definition User.php:4963
static findUsersByGroup( $groups, $limit=5000, $after=null)
Return the users who are members of the given group(s).
Definition User.php:1081
static selectFields()
Return the list of user fields that should be selected to create a new user object.
Definition User.php:5628
isHidden()
Check if user account is hidden.
Definition User.php:2418
checkPasswordValidity( $password)
Check if this is a valid password for this user.
Definition User.php:1198
static newFromSession(WebRequest $request=null)
Create a new user object using data from session.
Definition User.php:756
setOption( $oname, $val)
Set the given option for a user.
Definition User.php:3258
getEditCount()
Get the user's edit count.
Definition User.php:3692
getActorId(IDatabase $dbw=null)
Get the user's actor ID.
Definition User.php:2500
isValidPassword( $password)
Is the input a valid password for this user?
Definition User.php:1151
getBlock( $bFromSlave=true)
Get the block affecting the user, or null if the user is not blocked.
Definition User.php:2290
static newFromIdentity(UserIdentity $identity)
Returns a User object corresponding to the given UserIdentity.
Definition User.php:658
checkAndSetTouched()
Bump user_touched if it didn't change since this object was loaded.
Definition User.php:1710
isBlockedFrom( $title, $bFromSlave=false)
Check if user is blocked from editing a particular article.
Definition User.php:2302
getBlockId()
If user is blocked, return the ID for the block.
Definition User.php:2341
isLoggedIn()
Get whether the user is logged in.
Definition User.php:3793
saveSettings()
Save this user's settings into the database.
Definition User.php:4188
load( $flags=self::READ_NORMAL)
Load the user table data for this object from the source given by mFrom.
Definition User.php:364
blockedBy()
If user is blocked, return the name of the user who placed the block.
Definition User.php:2323
getRights()
Get the permissions this user has.
Definition User.php:3548
static createNew( $name, $params=[])
Add a user to the database, return the user object.
Definition User.php:4301
incEditCount()
Deferred version of incEditCountImmediate()
Definition User.php:5329
blockedFor()
If user is blocked, return the specified reason for the block.
Definition User.php:2332
isAnon()
Get whether the user is anonymous.
Definition User.php:3801
static newFromActorId( $id)
Static factory method for creation from a given actor ID.
Definition User.php:630
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Single row SELECT wrapper.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
$res
Definition database.txt:21
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same user
Wikitext formatted, in the key only.
const SCHEMA_COMPAT_WRITE_BOTH
Definition Defines.php:288
const SCHEMA_COMPAT_READ_OLD
Definition Defines.php:285
const NS_USER_TALK
Definition Defines.php:67
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2880
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:2042
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:815
processing should stop and the error should be shown to the user * false
Definition hooks.txt:187
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
A helper class for throttling authentication attempts.
const DB_MASTER
Definition defines.php:26