MediaWiki REL1_29
UserTest.php
Go to the documentation of this file.
1<?php
2
3define( 'NS_UNITTEST', 5600 );
4define( 'NS_UNITTEST_TALK', 5601 );
5
7use Wikimedia\TestingAccessWrapper;
8
16 protected $user;
17
18 protected function setUp() {
19 parent::setUp();
20
21 $this->setMwGlobals( [
22 'wgGroupPermissions' => [],
23 'wgRevokePermissions' => [],
24 ] );
25
27
28 $this->user = new User;
29 $this->user->addToDatabase();
30 $this->user->addGroup( 'unittesters' );
31 }
32
33 private function setUpPermissionGlobals() {
35
36 # Data for regular $wgGroupPermissions test
37 $wgGroupPermissions['unittesters'] = [
38 'test' => true,
39 'runtest' => true,
40 'writetest' => false,
41 'nukeworld' => false,
42 ];
43 $wgGroupPermissions['testwriters'] = [
44 'test' => true,
45 'writetest' => true,
46 'modifytest' => true,
47 ];
48
49 # Data for regular $wgRevokePermissions test
50 $wgRevokePermissions['formertesters'] = [
51 'runtest' => true,
52 ];
53
54 # For the options test
55 $wgGroupPermissions['*'] = [
56 'editmyoptions' => true,
57 ];
58 }
59
63 public function testGroupPermissions() {
64 $rights = User::getGroupPermissions( [ 'unittesters' ] );
65 $this->assertContains( 'runtest', $rights );
66 $this->assertNotContains( 'writetest', $rights );
67 $this->assertNotContains( 'modifytest', $rights );
68 $this->assertNotContains( 'nukeworld', $rights );
69
70 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
71 $this->assertContains( 'runtest', $rights );
72 $this->assertContains( 'writetest', $rights );
73 $this->assertContains( 'modifytest', $rights );
74 $this->assertNotContains( 'nukeworld', $rights );
75 }
76
80 public function testRevokePermissions() {
81 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
82 $this->assertNotContains( 'runtest', $rights );
83 $this->assertNotContains( 'writetest', $rights );
84 $this->assertNotContains( 'modifytest', $rights );
85 $this->assertNotContains( 'nukeworld', $rights );
86 }
87
91 public function testUserPermissions() {
92 $rights = $this->user->getRights();
93 $this->assertContains( 'runtest', $rights );
94 $this->assertNotContains( 'writetest', $rights );
95 $this->assertNotContains( 'modifytest', $rights );
96 $this->assertNotContains( 'nukeworld', $rights );
97 }
98
102 public function testUserGetRightsHooks() {
103 $user = new User;
105 $user->addGroup( 'unittesters' );
106 $user->addGroup( 'testwriters' );
107 $userWrapper = TestingAccessWrapper::newFromObject( $user );
108
109 $rights = $user->getRights();
110 $this->assertContains( 'test', $rights, 'sanity check' );
111 $this->assertContains( 'runtest', $rights, 'sanity check' );
112 $this->assertContains( 'writetest', $rights, 'sanity check' );
113 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
114
115 // Add a hook manipluating the rights
116 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
117 $rights[] = 'nukeworld';
118 $rights = array_diff( $rights, [ 'writetest' ] );
119 } ] ] );
120
121 $userWrapper->mRights = null;
122 $rights = $user->getRights();
123 $this->assertContains( 'test', $rights );
124 $this->assertContains( 'runtest', $rights );
125 $this->assertNotContains( 'writetest', $rights );
126 $this->assertContains( 'nukeworld', $rights );
127
128 // Add a Session that limits rights
129 $mock = $this->getMockBuilder( stdclass::class )
130 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
131 ->getMock();
132 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
133 $mock->method( 'getSessionId' )->willReturn(
134 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
135 );
136 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
137 $mockRequest = $this->getMockBuilder( FauxRequest::class )
138 ->setMethods( [ 'getSession' ] )
139 ->getMock();
140 $mockRequest->method( 'getSession' )->willReturn( $session );
141 $userWrapper->mRequest = $mockRequest;
142
143 $userWrapper->mRights = null;
144 $rights = $user->getRights();
145 $this->assertContains( 'test', $rights );
146 $this->assertNotContains( 'runtest', $rights );
147 $this->assertNotContains( 'writetest', $rights );
148 $this->assertNotContains( 'nukeworld', $rights );
149 }
150
155 public function testGetGroupsWithPermission( $expected, $right ) {
156 $result = User::getGroupsWithPermission( $right );
157 sort( $result );
158 sort( $expected );
159
160 $this->assertEquals( $expected, $result, "Groups with permission $right" );
161 }
162
163 public static function provideGetGroupsWithPermission() {
164 return [
165 [
166 [ 'unittesters', 'testwriters' ],
167 'test'
168 ],
169 [
170 [ 'unittesters' ],
171 'runtest'
172 ],
173 [
174 [ 'testwriters' ],
175 'writetest'
176 ],
177 [
178 [ 'testwriters' ],
179 'modifytest'
180 ],
181 ];
182 }
183
188 public function testIsIP( $value, $result, $message ) {
189 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
190 }
191
192 public static function provideIPs() {
193 return [
194 [ '', false, 'Empty string' ],
195 [ ' ', false, 'Blank space' ],
196 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
197 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
198 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
199 [ '203.0.113.0', true, 'IPv4 example' ],
200 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
201 // Not valid IPs but classified as such by MediaWiki for negated asserting
202 // of whether this might be the identifier of a logged-out user or whether
203 // to allow usernames like it.
204 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
205 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
206 ];
207 }
208
213 public function testIsValidUserName( $username, $result, $message ) {
214 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
215 }
216
217 public static function provideUserNames() {
218 return [
219 [ '', false, 'Empty string' ],
220 [ ' ', false, 'Blank space' ],
221 [ 'abcd', false, 'Starts with small letter' ],
222 [ 'Ab/cd', false, 'Contains slash' ],
223 [ 'Ab cd', true, 'Whitespace' ],
224 [ '192.168.1.1', false, 'IP' ],
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 testAllRightsWithMessage() {
244 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
245 $allRights = User::getAllRights();
246 $allMessageKeys = Language::getMessageKeysFor( 'en' );
247
248 $rightsWithMessage = [];
249 foreach ( $allMessageKeys as $message ) {
250 // === 0: must be at beginning of string (position 0)
251 if ( strpos( $message, 'right-' ) === 0 ) {
252 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
253 }
254 }
255
256 sort( $allRights );
257 sort( $rightsWithMessage );
258
259 $this->assertEquals(
260 $allRights,
261 $rightsWithMessage,
262 'Each user rights (core/extensions) has a corresponding right- message.'
263 );
264 }
265
271 public function testGetEditCount() {
272 $user = $this->getMutableTestUser()->getUser();
273
274 // let the user have a few (3) edits
275 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
276 for ( $i = 0; $i < 3; $i++ ) {
277 $page->doEditContent(
278 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
279 'test',
280 0,
281 false,
282 $user
283 );
284 }
285
286 $this->assertEquals(
287 3,
289 'After three edits, the user edit count should be 3'
290 );
291
292 // increase the edit count
294
295 $this->assertEquals(
296 4,
298 'After increasing the edit count manually, the user edit count should be 4'
299 );
300 }
301
307 public function testGetEditCountForAnons() {
308 $user = User::newFromName( 'Anonymous' );
309
310 $this->assertNull(
312 'Edit count starts null for anonymous users.'
313 );
314
316
317 $this->assertNull(
319 'Edit count remains null for anonymous users despite calls to increase it.'
320 );
321 }
322
328 public function testIncEditCount() {
329 $user = $this->getMutableTestUser()->getUser();
331
332 $reloadedUser = User::newFromId( $user->getId() );
333 $reloadedUser->incEditCount();
334
335 $this->assertEquals(
336 2,
337 $reloadedUser->getEditCount(),
338 'Increasing the edit count after a fresh load leaves the object up to date.'
339 );
340 }
341
347 public function testOptions() {
348 $user = $this->getMutableTestUser()->getUser();
349
350 $user->setOption( 'userjs-someoption', 'test' );
351 $user->setOption( 'rclimit', 200 );
353
354 $user = User::newFromName( $user->getName() );
355 $user->load( User::READ_LATEST );
356 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
357 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
358
359 $user = User::newFromName( $user->getName() );
360 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
361 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
362 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
363 }
364
370 public function testAnonOptions() {
372 $this->user->setOption( 'userjs-someoption', 'test' );
373 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
374 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
375 }
376
386 public function testCheckPasswordValidity() {
387 $this->setMwGlobals( [
388 'wgPasswordPolicy' => [
389 'policies' => [
390 'sysop' => [
391 'MinimalPasswordLength' => 8,
392 'MinimumPasswordLengthToLogin' => 1,
393 'PasswordCannotMatchUsername' => 1,
394 ],
395 'default' => [
396 'MinimalPasswordLength' => 6,
397 'PasswordCannotMatchUsername' => true,
398 'PasswordCannotMatchBlacklist' => true,
399 'MaximalPasswordLength' => 40,
400 ],
401 ],
402 'checks' => [
403 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
404 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
405 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
406 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
407 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
408 ],
409 ],
410 ] );
411
412 $user = static::getTestUser()->getUser();
413
414 // Sanity
415 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
416
417 // Minimum length
418 $this->assertFalse( $user->isValidPassword( 'a' ) );
419 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
420 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
421 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
422
423 // Maximum length
424 $longPass = str_repeat( 'a', 41 );
425 $this->assertFalse( $user->isValidPassword( $longPass ) );
426 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
427 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
428 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
429
430 // Matches username
431 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
432 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
433 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
434
435 // On the forbidden list
436 $user = User::newFromName( 'Useruser' );
437 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
438 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
439 }
440
445 public function testGetCanonicalName( $name, $expectedArray ) {
446 // fake interwiki map for the 'Interwiki prefix' testcase
447 $this->mergeMwGlobalArrayValue( 'wgHooks', [
448 'InterwikiLoadPrefix' => [
449 function ( $prefix, &$iwdata ) {
450 if ( $prefix === 'interwiki' ) {
451 $iwdata = [
452 'iw_url' => 'http://example.com/',
453 'iw_local' => 0,
454 'iw_trans' => 0,
455 ];
456 return false;
457 }
458 },
459 ],
460 ] );
461
462 foreach ( $expectedArray as $validate => $expected ) {
463 $this->assertEquals(
464 $expected,
465 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
466 }
467 }
468
469 public static function provideGetCanonicalName() {
470 return [
471 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
472 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
473 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
474 'valid' => false, 'false' => 'Talk:Username' ] ],
475 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
476 'valid' => false, 'false' => 'Interwiki:Username' ] ],
477 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
478 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
479 'usable' => 'Multi spaces' ] ],
480 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
481 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
482 'valid' => false, 'false' => 'In[]valid' ] ],
483 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
484 'false' => 'With / slash' ] ],
485 ];
486 }
487
491 public function testEquals() {
492 $first = $this->getMutableTestUser()->getUser();
493 $second = User::newFromName( $first->getName() );
494
495 $this->assertTrue( $first->equals( $first ) );
496 $this->assertTrue( $first->equals( $second ) );
497 $this->assertTrue( $second->equals( $first ) );
498
499 $third = $this->getMutableTestUser()->getUser();
500 $fourth = $this->getMutableTestUser()->getUser();
501
502 $this->assertFalse( $third->equals( $fourth ) );
503 $this->assertFalse( $fourth->equals( $third ) );
504
505 // Test users loaded from db with id
506 $user = $this->getMutableTestUser()->getUser();
507 $fifth = User::newFromId( $user->getId() );
508 $sixth = User::newFromName( $user->getName() );
509 $this->assertTrue( $fifth->equals( $sixth ) );
510 }
511
515 public function testGetId() {
516 $user = static::getTestUser()->getUser();
517 $this->assertTrue( $user->getId() > 0 );
518 }
519
524 public function testLoggedIn() {
525 $user = $this->getMutableTestUser()->getUser();
526 $this->assertTrue( $user->isLoggedIn() );
527 $this->assertFalse( $user->isAnon() );
528
529 // Non-existent users are perceived as anonymous
530 $user = User::newFromName( 'UTNonexistent' );
531 $this->assertFalse( $user->isLoggedIn() );
532 $this->assertTrue( $user->isAnon() );
533
534 $user = new User;
535 $this->assertFalse( $user->isLoggedIn() );
536 $this->assertTrue( $user->isAnon() );
537 }
538
542 public function testCheckAndSetTouched() {
543 $user = $this->getMutableTestUser()->getUser();
544 $user = TestingAccessWrapper::newFromObject( $user );
545 $this->assertTrue( $user->isLoggedIn() );
546
547 $touched = $user->getDBTouched();
548 $this->assertTrue(
549 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
550 $this->assertGreaterThan(
551 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
552
553 $touched = $user->getDBTouched();
554 $this->assertTrue(
555 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
556 $this->assertGreaterThan(
557 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
558 }
559
563 public function testFindUsersByGroup() {
564 $users = User::findUsersByGroup( [] );
565 $this->assertEquals( 0, iterator_count( $users ) );
566
567 $users = User::findUsersByGroup( 'foo' );
568 $this->assertEquals( 0, iterator_count( $users ) );
569
570 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
571 $users = User::findUsersByGroup( 'foo' );
572 $this->assertEquals( 1, iterator_count( $users ) );
573 $users->rewind();
574 $this->assertTrue( $user->equals( $users->current() ) );
575
576 // arguments have OR relationship
577 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
578 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
579 $this->assertEquals( 2, iterator_count( $users ) );
580 $users->rewind();
581 $this->assertTrue( $user->equals( $users->current() ) );
582 $users->next();
583 $this->assertTrue( $user2->equals( $users->current() ) );
584
585 // users are not duplicated
586 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
587 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
588 $this->assertEquals( 1, iterator_count( $users ) );
589 $users->rewind();
590 $this->assertTrue( $user->equals( $users->current() ) );
591 }
592
598 public function testAutoblockCookies() {
599 // Set up the bits of global configuration that we use.
600 $this->setMwGlobals( [
601 'wgCookieSetOnAutoblock' => true,
602 'wgCookiePrefix' => 'wmsitetitle',
603 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
604 ] );
605
606 // 1. Log in a test user, and block them.
607 $user1tmp = $this->getTestUser()->getUser();
608 $request1 = new FauxRequest();
609 $request1->getSession()->setUser( $user1tmp );
610 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
611 $block = new Block( [
612 'enableAutoblock' => true,
613 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
614 ] );
615 $block->setTarget( $user1tmp );
616 $block->insert();
617 $user1 = User::newFromSession( $request1 );
618 $user1->mBlock = $block;
619 $user1->load();
620
621 // Confirm that the block has been applied as required.
622 $this->assertTrue( $user1->isLoggedIn() );
623 $this->assertTrue( $user1->isBlocked() );
624 $this->assertEquals( Block::TYPE_USER, $block->getType() );
625 $this->assertTrue( $block->isAutoblocking() );
626 $this->assertGreaterThanOrEqual( 1, $block->getId() );
627
628 // Test for the desired cookie name, value, and expiry.
629 $cookies = $request1->response()->getCookies();
630 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
631 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
632 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
633 $this->assertEquals( $block->getId(), $cookieValue );
634
635 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
636 $request2 = new FauxRequest();
637 $request2->setCookie( 'BlockID', $block->getCookieValue() );
638 $user2 = User::newFromSession( $request2 );
639 $user2->load();
640 $this->assertNotEquals( $user1->getId(), $user2->getId() );
641 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
642 $this->assertTrue( $user2->isAnon() );
643 $this->assertFalse( $user2->isLoggedIn() );
644 $this->assertTrue( $user2->isBlocked() );
645 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
646 // Can't directly compare the objects becuase of member type differences.
647 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
648 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
649 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
650
651 // 3. Finally, set up a request as a new user, and the block should still be applied.
652 $user3tmp = $this->getTestUser()->getUser();
653 $request3 = new FauxRequest();
654 $request3->getSession()->setUser( $user3tmp );
655 $request3->setCookie( 'BlockID', $block->getId() );
656 $user3 = User::newFromSession( $request3 );
657 $user3->load();
658 $this->assertTrue( $user3->isLoggedIn() );
659 $this->assertTrue( $user3->isBlocked() );
660 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
661
662 // Clean up.
663 $block->delete();
664 }
665
671 // Set up the bits of global configuration that we use.
672 $this->setMwGlobals( [
673 'wgCookieSetOnAutoblock' => false,
674 'wgCookiePrefix' => 'wm_no_cookies',
675 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
676 ] );
677
678 // 1. Log in a test user, and block them.
679 $testUser = $this->getTestUser()->getUser();
680 $request1 = new FauxRequest();
681 $request1->getSession()->setUser( $testUser );
682 $block = new Block( [ 'enableAutoblock' => true ] );
683 $block->setTarget( $testUser );
684 $block->insert();
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 // 1. Log in a test user, and block them indefinitely.
715 $user1Tmp = $this->getTestUser()->getUser();
716 $request1 = new FauxRequest();
717 $request1->getSession()->setUser( $user1Tmp );
718 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
719 $block->setTarget( $user1Tmp );
720 $block->insert();
721 $user1 = User::newFromSession( $request1 );
722 $user1->mBlock = $block;
723 $user1->load();
724
725 // 2. Test the cookie's expiry timestamp.
726 $this->assertTrue( $user1->isLoggedIn() );
727 $this->assertTrue( $user1->isBlocked() );
728 $this->assertEquals( Block::TYPE_USER, $block->getType() );
729 $this->assertTrue( $block->isAutoblocking() );
730 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
731 $cookies = $request1->response()->getCookies();
732 // Test the cookie's expiry to the nearest minute.
733 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
734 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
735 // Check for expiry dates in a 10-second window, to account for slow testing.
736 $this->assertEquals(
737 $expOneDay,
738 $cookies['wm_infinite_blockBlockID']['expire'],
739 'Expiry date',
740 5.0
741 );
742
743 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
744 $newExpiry = wfTimestamp() + 2 * 60 * 60;
745 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
746 $block->update();
747 $user2tmp = $this->getTestUser()->getUser();
748 $request2 = new FauxRequest();
749 $request2->getSession()->setUser( $user2tmp );
750 $user2 = User::newFromSession( $request2 );
751 $user2->mBlock = $block;
752 $user2->load();
753 $cookies = $request2->response()->getCookies();
754 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
755 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
756
757 // Clean up.
758 $block->delete();
759 }
760
761 public function testSoftBlockRanges() {
763
764 $this->setMwGlobals( [
765 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
766 'wgUser' => null,
767 ] );
768
769 // IP isn't in $wgSoftBlockRanges
770 $request = new FauxRequest();
771 $request->setIP( '192.168.0.1' );
772 $wgUser = User::newFromSession( $request );
773 $this->assertNull( $wgUser->getBlock() );
774
775 // IP is in $wgSoftBlockRanges
776 $request = new FauxRequest();
777 $request->setIP( '10.20.30.40' );
778 $wgUser = User::newFromSession( $request );
779 $block = $wgUser->getBlock();
780 $this->assertInstanceOf( Block::class, $block );
781 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
782
783 // Make sure the block is really soft
784 $request->getSession()->setUser( $this->getTestUser()->getUser() );
785 $wgUser = User::newFromSession( $request );
786 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
787 $this->assertNull( $wgUser->getBlock() );
788 }
789
794 // Set up the bits of global configuration that we use.
795 $this->setMwGlobals( [
796 'wgCookieSetOnAutoblock' => true,
797 'wgCookiePrefix' => 'wmsitetitle',
798 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
799 ] );
800
801 // 1. Log in a blocked test user.
802 $user1tmp = $this->getTestUser()->getUser();
803 $request1 = new FauxRequest();
804 $request1->getSession()->setUser( $user1tmp );
805 $block = new Block( [ 'enableAutoblock' => true ] );
806 $block->setTarget( $user1tmp );
807 $block->insert();
808 $user1 = User::newFromSession( $request1 );
809 $user1->mBlock = $block;
810 $user1->load();
811
812 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
813 // user not blocked.
814 $request2 = new FauxRequest();
815 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
816 $user2 = User::newFromSession( $request2 );
817 $user2->load();
818 $this->assertTrue( $user2->isAnon() );
819 $this->assertFalse( $user2->isLoggedIn() );
820 $this->assertFalse( $user2->isBlocked() );
821
822 // Clean up.
823 $block->delete();
824 }
825
831 // Set up the bits of global configuration that we use.
832 $this->setMwGlobals( [
833 'wgCookieSetOnAutoblock' => true,
834 'wgCookiePrefix' => 'wmsitetitle',
835 'wgSecretKey' => null,
836 ] );
837
838 // 1. Log in a blocked test user.
839 $user1tmp = $this->getTestUser()->getUser();
840 $request1 = new FauxRequest();
841 $request1->getSession()->setUser( $user1tmp );
842 $block = new Block( [ 'enableAutoblock' => true ] );
843 $block->setTarget( $user1tmp );
844 $block->insert();
845 $user1 = User::newFromSession( $request1 );
846 $user1->mBlock = $block;
847 $user1->load();
848 $this->assertTrue( $user1->isBlocked() );
849
850 // 2. Create a new request, set the cookie to just the block ID, and the user should
851 // still get blocked when they log in again.
852 $request2 = new FauxRequest();
853 $request2->setCookie( 'BlockID', $block->getId() );
854 $user2 = User::newFromSession( $request2 );
855 $user2->load();
856 $this->assertNotEquals( $user1->getId(), $user2->getId() );
857 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
858 $this->assertTrue( $user2->isAnon() );
859 $this->assertFalse( $user2->isLoggedIn() );
860 $this->assertTrue( $user2->isBlocked() );
861 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
862
863 // Clean up.
864 $block->delete();
865 }
866
867 public function testIsPingLimitable() {
868 $request = new FauxRequest();
869 $request->setIP( '1.2.3.4' );
870 $user = User::newFromSession( $request );
871
872 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
873 $this->assertTrue( $user->isPingLimitable() );
874
875 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
876 $this->assertFalse( $user->isPingLimitable() );
877
878 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
879 $this->assertFalse( $user->isPingLimitable() );
880
881 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
882 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
883 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
884 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
885 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
886 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
887 }
888
889 public function provideExperienceLevel() {
890 return [
891 [ 2, 2, 'newcomer' ],
892 [ 12, 3, 'newcomer' ],
893 [ 8, 5, 'newcomer' ],
894 [ 15, 10, 'learner' ],
895 [ 450, 20, 'learner' ],
896 [ 460, 33, 'learner' ],
897 [ 525, 28, 'learner' ],
898 [ 538, 33, 'experienced' ],
899 ];
900 }
901
905 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
906 $this->setMwGlobals( [
907 'wgLearnerEdits' => 10,
908 'wgLearnerMemberSince' => 4,
909 'wgExperiencedUserEdits' => 500,
910 'wgExperiencedUserMemberSince' => 30,
911 ] );
912
913 $db = wfGetDB( DB_MASTER );
914
915 $data = new stdClass();
916 $data->user_id = 1;
917 $data->user_name = 'name';
918 $data->user_real_name = 'Real Name';
919 $data->user_touched = 1;
920 $data->user_token = 'token';
921 $data->user_email = 'a@a.a';
922 $data->user_email_authenticated = null;
923 $data->user_email_token = 'token';
924 $data->user_email_token_expires = null;
925 $data->user_editcount = $editCount;
926 $data->user_registration = $db->timestamp( time() - $memberSince * 86400 );
927 $user = User::newFromRow( $data );
928
929 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
930 }
931
932 public function testExperienceLevelAnon() {
933 $user = User::newFromName( '10.11.12.13', false );
934
935 $this->assertFalse( $user->getExperienceLevel() );
936 }
937}
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.
$wgUser
Definition Setup.php:781
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
Definition Block.php:1508
const TYPE_USER
Definition Block.php:83
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
WebRequest clone which takes values from a provided array.
static generateHex( $chars, $forceStrong=false)
Generate a run of (ideally) 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.
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
setMwGlobals( $pairs, $value=null)
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Database.
Definition UserTest.php:12
testUserPermissions()
User::getRights.
Definition UserTest.php:91
testGetGroupsWithPermission( $expected, $right)
provideGetGroupsWithPermission User::getGroupsWithPermission
Definition UserTest.php:155
testExperienceLevelAnon()
Definition UserTest.php:932
testUserGetRightsHooks()
User::getRights.
Definition UserTest.php:102
testOptions()
Test changing user options.
Definition UserTest.php:347
testGetCanonicalName( $name, $expectedArray)
User::getCanonicalName() provideGetCanonicalName.
Definition UserTest.php:445
User $user
Definition UserTest.php:16
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:598
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:793
testExperienceLevel( $editCount, $memberSince, $expLevel)
provideExperienceLevel
Definition UserTest.php:905
testIsPingLimitable()
Definition UserTest.php:867
static provideGetGroupsWithPermission()
Definition UserTest.php:163
testIsValidUserName( $username, $result, $message)
provideUserNames User::isValidUserName
Definition UserTest.php:213
testIsIP( $value, $result, $message)
provideIPs User::isIP
Definition UserTest.php:188
testGetEditCount()
Test User::editCount medium User::getEditCount.
Definition UserTest.php:271
testAutoblockCookieNoSecretKey()
The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
Definition UserTest.php:830
testSoftBlockRanges()
Definition UserTest.php:761
static provideGetCanonicalName()
Definition UserTest.php:469
testAnonOptions()
T39963 Make sure defaults are loaded when setOption is called.
Definition UserTest.php:370
setUpPermissionGlobals()
Definition UserTest.php:33
testIncEditCount()
Test User::editCount medium User::incEditCount.
Definition UserTest.php:328
testGetEditCountForAnons()
Test User::editCount medium User::getEditCount.
Definition UserTest.php:307
testRevokePermissions()
User::getGroupPermissions.
Definition UserTest.php:80
provideExperienceLevel()
Definition UserTest.php:889
testGetId()
User::getId.
Definition UserTest.php:515
testEquals()
User::equals.
Definition UserTest.php:491
testCheckPasswordValidity()
Test password validity checks.
Definition UserTest.php:386
testAllRightsWithMessage()
Test, if for all rights a right- message exist, which is used on Special:ListGroupRights as help text...
Definition UserTest.php:243
testCheckAndSetTouched()
User::checkAndSetTouched.
Definition UserTest.php:542
testLoggedIn()
User::isLoggedIn User::isAnon.
Definition UserTest.php:524
testAutoblockCookiesDisabled()
Make sure that no cookie is set to track autoblocked users when $wgCookieSetOnAutoblock is false.
Definition UserTest.php:670
testGroupPermissions()
User::getGroupPermissions.
Definition UserTest.php:63
static provideIPs()
Definition UserTest.php:192
testFindUsersByGroup()
User::findUsersByGroup.
Definition UserTest.php:563
static provideUserNames()
Definition UserTest.php:217
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:50
getPasswordValidity( $password)
Given unvalidated password input, return error message on failure.
Definition User.php:1000
getName()
Get the user name, or the IP of an anonymous user.
Definition User.php:2226
addToDatabase()
Add this existing user object to the database.
Definition User.php:4153
isBlocked( $bFromSlave=true)
Check if user is blocked.
Definition User.php:2044
getExperienceLevel()
Compute experienced level based on edit count and registration date.
Definition User.php:3792
addGroup( $group, $expiry=null)
Add the user to the given group.
Definition User.php:3412
getDBTouched()
Get the user_touched timestamp field (time of last DB updates)
Definition User.php:2562
getId()
Get the user's ID.
Definition User.php:2201
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition User.php:2858
isPingLimitable()
Is this user subject to rate limiting?
Definition User.php:1876
checkPasswordValidity( $password)
Check if this is a valid password for this user.
Definition User.php:1036
setOption( $oname, $val)
Set the given option for a user.
Definition User.php:2945
getEditCount()
Get the user's edit count.
Definition User.php:3377
isValidPassword( $password)
Is the input a valid password for this user?
Definition User.php:989
checkAndSetTouched()
Bump user_touched if it didn't change since this object was loaded.
Definition User.php:1500
getBlockId()
If user is blocked, return the ID for the block.
Definition User.php:2105
isLoggedIn()
Get whether the user is logged in.
Definition User.php:3478
saveSettings()
Save this user's settings into the database.
Definition User.php:3985
load( $flags=self::READ_NORMAL)
Load the user table data for this object from the source given by mFrom.
Definition User.php:367
getRights()
Get the permissions this user has.
Definition User.php:3234
equals(User $user)
Checks if two user objects point to the same user.
Definition User.php:5512
incEditCount()
Deferred version of incEditCountImmediate()
Definition User.php:5082
isAnon()
Get whether the user is anonymous.
Definition User.php:3486
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition WikiPage.php:120
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
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.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition hooks.txt:2578
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. '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 '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! 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! 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:1954
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2723
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:785
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
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