Remove empty lines at end of functions
[lhc/web/wiklou.git] / tests / phpunit / includes / user / UserTest.php
1 <?php
2
3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
5
6 /**
7 * @group Database
8 */
9 class UserTest extends MediaWikiTestCase {
10 /**
11 * @var User
12 */
13 protected $user;
14
15 protected function setUp() {
16 parent::setUp();
17
18 $this->setMwGlobals( [
19 'wgGroupPermissions' => [],
20 'wgRevokePermissions' => [],
21 ] );
22
23 $this->setUpPermissionGlobals();
24
25 $this->user = new User;
26 $this->user->addGroup( 'unittesters' );
27 }
28
29 private function setUpPermissionGlobals() {
30 global $wgGroupPermissions, $wgRevokePermissions;
31
32 # Data for regular $wgGroupPermissions test
33 $wgGroupPermissions['unittesters'] = [
34 'test' => true,
35 'runtest' => true,
36 'writetest' => false,
37 'nukeworld' => false,
38 ];
39 $wgGroupPermissions['testwriters'] = [
40 'test' => true,
41 'writetest' => true,
42 'modifytest' => true,
43 ];
44
45 # Data for regular $wgRevokePermissions test
46 $wgRevokePermissions['formertesters'] = [
47 'runtest' => true,
48 ];
49
50 # For the options test
51 $wgGroupPermissions['*'] = [
52 'editmyoptions' => true,
53 ];
54 }
55
56 /**
57 * @covers User::getGroupPermissions
58 */
59 public function testGroupPermissions() {
60 $rights = User::getGroupPermissions( [ 'unittesters' ] );
61 $this->assertContains( 'runtest', $rights );
62 $this->assertNotContains( 'writetest', $rights );
63 $this->assertNotContains( 'modifytest', $rights );
64 $this->assertNotContains( 'nukeworld', $rights );
65
66 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
67 $this->assertContains( 'runtest', $rights );
68 $this->assertContains( 'writetest', $rights );
69 $this->assertContains( 'modifytest', $rights );
70 $this->assertNotContains( 'nukeworld', $rights );
71 }
72
73 /**
74 * @covers User::getGroupPermissions
75 */
76 public function testRevokePermissions() {
77 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
78 $this->assertNotContains( 'runtest', $rights );
79 $this->assertNotContains( 'writetest', $rights );
80 $this->assertNotContains( 'modifytest', $rights );
81 $this->assertNotContains( 'nukeworld', $rights );
82 }
83
84 /**
85 * @covers User::getRights
86 */
87 public function testUserPermissions() {
88 $rights = $this->user->getRights();
89 $this->assertContains( 'runtest', $rights );
90 $this->assertNotContains( 'writetest', $rights );
91 $this->assertNotContains( 'modifytest', $rights );
92 $this->assertNotContains( 'nukeworld', $rights );
93 }
94
95 /**
96 * @covers User::getRights
97 */
98 public function testUserGetRightsHooks() {
99 $user = new User;
100 $user->addGroup( 'unittesters' );
101 $user->addGroup( 'testwriters' );
102 $userWrapper = TestingAccessWrapper::newFromObject( $user );
103
104 $rights = $user->getRights();
105 $this->assertContains( 'test', $rights, 'sanity check' );
106 $this->assertContains( 'runtest', $rights, 'sanity check' );
107 $this->assertContains( 'writetest', $rights, 'sanity check' );
108 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
109
110 // Add a hook manipluating the rights
111 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
112 $rights[] = 'nukeworld';
113 $rights = array_diff( $rights, [ 'writetest' ] );
114 } ] ] );
115
116 $userWrapper->mRights = null;
117 $rights = $user->getRights();
118 $this->assertContains( 'test', $rights );
119 $this->assertContains( 'runtest', $rights );
120 $this->assertNotContains( 'writetest', $rights );
121 $this->assertContains( 'nukeworld', $rights );
122
123 // Add a Session that limits rights
124 $mock = $this->getMockBuilder( stdclass::class )
125 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
126 ->getMock();
127 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
128 $mock->method( 'getSessionId' )->willReturn(
129 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
130 );
131 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
132 $mockRequest = $this->getMockBuilder( FauxRequest::class )
133 ->setMethods( [ 'getSession' ] )
134 ->getMock();
135 $mockRequest->method( 'getSession' )->willReturn( $session );
136 $userWrapper->mRequest = $mockRequest;
137
138 $userWrapper->mRights = null;
139 $rights = $user->getRights();
140 $this->assertContains( 'test', $rights );
141 $this->assertNotContains( 'runtest', $rights );
142 $this->assertNotContains( 'writetest', $rights );
143 $this->assertNotContains( 'nukeworld', $rights );
144 }
145
146 /**
147 * @dataProvider provideGetGroupsWithPermission
148 * @covers User::getGroupsWithPermission
149 */
150 public function testGetGroupsWithPermission( $expected, $right ) {
151 $result = User::getGroupsWithPermission( $right );
152 sort( $result );
153 sort( $expected );
154
155 $this->assertEquals( $expected, $result, "Groups with permission $right" );
156 }
157
158 public static function provideGetGroupsWithPermission() {
159 return [
160 [
161 [ 'unittesters', 'testwriters' ],
162 'test'
163 ],
164 [
165 [ 'unittesters' ],
166 'runtest'
167 ],
168 [
169 [ 'testwriters' ],
170 'writetest'
171 ],
172 [
173 [ 'testwriters' ],
174 'modifytest'
175 ],
176 ];
177 }
178
179 /**
180 * @dataProvider provideIPs
181 * @covers User::isIP
182 */
183 public function testIsIP( $value, $result, $message ) {
184 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
185 }
186
187 public static function provideIPs() {
188 return [
189 [ '', false, 'Empty string' ],
190 [ ' ', false, 'Blank space' ],
191 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
192 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
193 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
194 [ '203.0.113.0', true, 'IPv4 example' ],
195 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
196 // Not valid IPs but classified as such by MediaWiki for negated asserting
197 // of whether this might be the identifier of a logged-out user or whether
198 // to allow usernames like it.
199 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
200 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
201 ];
202 }
203
204 /**
205 * @dataProvider provideUserNames
206 * @covers User::isValidUserName
207 */
208 public function testIsValidUserName( $username, $result, $message ) {
209 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
210 }
211
212 public static function provideUserNames() {
213 return [
214 [ '', false, 'Empty string' ],
215 [ ' ', false, 'Blank space' ],
216 [ 'abcd', false, 'Starts with small letter' ],
217 [ 'Ab/cd', false, 'Contains slash' ],
218 [ 'Ab cd', true, 'Whitespace' ],
219 [ '192.168.1.1', false, 'IP' ],
220 [ 'User:Abcd', false, 'Reserved Namespace' ],
221 [ '12abcd232', true, 'Starts with Numbers' ],
222 [ '?abcd', true, 'Start with ? mark' ],
223 [ '#abcd', false, 'Start with #' ],
224 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
225 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
226 [ 'Ab cd', false, ' Ideographic space' ],
227 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
228 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
229 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
230 ];
231 }
232
233 /**
234 * Test, if for all rights a right- message exist,
235 * which is used on Special:ListGroupRights as help text
236 * Extensions and core
237 */
238 public function testAllRightsWithMessage() {
239 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
240 $allRights = User::getAllRights();
241 $allMessageKeys = Language::getMessageKeysFor( 'en' );
242
243 $rightsWithMessage = [];
244 foreach ( $allMessageKeys as $message ) {
245 // === 0: must be at beginning of string (position 0)
246 if ( strpos( $message, 'right-' ) === 0 ) {
247 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
248 }
249 }
250
251 sort( $allRights );
252 sort( $rightsWithMessage );
253
254 $this->assertEquals(
255 $allRights,
256 $rightsWithMessage,
257 'Each user rights (core/extensions) has a corresponding right- message.'
258 );
259 }
260
261 /**
262 * Test User::editCount
263 * @group medium
264 * @covers User::getEditCount
265 */
266 public function testGetEditCount() {
267 $user = $this->getMutableTestUser()->getUser();
268
269 // let the user have a few (3) edits
270 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
271 for ( $i = 0; $i < 3; $i++ ) {
272 $page->doEditContent(
273 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
274 'test',
275 0,
276 false,
277 $user
278 );
279 }
280
281 $this->assertEquals(
282 3,
283 $user->getEditCount(),
284 'After three edits, the user edit count should be 3'
285 );
286
287 // increase the edit count
288 $user->incEditCount();
289
290 $this->assertEquals(
291 4,
292 $user->getEditCount(),
293 'After increasing the edit count manually, the user edit count should be 4'
294 );
295 }
296
297 /**
298 * Test User::editCount
299 * @group medium
300 * @covers User::getEditCount
301 */
302 public function testGetEditCountForAnons() {
303 $user = User::newFromName( 'Anonymous' );
304
305 $this->assertNull(
306 $user->getEditCount(),
307 'Edit count starts null for anonymous users.'
308 );
309
310 $user->incEditCount();
311
312 $this->assertNull(
313 $user->getEditCount(),
314 'Edit count remains null for anonymous users despite calls to increase it.'
315 );
316 }
317
318 /**
319 * Test User::editCount
320 * @group medium
321 * @covers User::incEditCount
322 */
323 public function testIncEditCount() {
324 $user = $this->getMutableTestUser()->getUser();
325 $user->incEditCount();
326
327 $reloadedUser = User::newFromId( $user->getId() );
328 $reloadedUser->incEditCount();
329
330 $this->assertEquals(
331 2,
332 $reloadedUser->getEditCount(),
333 'Increasing the edit count after a fresh load leaves the object up to date.'
334 );
335 }
336
337 /**
338 * Test changing user options.
339 * @covers User::setOption
340 * @covers User::getOption
341 */
342 public function testOptions() {
343 $user = $this->getMutableTestUser()->getUser();
344
345 $user->setOption( 'userjs-someoption', 'test' );
346 $user->setOption( 'cols', 200 );
347 $user->saveSettings();
348
349 $user = User::newFromName( $user->getName() );
350 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
351 $this->assertEquals( 200, $user->getOption( 'cols' ) );
352 }
353
354 /**
355 * Bug 37963
356 * Make sure defaults are loaded when setOption is called.
357 * @covers User::loadOptions
358 */
359 public function testAnonOptions() {
360 global $wgDefaultUserOptions;
361 $this->user->setOption( 'userjs-someoption', 'test' );
362 $this->assertEquals( $wgDefaultUserOptions['cols'], $this->user->getOption( 'cols' ) );
363 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
364 }
365
366 /**
367 * Test password validity checks. There are 3 checks in core,
368 * - ensure the password meets the minimal length
369 * - ensure the password is not the same as the username
370 * - ensure the username/password combo isn't forbidden
371 * @covers User::checkPasswordValidity()
372 * @covers User::getPasswordValidity()
373 * @covers User::isValidPassword()
374 */
375 public function testCheckPasswordValidity() {
376 $this->setMwGlobals( [
377 'wgPasswordPolicy' => [
378 'policies' => [
379 'sysop' => [
380 'MinimalPasswordLength' => 8,
381 'MinimumPasswordLengthToLogin' => 1,
382 'PasswordCannotMatchUsername' => 1,
383 ],
384 'default' => [
385 'MinimalPasswordLength' => 6,
386 'PasswordCannotMatchUsername' => true,
387 'PasswordCannotMatchBlacklist' => true,
388 'MaximalPasswordLength' => 40,
389 ],
390 ],
391 'checks' => [
392 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
393 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
394 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
395 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
396 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
397 ],
398 ],
399 ] );
400
401 $user = static::getTestUser()->getUser();
402
403 // Sanity
404 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
405
406 // Minimum length
407 $this->assertFalse( $user->isValidPassword( 'a' ) );
408 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
409 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
410 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
411
412 // Maximum length
413 $longPass = str_repeat( 'a', 41 );
414 $this->assertFalse( $user->isValidPassword( $longPass ) );
415 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
416 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
417 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
418
419 // Matches username
420 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
421 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
422 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
423
424 // On the forbidden list
425 $user = User::newFromName( 'Useruser' );
426 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
427 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
428 }
429
430 /**
431 * @covers User::getCanonicalName()
432 * @dataProvider provideGetCanonicalName
433 */
434 public function testGetCanonicalName( $name, $expectedArray ) {
435 // fake interwiki map for the 'Interwiki prefix' testcase
436 $this->mergeMwGlobalArrayValue( 'wgHooks', [
437 'InterwikiLoadPrefix' => [
438 function ( $prefix, &$iwdata ) {
439 if ( $prefix === 'interwiki' ) {
440 $iwdata = [
441 'iw_url' => 'http://example.com/',
442 'iw_local' => 0,
443 'iw_trans' => 0,
444 ];
445 return false;
446 }
447 },
448 ],
449 ] );
450
451 foreach ( $expectedArray as $validate => $expected ) {
452 $this->assertEquals(
453 $expected,
454 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
455 }
456 }
457
458 public static function provideGetCanonicalName() {
459 return [
460 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
461 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
462 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
463 'valid' => false, 'false' => 'Talk:Username' ] ],
464 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
465 'valid' => false, 'false' => 'Interwiki:Username' ] ],
466 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
467 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
468 'usable' => 'Multi spaces' ] ],
469 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
470 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
471 'valid' => false, 'false' => 'In[]valid' ] ],
472 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
473 'false' => 'With / slash' ] ],
474 ];
475 }
476
477 /**
478 * @covers User::equals
479 */
480 public function testEquals() {
481 $first = $this->getMutableTestUser()->getUser();
482 $second = User::newFromName( $first->getName() );
483
484 $this->assertTrue( $first->equals( $first ) );
485 $this->assertTrue( $first->equals( $second ) );
486 $this->assertTrue( $second->equals( $first ) );
487
488 $third = $this->getMutableTestUser()->getUser();
489 $fourth = $this->getMutableTestUser()->getUser();
490
491 $this->assertFalse( $third->equals( $fourth ) );
492 $this->assertFalse( $fourth->equals( $third ) );
493
494 // Test users loaded from db with id
495 $user = $this->getMutableTestUser()->getUser();
496 $fifth = User::newFromId( $user->getId() );
497 $sixth = User::newFromName( $user->getName() );
498 $this->assertTrue( $fifth->equals( $sixth ) );
499 }
500
501 /**
502 * @covers User::getId
503 */
504 public function testGetId() {
505 $user = static::getTestUser()->getUser();
506 $this->assertTrue( $user->getId() > 0 );
507 }
508
509 /**
510 * @covers User::isLoggedIn
511 * @covers User::isAnon
512 */
513 public function testLoggedIn() {
514 $user = $this->getMutableTestUser()->getUser();
515 $this->assertTrue( $user->isLoggedIn() );
516 $this->assertFalse( $user->isAnon() );
517
518 // Non-existent users are perceived as anonymous
519 $user = User::newFromName( 'UTNonexistent' );
520 $this->assertFalse( $user->isLoggedIn() );
521 $this->assertTrue( $user->isAnon() );
522
523 $user = new User;
524 $this->assertFalse( $user->isLoggedIn() );
525 $this->assertTrue( $user->isAnon() );
526 }
527
528 /**
529 * @covers User::checkAndSetTouched
530 */
531 public function testCheckAndSetTouched() {
532 $user = $this->getMutableTestUser()->getUser();
533 $user = TestingAccessWrapper::newFromObject( $user );
534 $this->assertTrue( $user->isLoggedIn() );
535
536 $touched = $user->getDBTouched();
537 $this->assertTrue(
538 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
539 $this->assertGreaterThan(
540 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
541
542 $touched = $user->getDBTouched();
543 $this->assertTrue(
544 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
545 $this->assertGreaterThan(
546 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
547 }
548
549 /**
550 * @covers User::findUsersByGroup
551 */
552 public function testFindUsersByGroup() {
553 $users = User::findUsersByGroup( [] );
554 $this->assertEquals( 0, iterator_count( $users ) );
555
556 $users = User::findUsersByGroup( 'foo' );
557 $this->assertEquals( 0, iterator_count( $users ) );
558
559 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
560 $users = User::findUsersByGroup( 'foo' );
561 $this->assertEquals( 1, iterator_count( $users ) );
562 $users->rewind();
563 $this->assertTrue( $user->equals( $users->current() ) );
564
565 // arguments have OR relationship
566 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
567 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
568 $this->assertEquals( 2, iterator_count( $users ) );
569 $users->rewind();
570 $this->assertTrue( $user->equals( $users->current() ) );
571 $users->next();
572 $this->assertTrue( $user2->equals( $users->current() ) );
573
574 // users are not duplicated
575 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
576 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
577 $this->assertEquals( 1, iterator_count( $users ) );
578 $users->rewind();
579 $this->assertTrue( $user->equals( $users->current() ) );
580 }
581 }