Merge "resourceloader: Switch params for private addLink() function"
[lhc/web/wiklou.git] / tests / phpunit / includes / TitleTest.php
1 <?php
2
3 use MediaWiki\Linker\LinkTarget;
4 use MediaWiki\MediaWikiServices;
5 use Wikimedia\TestingAccessWrapper;
6
7 /**
8 * @group Database
9 * @group Title
10 */
11 class TitleTest extends MediaWikiTestCase {
12 protected function setUp() {
13 parent::setUp();
14
15 $this->setMwGlobals( [
16 'wgAllowUserJs' => false,
17 'wgDefaultLanguageVariant' => false,
18 'wgMetaNamespace' => 'Project',
19 ] );
20 $this->setUserLang( 'en' );
21 $this->setContentLang( 'en' );
22 }
23
24 protected function tearDown() {
25 // For testNewMainPage
26 MessageCache::destroyInstance();
27 parent::tearDown();
28 }
29
30 /**
31 * @covers Title::legalChars
32 */
33 public function testLegalChars() {
34 $titlechars = Title::legalChars();
35
36 foreach ( range( 1, 255 ) as $num ) {
37 $chr = chr( $num );
38 if ( strpos( "#[]{}<>|", $chr ) !== false || preg_match( "/[\\x00-\\x1f\\x7f]/", $chr ) ) {
39 $this->assertFalse(
40 (bool)preg_match( "/[$titlechars]/", $chr ),
41 "chr($num) = $chr is not a valid titlechar"
42 );
43 } else {
44 $this->assertTrue(
45 (bool)preg_match( "/[$titlechars]/", $chr ),
46 "chr($num) = $chr is a valid titlechar"
47 );
48 }
49 }
50 }
51
52 public static function provideValidSecureAndSplit() {
53 return [
54 [ 'Sandbox' ],
55 [ 'A "B"' ],
56 [ 'A \'B\'' ],
57 [ '.com' ],
58 [ '~' ],
59 [ '#' ],
60 [ '"' ],
61 [ '\'' ],
62 [ 'Talk:Sandbox' ],
63 [ 'Talk:Foo:Sandbox' ],
64 [ 'File:Example.svg' ],
65 [ 'File_talk:Example.svg' ],
66 [ 'Foo/.../Sandbox' ],
67 [ 'Sandbox/...' ],
68 [ 'A~~' ],
69 [ ':A' ],
70 // Length is 256 total, but only title part matters
71 [ 'Category:' . str_repeat( 'x', 248 ) ],
72 [ str_repeat( 'x', 252 ) ],
73 // interwiki prefix
74 [ 'localtestiw: #anchor' ],
75 [ 'localtestiw:' ],
76 [ 'localtestiw:foo' ],
77 [ 'localtestiw: foo # anchor' ],
78 [ 'localtestiw: Talk: Sandbox # anchor' ],
79 [ 'remotetestiw:' ],
80 [ 'remotetestiw: Talk: # anchor' ],
81 [ 'remotetestiw: #bar' ],
82 [ 'remotetestiw: Talk:' ],
83 [ 'remotetestiw: Talk: Foo' ],
84 [ 'localtestiw:remotetestiw:' ],
85 [ 'localtestiw:remotetestiw:foo' ]
86 ];
87 }
88
89 public static function provideInvalidSecureAndSplit() {
90 return [
91 [ '', 'title-invalid-empty' ],
92 [ ':', 'title-invalid-empty' ],
93 [ '__ __', 'title-invalid-empty' ],
94 [ ' __ ', 'title-invalid-empty' ],
95 // Bad characters forbidden regardless of wgLegalTitleChars
96 [ 'A [ B', 'title-invalid-characters' ],
97 [ 'A ] B', 'title-invalid-characters' ],
98 [ 'A { B', 'title-invalid-characters' ],
99 [ 'A } B', 'title-invalid-characters' ],
100 [ 'A < B', 'title-invalid-characters' ],
101 [ 'A > B', 'title-invalid-characters' ],
102 [ 'A | B', 'title-invalid-characters' ],
103 [ "A \t B", 'title-invalid-characters' ],
104 [ "A \n B", 'title-invalid-characters' ],
105 // URL encoding
106 [ 'A%20B', 'title-invalid-characters' ],
107 [ 'A%23B', 'title-invalid-characters' ],
108 [ 'A%2523B', 'title-invalid-characters' ],
109 // XML/HTML character entity references
110 // Note: Commented out because they are not marked invalid by the PHP test as
111 // Title::newFromText runs Sanitizer::decodeCharReferencesAndNormalize first.
112 // 'A &eacute; B',
113 // 'A &#233; B',
114 // 'A &#x00E9; B',
115 // Subject of NS_TALK does not roundtrip to NS_MAIN
116 [ 'Talk:File:Example.svg', 'title-invalid-talk-namespace' ],
117 // Directory navigation
118 [ '.', 'title-invalid-relative' ],
119 [ '..', 'title-invalid-relative' ],
120 [ './Sandbox', 'title-invalid-relative' ],
121 [ '../Sandbox', 'title-invalid-relative' ],
122 [ 'Foo/./Sandbox', 'title-invalid-relative' ],
123 [ 'Foo/../Sandbox', 'title-invalid-relative' ],
124 [ 'Sandbox/.', 'title-invalid-relative' ],
125 [ 'Sandbox/..', 'title-invalid-relative' ],
126 // Tilde
127 [ 'A ~~~ Name', 'title-invalid-magic-tilde' ],
128 [ 'A ~~~~ Signature', 'title-invalid-magic-tilde' ],
129 [ 'A ~~~~~ Timestamp', 'title-invalid-magic-tilde' ],
130 // Length
131 [ str_repeat( 'x', 256 ), 'title-invalid-too-long' ],
132 // Namespace prefix without actual title
133 [ 'Talk:', 'title-invalid-empty' ],
134 [ 'Talk:#', 'title-invalid-empty' ],
135 [ 'Category: ', 'title-invalid-empty' ],
136 [ 'Category: #bar', 'title-invalid-empty' ],
137 // interwiki prefix
138 [ 'localtestiw: Talk: # anchor', 'title-invalid-empty' ],
139 [ 'localtestiw: Talk:', 'title-invalid-empty' ]
140 ];
141 }
142
143 private function secureAndSplitGlobals() {
144 $this->setMwGlobals( [
145 'wgLocalInterwikis' => [ 'localtestiw' ],
146 'wgHooks' => [
147 'InterwikiLoadPrefix' => [
148 function ( $prefix, &$data ) {
149 if ( $prefix === 'localtestiw' ) {
150 $data = [ 'iw_url' => 'localtestiw' ];
151 } elseif ( $prefix === 'remotetestiw' ) {
152 $data = [ 'iw_url' => 'remotetestiw' ];
153 }
154 return false;
155 }
156 ]
157 ]
158 ] );
159
160 // Reset TitleParser since we modified $wgLocalInterwikis
161 $this->setService( 'TitleParser', new MediaWikiTitleCodec(
162 Language::factory( 'en' ),
163 new GenderCache(),
164 [ 'localtestiw' ]
165 ) );
166 }
167
168 /**
169 * See also mediawiki.Title.test.js
170 * @covers Title::secureAndSplit
171 * @dataProvider provideValidSecureAndSplit
172 * @note This mainly tests MediaWikiTitleCodec::parseTitle().
173 */
174 public function testSecureAndSplitValid( $text ) {
175 $this->secureAndSplitGlobals();
176 $this->assertInstanceOf( Title::class, Title::newFromText( $text ), "Valid: $text" );
177 }
178
179 /**
180 * See also mediawiki.Title.test.js
181 * @covers Title::secureAndSplit
182 * @dataProvider provideInvalidSecureAndSplit
183 * @note This mainly tests MediaWikiTitleCodec::parseTitle().
184 */
185 public function testSecureAndSplitInvalid( $text, $expectedErrorMessage ) {
186 $this->secureAndSplitGlobals();
187 try {
188 Title::newFromTextThrow( $text ); // should throw
189 $this->assertTrue( false, "Invalid: $text" );
190 } catch ( MalformedTitleException $ex ) {
191 $this->assertEquals( $expectedErrorMessage, $ex->getErrorMessage(), "Invalid: $text" );
192 }
193 }
194
195 public static function provideConvertByteClassToUnicodeClass() {
196 return [
197 [
198 ' %!"$&\'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF+',
199 ' %!"$&\'()*,\\-./0-9:;=?@A-Z\\\\\\^_`a-z~+\\u0080-\\uFFFF',
200 ],
201 [
202 'QWERTYf-\\xFF+',
203 'QWERTYf-\\x7F+\\u0080-\\uFFFF',
204 ],
205 [
206 'QWERTY\\x66-\\xFD+',
207 'QWERTYf-\\x7F+\\u0080-\\uFFFF',
208 ],
209 [
210 'QWERTYf-y+',
211 'QWERTYf-y+',
212 ],
213 [
214 'QWERTYf-\\x80+',
215 'QWERTYf-\\x7F+\\u0080-\\uFFFF',
216 ],
217 [
218 'QWERTY\\x66-\\x80+\\x23',
219 'QWERTYf-\\x7F+#\\u0080-\\uFFFF',
220 ],
221 [
222 'QWERTY\\x66-\\x80+\\xD3',
223 'QWERTYf-\\x7F+\\u0080-\\uFFFF',
224 ],
225 [
226 '\\\\\\x99',
227 '\\\\\\u0080-\\uFFFF',
228 ],
229 [
230 '-\\x99',
231 '\\-\\u0080-\\uFFFF',
232 ],
233 [
234 'QWERTY\\-\\x99',
235 'QWERTY\\-\\u0080-\\uFFFF',
236 ],
237 [
238 '\\\\x99',
239 '\\\\x99',
240 ],
241 [
242 'A-\\x9F',
243 'A-\\x7F\\u0080-\\uFFFF',
244 ],
245 [
246 '\\x66-\\x77QWERTY\\x88-\\x91FXZ',
247 'f-wQWERTYFXZ\\u0080-\\uFFFF',
248 ],
249 [
250 '\\x66-\\x99QWERTY\\xAA-\\xEEFXZ',
251 'f-\\x7FQWERTYFXZ\\u0080-\\uFFFF',
252 ],
253 ];
254 }
255
256 /**
257 * @dataProvider provideConvertByteClassToUnicodeClass
258 * @covers Title::convertByteClassToUnicodeClass
259 */
260 public function testConvertByteClassToUnicodeClass( $byteClass, $unicodeClass ) {
261 $this->assertEquals( $unicodeClass, Title::convertByteClassToUnicodeClass( $byteClass ) );
262 }
263
264 /**
265 * @dataProvider provideSpecialNamesWithAndWithoutParameter
266 * @covers Title::fixSpecialName
267 */
268 public function testFixSpecialNameRetainsParameter( $text, $expectedParam ) {
269 $title = Title::newFromText( $text );
270 $fixed = $title->fixSpecialName();
271 $stuff = explode( '/', $fixed->getDBkey(), 2 );
272 if ( count( $stuff ) == 2 ) {
273 $par = $stuff[1];
274 } else {
275 $par = null;
276 }
277 $this->assertEquals(
278 $expectedParam,
279 $par,
280 "T33100 regression check: Title->fixSpecialName() should preserve parameter"
281 );
282 }
283
284 public static function provideSpecialNamesWithAndWithoutParameter() {
285 return [
286 [ 'Special:Version', null ],
287 [ 'Special:Version/', '' ],
288 [ 'Special:Version/param', 'param' ],
289 ];
290 }
291
292 /**
293 * Auth-less test of Title::isValidMoveOperation
294 *
295 * @param string $source
296 * @param string $target
297 * @param array|string|bool $expected Required error
298 * @dataProvider provideTestIsValidMoveOperation
299 * @covers Title::isValidMoveOperation
300 */
301 public function testIsValidMoveOperation( $source, $target, $expected ) {
302 $this->setMwGlobals( 'wgContentHandlerUseDB', false );
303 $title = Title::newFromText( $source );
304 $nt = Title::newFromText( $target );
305 $errors = $title->isValidMoveOperation( $nt, false );
306 if ( $expected === true ) {
307 $this->assertTrue( $errors );
308 } else {
309 $errors = $this->flattenErrorsArray( $errors );
310 foreach ( (array)$expected as $error ) {
311 $this->assertContains( $error, $errors );
312 }
313 }
314 }
315
316 public static function provideTestIsValidMoveOperation() {
317 return [
318 // for Title::isValidMoveOperation
319 [ 'Some page', '', 'badtitletext' ],
320 [ 'Test', 'Test', 'selfmove' ],
321 [ 'Special:FooBar', 'Test', 'immobile-source-namespace' ],
322 [ 'Test', 'Special:FooBar', 'immobile-target-namespace' ],
323 [ 'MediaWiki:Common.js', 'Help:Some wikitext page', 'bad-target-model' ],
324 [ 'Page', 'File:Test.jpg', 'nonfile-cannot-move-to-file' ],
325 [ 'File:Test.jpg', 'Page', 'imagenocrossnamespace' ],
326 ];
327 }
328
329 /**
330 * Auth-less test of Title::userCan
331 *
332 * @param array $whitelistRegexp
333 * @param string $source
334 * @param string $action
335 * @param array|string|bool $expected Required error
336 *
337 * @covers \Mediawiki\Permissions\PermissionManager::checkReadPermissions
338 * @dataProvider dataWgWhitelistReadRegexp
339 */
340 public function testWgWhitelistReadRegexp( $whitelistRegexp, $source, $action, $expected ) {
341 // $wgWhitelistReadRegexp must be an array. Since the provided test cases
342 // usually have only one regex, it is more concise to write the lonely regex
343 // as a string. Thus we cast to an array() to honor $wgWhitelistReadRegexp
344 // type requisite.
345 if ( is_string( $whitelistRegexp ) ) {
346 $whitelistRegexp = [ $whitelistRegexp ];
347 }
348
349 $this->setMwGlobals( [
350 // So User::isEveryoneAllowed( 'read' ) === false
351 'wgGroupPermissions' => [ '*' => [ 'read' => false ] ],
352 'wgWhitelistRead' => [ 'some random non sense title' ],
353 'wgWhitelistReadRegexp' => $whitelistRegexp,
354 ] );
355
356 $title = Title::newFromDBkey( $source );
357
358 // New anonymous user with no rights
359 $user = new User;
360 $user->mRights = [];
361 $errors = $title->userCan( $action, $user );
362
363 if ( is_bool( $expected ) ) {
364 # Forge the assertion message depending on the assertion expectation
365 $allowableness = $expected
366 ? " should be allowed"
367 : " should NOT be allowed";
368 $this->assertEquals(
369 $expected,
370 $errors,
371 "User action '$action' on [[$source]] $allowableness."
372 );
373 } else {
374 $errors = $this->flattenErrorsArray( $errors );
375 foreach ( (array)$expected as $error ) {
376 $this->assertContains( $error, $errors );
377 }
378 }
379 }
380
381 /**
382 * Provides test parameter values for testWgWhitelistReadRegexp()
383 */
384 public function dataWgWhitelistReadRegexp() {
385 $ALLOWED = true;
386 $DISALLOWED = false;
387
388 return [
389 // Everything, if this doesn't work, we're really in trouble
390 [ '/.*/', 'Main_Page', 'read', $ALLOWED ],
391 [ '/.*/', 'Main_Page', 'edit', $DISALLOWED ],
392
393 // We validate against the title name, not the db key
394 [ '/^Main_Page$/', 'Main_Page', 'read', $DISALLOWED ],
395 // Main page
396 [ '/^Main/', 'Main_Page', 'read', $ALLOWED ],
397 [ '/^Main.*/', 'Main_Page', 'read', $ALLOWED ],
398 // With spaces
399 [ '/Mic\sCheck/', 'Mic Check', 'read', $ALLOWED ],
400 // Unicode multibyte
401 // ...without unicode modifier
402 [ '/Unicode Test . Yes/', 'Unicode Test Ñ Yes', 'read', $DISALLOWED ],
403 // ...with unicode modifier
404 [ '/Unicode Test . Yes/u', 'Unicode Test Ñ Yes', 'read', $ALLOWED ],
405 // Case insensitive
406 [ '/MiC ChEcK/', 'mic check', 'read', $DISALLOWED ],
407 [ '/MiC ChEcK/i', 'mic check', 'read', $ALLOWED ],
408
409 // From DefaultSettings.php:
410 [ "@^UsEr.*@i", 'User is banned', 'read', $ALLOWED ],
411 [ "@^UsEr.*@i", 'User:John Doe', 'read', $ALLOWED ],
412
413 // With namespaces:
414 [ '/^Special:NewPages$/', 'Special:NewPages', 'read', $ALLOWED ],
415 [ null, 'Special:Newpages', 'read', $DISALLOWED ],
416
417 ];
418 }
419
420 public function flattenErrorsArray( $errors ) {
421 $result = [];
422 foreach ( $errors as $error ) {
423 $result[] = $error[0];
424 }
425
426 return $result;
427 }
428
429 /**
430 * @dataProvider provideGetPageViewLanguage
431 * @covers Title::getPageViewLanguage
432 */
433 public function testGetPageViewLanguage( $expected, $titleText, $contLang,
434 $lang, $variant, $msg = ''
435 ) {
436 // Setup environnement for this test
437 $this->setMwGlobals( [
438 'wgDefaultLanguageVariant' => $variant,
439 'wgAllowUserJs' => true,
440 ] );
441 $this->setUserLang( $lang );
442 $this->setContentLang( $contLang );
443
444 $title = Title::newFromText( $titleText );
445 $this->assertInstanceOf( Title::class, $title,
446 "Test must be passed a valid title text, you gave '$titleText'"
447 );
448 $this->assertEquals( $expected,
449 $title->getPageViewLanguage()->getCode(),
450 $msg
451 );
452 }
453
454 public static function provideGetPageViewLanguage() {
455 # Format:
456 # - expected
457 # - Title name
458 # - content language (expected in most cases)
459 # - wgLang (on some specific pages)
460 # - wgDefaultLanguageVariant
461 # - Optional message
462 return [
463 [ 'fr', 'Help:I_need_somebody', 'fr', 'fr', false ],
464 [ 'es', 'Help:I_need_somebody', 'es', 'zh-tw', false ],
465 [ 'zh', 'Help:I_need_somebody', 'zh', 'zh-tw', false ],
466
467 [ 'es', 'Help:I_need_somebody', 'es', 'zh-tw', 'zh-cn' ],
468 [ 'es', 'MediaWiki:About', 'es', 'zh-tw', 'zh-cn' ],
469 [ 'es', 'MediaWiki:About/', 'es', 'zh-tw', 'zh-cn' ],
470 [ 'de', 'MediaWiki:About/de', 'es', 'zh-tw', 'zh-cn' ],
471 [ 'en', 'MediaWiki:Common.js', 'es', 'zh-tw', 'zh-cn' ],
472 [ 'en', 'MediaWiki:Common.css', 'es', 'zh-tw', 'zh-cn' ],
473 [ 'en', 'User:JohnDoe/Common.js', 'es', 'zh-tw', 'zh-cn' ],
474 [ 'en', 'User:JohnDoe/Monobook.css', 'es', 'zh-tw', 'zh-cn' ],
475
476 [ 'zh-cn', 'Help:I_need_somebody', 'zh', 'zh-tw', 'zh-cn' ],
477 [ 'zh', 'MediaWiki:About', 'zh', 'zh-tw', 'zh-cn' ],
478 [ 'zh', 'MediaWiki:About/', 'zh', 'zh-tw', 'zh-cn' ],
479 [ 'de', 'MediaWiki:About/de', 'zh', 'zh-tw', 'zh-cn' ],
480 [ 'zh-cn', 'MediaWiki:About/zh-cn', 'zh', 'zh-tw', 'zh-cn' ],
481 [ 'zh-tw', 'MediaWiki:About/zh-tw', 'zh', 'zh-tw', 'zh-cn' ],
482 [ 'en', 'MediaWiki:Common.js', 'zh', 'zh-tw', 'zh-cn' ],
483 [ 'en', 'MediaWiki:Common.css', 'zh', 'zh-tw', 'zh-cn' ],
484 [ 'en', 'User:JohnDoe/Common.js', 'zh', 'zh-tw', 'zh-cn' ],
485 [ 'en', 'User:JohnDoe/Monobook.css', 'zh', 'zh-tw', 'zh-cn' ],
486
487 [ 'zh-tw', 'Special:NewPages', 'es', 'zh-tw', 'zh-cn' ],
488 [ 'zh-tw', 'Special:NewPages', 'zh', 'zh-tw', 'zh-cn' ],
489
490 ];
491 }
492
493 /**
494 * @dataProvider provideBaseTitleCases
495 * @covers Title::getBaseText
496 */
497 public function testGetBaseText( $title, $expected, $msg = '' ) {
498 $title = Title::newFromText( $title );
499 $this->assertEquals( $expected,
500 $title->getBaseText(),
501 $msg
502 );
503 }
504
505 public static function provideBaseTitleCases() {
506 return [
507 # Title, expected base, optional message
508 [ 'User:John_Doe/subOne/subTwo', 'John Doe/subOne' ],
509 [ 'User:Foo/Bar/Baz', 'Foo/Bar' ],
510 ];
511 }
512
513 /**
514 * @dataProvider provideRootTitleCases
515 * @covers Title::getRootText
516 */
517 public function testGetRootText( $title, $expected, $msg = '' ) {
518 $title = Title::newFromText( $title );
519 $this->assertEquals( $expected,
520 $title->getRootText(),
521 $msg
522 );
523 }
524
525 public static function provideRootTitleCases() {
526 return [
527 # Title, expected base, optional message
528 [ 'User:John_Doe/subOne/subTwo', 'John Doe' ],
529 [ 'User:Foo/Bar/Baz', 'Foo' ],
530 ];
531 }
532
533 /**
534 * @todo Handle $wgNamespacesWithSubpages cases
535 * @dataProvider provideSubpageTitleCases
536 * @covers Title::getSubpageText
537 */
538 public function testGetSubpageText( $title, $expected, $msg = '' ) {
539 $title = Title::newFromText( $title );
540 $this->assertEquals( $expected,
541 $title->getSubpageText(),
542 $msg
543 );
544 }
545
546 public static function provideSubpageTitleCases() {
547 return [
548 # Title, expected base, optional message
549 [ 'User:John_Doe/subOne/subTwo', 'subTwo' ],
550 [ 'User:John_Doe/subOne', 'subOne' ],
551 ];
552 }
553
554 public static function provideNewFromTitleValue() {
555 return [
556 [ new TitleValue( NS_MAIN, 'Foo' ) ],
557 [ new TitleValue( NS_MAIN, 'Foo', 'bar' ) ],
558 [ new TitleValue( NS_USER, 'Hansi_Maier' ) ],
559 ];
560 }
561
562 /**
563 * @covers Title::newFromTitleValue
564 * @dataProvider provideNewFromTitleValue
565 */
566 public function testNewFromTitleValue( TitleValue $value ) {
567 $title = Title::newFromTitleValue( $value );
568
569 $dbkey = str_replace( ' ', '_', $value->getText() );
570 $this->assertEquals( $dbkey, $title->getDBkey() );
571 $this->assertEquals( $value->getNamespace(), $title->getNamespace() );
572 $this->assertEquals( $value->getFragment(), $title->getFragment() );
573 }
574
575 /**
576 * @covers Title::newFromLinkTarget
577 * @dataProvider provideNewFromTitleValue
578 */
579 public function testNewFromLinkTarget( LinkTarget $value ) {
580 $title = Title::newFromLinkTarget( $value );
581
582 $dbkey = str_replace( ' ', '_', $value->getText() );
583 $this->assertEquals( $dbkey, $title->getDBkey() );
584 $this->assertEquals( $value->getNamespace(), $title->getNamespace() );
585 $this->assertEquals( $value->getFragment(), $title->getFragment() );
586 }
587
588 /**
589 * @covers Title::newFromLinkTarget
590 */
591 public function testNewFromLinkTarget_clone() {
592 $title = Title::newFromText( __METHOD__ );
593 $this->assertSame( $title, Title::newFromLinkTarget( $title ) );
594
595 // The Title::NEW_CLONE flag should ensure that a fresh instance is returned.
596 $clone = Title::newFromLinkTarget( $title, Title::NEW_CLONE );
597 $this->assertNotSame( $title, $clone );
598 $this->assertTrue( $clone->equals( $title ) );
599 }
600
601 public static function provideGetTitleValue() {
602 return [
603 [ 'Foo' ],
604 [ 'Foo#bar' ],
605 [ 'User:Hansi_Maier' ],
606 ];
607 }
608
609 /**
610 * @covers Title::getTitleValue
611 * @dataProvider provideGetTitleValue
612 */
613 public function testGetTitleValue( $text ) {
614 $title = Title::newFromText( $text );
615 $value = $title->getTitleValue();
616
617 $dbkey = str_replace( ' ', '_', $value->getText() );
618 $this->assertEquals( $title->getDBkey(), $dbkey );
619 $this->assertEquals( $title->getNamespace(), $value->getNamespace() );
620 $this->assertEquals( $title->getFragment(), $value->getFragment() );
621 }
622
623 public static function provideGetFragment() {
624 return [
625 [ 'Foo', '' ],
626 [ 'Foo#bar', 'bar' ],
627 [ 'Foo#bär', 'bär' ],
628
629 // Inner whitespace is normalized
630 [ 'Foo#bar_bar', 'bar bar' ],
631 [ 'Foo#bar bar', 'bar bar' ],
632 [ 'Foo#bar bar', 'bar bar' ],
633
634 // Leading whitespace is kept, trailing whitespace is trimmed.
635 // XXX: Is this really want we want?
636 [ 'Foo#_bar_bar_', ' bar bar' ],
637 [ 'Foo# bar bar ', ' bar bar' ],
638 ];
639 }
640
641 /**
642 * @covers Title::getFragment
643 * @dataProvider provideGetFragment
644 *
645 * @param string $full
646 * @param string $fragment
647 */
648 public function testGetFragment( $full, $fragment ) {
649 $title = Title::newFromText( $full );
650 $this->assertEquals( $fragment, $title->getFragment() );
651 }
652
653 /**
654 * @covers Title::isAlwaysKnown
655 * @dataProvider provideIsAlwaysKnown
656 * @param string $page
657 * @param bool $isKnown
658 */
659 public function testIsAlwaysKnown( $page, $isKnown ) {
660 $title = Title::newFromText( $page );
661 $this->assertEquals( $isKnown, $title->isAlwaysKnown() );
662 }
663
664 public static function provideIsAlwaysKnown() {
665 return [
666 [ 'Some nonexistent page', false ],
667 [ 'UTPage', false ],
668 [ '#test', true ],
669 [ 'Special:BlankPage', true ],
670 [ 'Special:SomeNonexistentSpecialPage', false ],
671 [ 'MediaWiki:Parentheses', true ],
672 [ 'MediaWiki:Some nonexistent message', false ],
673 ];
674 }
675
676 /**
677 * @covers Title::isValid
678 * @dataProvider provideIsValid
679 * @param Title $title
680 * @param bool $isValid
681 */
682 public function testIsValid( Title $title, $isValid ) {
683 $this->assertEquals( $isValid, $title->isValid(), $title->getPrefixedText() );
684 }
685
686 public static function provideIsValid() {
687 return [
688 [ Title::makeTitle( NS_MAIN, '' ), false ],
689 [ Title::makeTitle( NS_MAIN, '<>' ), false ],
690 [ Title::makeTitle( NS_MAIN, '|' ), false ],
691 [ Title::makeTitle( NS_MAIN, '#' ), false ],
692 [ Title::makeTitle( NS_MAIN, 'Test' ), true ],
693 [ Title::makeTitle( -33, 'Test' ), false ],
694 [ Title::makeTitle( 77663399, 'Test' ), false ],
695 ];
696 }
697
698 /**
699 * @covers Title::isAlwaysKnown
700 */
701 public function testIsAlwaysKnownOnInterwiki() {
702 $title = Title::makeTitle( NS_MAIN, 'Interwiki link', '', 'externalwiki' );
703 $this->assertTrue( $title->isAlwaysKnown() );
704 }
705
706 /**
707 * @covers Title::exists
708 */
709 public function testExists() {
710 $title = Title::makeTitle( NS_PROJECT, 'New page' );
711 $linkCache = MediaWikiServices::getInstance()->getLinkCache();
712
713 $article = new Article( $title );
714 $page = $article->getPage();
715 $page->doEditContent( new WikitextContent( 'Some [[link]]' ), 'summary' );
716
717 // Tell Title it doesn't know whether it exists
718 $title->mArticleID = -1;
719
720 // Tell the link cache it doesn't exists when it really does
721 $linkCache->clearLink( $title );
722 $linkCache->addBadLinkObj( $title );
723
724 $this->assertEquals(
725 false,
726 $title->exists(),
727 'exists() should rely on link cache unless GAID_FOR_UPDATE is used'
728 );
729 $this->assertEquals(
730 true,
731 $title->exists( Title::GAID_FOR_UPDATE ),
732 'exists() should re-query database when GAID_FOR_UPDATE is used'
733 );
734 }
735
736 public function provideCanHaveTalkPage() {
737 return [
738 'User page has talk page' => [
739 Title::makeTitle( NS_USER, 'Jane' ), true
740 ],
741 'Talke page has talk page' => [
742 Title::makeTitle( NS_TALK, 'Foo' ), true
743 ],
744 'Special page cannot have talk page' => [
745 Title::makeTitle( NS_SPECIAL, 'Thing' ), false
746 ],
747 'Virtual namespace cannot have talk page' => [
748 Title::makeTitle( NS_MEDIA, 'Kitten.jpg' ), false
749 ],
750 ];
751 }
752
753 /**
754 * @dataProvider provideCanHaveTalkPage
755 * @covers Title::canHaveTalkPage
756 *
757 * @param Title $title
758 * @param bool $expected
759 */
760 public function testCanHaveTalkPage( Title $title, $expected ) {
761 $actual = $title->canHaveTalkPage();
762 $this->assertSame( $expected, $actual, $title->getPrefixedDBkey() );
763 }
764
765 public static function provideGetTalkPage_good() {
766 return [
767 [ Title::makeTitle( NS_MAIN, 'Test' ), Title::makeTitle( NS_TALK, 'Test' ) ],
768 [ Title::makeTitle( NS_TALK, 'Test' ), Title::makeTitle( NS_TALK, 'Test' ) ],
769 ];
770 }
771
772 /**
773 * @dataProvider provideGetTalkPage_good
774 * @covers Title::getTalkPage
775 */
776 public function testGetTalkPage_good( Title $title, Title $expected ) {
777 $talk = $title->getTalkPage();
778 $this->assertSame(
779 $expected->getPrefixedDBKey(),
780 $talk->getPrefixedDBKey(),
781 $title->getPrefixedDBKey()
782 );
783 }
784
785 /**
786 * @dataProvider provideGetTalkPage_good
787 * @covers Title::getTalkPageIfDefined
788 */
789 public function testGetTalkPageIfDefined_good( Title $title ) {
790 $talk = $title->getTalkPageIfDefined();
791 $this->assertInstanceOf(
792 Title::class,
793 $talk,
794 $title->getPrefixedDBKey()
795 );
796 }
797
798 public static function provideGetTalkPage_bad() {
799 return [
800 [ Title::makeTitle( NS_SPECIAL, 'Test' ) ],
801 [ Title::makeTitle( NS_MEDIA, 'Test' ) ],
802 ];
803 }
804
805 /**
806 * @dataProvider provideGetTalkPage_bad
807 * @covers Title::getTalkPageIfDefined
808 */
809 public function testGetTalkPageIfDefined_bad( Title $title ) {
810 $talk = $title->getTalkPageIfDefined();
811 $this->assertNull(
812 $talk,
813 $title->getPrefixedDBKey()
814 );
815 }
816
817 public function provideCreateFragmentTitle() {
818 return [
819 [ Title::makeTitle( NS_MAIN, 'Test' ), 'foo' ],
820 [ Title::makeTitle( NS_TALK, 'Test', 'foo' ), '' ],
821 [ Title::makeTitle( NS_CATEGORY, 'Test', 'foo' ), 'bar' ],
822 [ Title::makeTitle( NS_MAIN, 'Test1', '', 'interwiki' ), 'baz' ]
823 ];
824 }
825
826 /**
827 * @covers Title::createFragmentTarget
828 * @dataProvider provideCreateFragmentTitle
829 */
830 public function testCreateFragmentTitle( Title $title, $fragment ) {
831 $this->mergeMwGlobalArrayValue( 'wgHooks', [
832 'InterwikiLoadPrefix' => [
833 function ( $prefix, &$iwdata ) {
834 if ( $prefix === 'interwiki' ) {
835 $iwdata = [
836 'iw_url' => 'http://example.com/',
837 'iw_local' => 0,
838 'iw_trans' => 0,
839 ];
840 return false;
841 }
842 },
843 ],
844 ] );
845
846 $fragmentTitle = $title->createFragmentTarget( $fragment );
847
848 $this->assertEquals( $title->getNamespace(), $fragmentTitle->getNamespace() );
849 $this->assertEquals( $title->getText(), $fragmentTitle->getText() );
850 $this->assertEquals( $title->getInterwiki(), $fragmentTitle->getInterwiki() );
851 $this->assertEquals( $fragment, $fragmentTitle->getFragment() );
852 }
853
854 public function provideGetPrefixedText() {
855 return [
856 // ns = 0
857 [
858 Title::makeTitle( NS_MAIN, 'Foo bar' ),
859 'Foo bar'
860 ],
861 // ns = 2
862 [
863 Title::makeTitle( NS_USER, 'Foo bar' ),
864 'User:Foo bar'
865 ],
866 // ns = 3
867 [
868 Title::makeTitle( NS_USER_TALK, 'Foo bar' ),
869 'User talk:Foo bar'
870 ],
871 // fragment not included
872 [
873 Title::makeTitle( NS_MAIN, 'Foo bar', 'fragment' ),
874 'Foo bar'
875 ],
876 // ns = -2
877 [
878 Title::makeTitle( NS_MEDIA, 'Foo bar' ),
879 'Media:Foo bar'
880 ],
881 // non-existent namespace
882 [
883 Title::makeTitle( 100777, 'Foo bar' ),
884 'Special:Badtitle/NS100777:Foo bar'
885 ],
886 ];
887 }
888
889 /**
890 * @covers Title::getPrefixedText
891 * @dataProvider provideGetPrefixedText
892 */
893 public function testGetPrefixedText( Title $title, $expected ) {
894 $this->assertEquals( $expected, $title->getPrefixedText() );
895 }
896
897 public function provideGetPrefixedDBKey() {
898 return [
899 // ns = 0
900 [
901 Title::makeTitle( NS_MAIN, 'Foo_bar' ),
902 'Foo_bar'
903 ],
904 // ns = 2
905 [
906 Title::makeTitle( NS_USER, 'Foo_bar' ),
907 'User:Foo_bar'
908 ],
909 // ns = 3
910 [
911 Title::makeTitle( NS_USER_TALK, 'Foo_bar' ),
912 'User_talk:Foo_bar'
913 ],
914 // fragment not included
915 [
916 Title::makeTitle( NS_MAIN, 'Foo_bar', 'fragment' ),
917 'Foo_bar'
918 ],
919 // ns = -2
920 [
921 Title::makeTitle( NS_MEDIA, 'Foo_bar' ),
922 'Media:Foo_bar'
923 ],
924 // non-existent namespace
925 [
926 Title::makeTitle( 100777, 'Foo_bar' ),
927 'Special:Badtitle/NS100777:Foo_bar'
928 ],
929 ];
930 }
931
932 /**
933 * @covers Title::getPrefixedDBKey
934 * @dataProvider provideGetPrefixedDBKey
935 */
936 public function testGetPrefixedDBKey( Title $title, $expected ) {
937 $this->assertEquals( $expected, $title->getPrefixedDBkey() );
938 }
939
940 /**
941 * @covers Title::getFragmentForURL
942 * @dataProvider provideGetFragmentForURL
943 *
944 * @param string $titleStr
945 * @param string $expected
946 */
947 public function testGetFragmentForURL( $titleStr, $expected ) {
948 $this->setMwGlobals( [
949 'wgFragmentMode' => [ 'html5' ],
950 'wgExternalInterwikiFragmentMode' => 'legacy',
951 ] );
952 $dbw = wfGetDB( DB_MASTER );
953 $dbw->insert( 'interwiki',
954 [
955 [
956 'iw_prefix' => 'de',
957 'iw_url' => 'http://de.wikipedia.org/wiki/',
958 'iw_api' => 'http://de.wikipedia.org/w/api.php',
959 'iw_wikiid' => 'dewiki',
960 'iw_local' => 1,
961 'iw_trans' => 0,
962 ],
963 [
964 'iw_prefix' => 'zz',
965 'iw_url' => 'http://zzwiki.org/wiki/',
966 'iw_api' => 'http://zzwiki.org/w/api.php',
967 'iw_wikiid' => 'zzwiki',
968 'iw_local' => 0,
969 'iw_trans' => 0,
970 ],
971 ],
972 __METHOD__,
973 [ 'IGNORE' ]
974 );
975
976 $title = Title::newFromText( $titleStr );
977 self::assertEquals( $expected, $title->getFragmentForURL() );
978
979 $dbw->delete( 'interwiki', '*', __METHOD__ );
980 }
981
982 public function provideGetFragmentForURL() {
983 return [
984 [ 'Foo', '' ],
985 [ 'Foo#ümlåût', '#ümlåût' ],
986 [ 'de:Foo#Bå®', '#Bå®' ],
987 [ 'zz:Foo#тест', '#.D1.82.D0.B5.D1.81.D1.82' ],
988 ];
989 }
990
991 /**
992 * @covers Title::isRawHtmlMessage
993 * @dataProvider provideIsRawHtmlMessage
994 */
995 public function testIsRawHtmlMessage( $textForm, $expected ) {
996 $this->setMwGlobals( 'wgRawHtmlMessages', [
997 'foobar',
998 'foo_bar',
999 'foo-bar',
1000 ] );
1001
1002 $title = Title::newFromText( $textForm );
1003 $this->assertSame( $expected, $title->isRawHtmlMessage() );
1004 }
1005
1006 public function provideIsRawHtmlMessage() {
1007 return [
1008 [ 'MediaWiki:Foobar', true ],
1009 [ 'MediaWiki:Foo bar', true ],
1010 [ 'MediaWiki:Foo-bar', true ],
1011 [ 'MediaWiki:foo bar', true ],
1012 [ 'MediaWiki:foo-bar', true ],
1013 [ 'MediaWiki:foobar', true ],
1014 [ 'MediaWiki:some-other-message', false ],
1015 [ 'Main Page', false ],
1016 ];
1017 }
1018
1019 public function provideEquals() {
1020 yield [
1021 Title::newFromText( 'Main Page' ),
1022 Title::newFromText( 'Main Page' ),
1023 true
1024 ];
1025 yield [
1026 Title::newFromText( 'Main Page' ),
1027 Title::newFromText( 'Not The Main Page' ),
1028 false
1029 ];
1030 yield [
1031 Title::newFromText( 'Main Page' ),
1032 Title::newFromText( 'Project:Main Page' ),
1033 false
1034 ];
1035 yield [
1036 Title::newFromText( 'File:Example.png' ),
1037 Title::newFromText( 'Image:Example.png' ),
1038 true
1039 ];
1040 yield [
1041 Title::newFromText( 'Special:Version' ),
1042 Title::newFromText( 'Special:Version' ),
1043 true
1044 ];
1045 yield [
1046 Title::newFromText( 'Special:Version' ),
1047 Title::newFromText( 'Special:Recentchanges' ),
1048 false
1049 ];
1050 yield [
1051 Title::newFromText( 'Special:Version' ),
1052 Title::newFromText( 'Main Page' ),
1053 false
1054 ];
1055 yield [
1056 Title::makeTitle( NS_MAIN, 'Foo', '', '' ),
1057 Title::makeTitle( NS_MAIN, 'Foo', '', '' ),
1058 true
1059 ];
1060 yield [
1061 Title::makeTitle( NS_MAIN, 'Foo', '', '' ),
1062 Title::makeTitle( NS_MAIN, 'Bar', '', '' ),
1063 false
1064 ];
1065 yield [
1066 Title::makeTitle( NS_MAIN, 'Foo', '', '' ),
1067 Title::makeTitle( NS_TALK, 'Foo', '', '' ),
1068 false
1069 ];
1070 yield [
1071 Title::makeTitle( NS_MAIN, 'Foo', 'Bar', '' ),
1072 Title::makeTitle( NS_MAIN, 'Foo', 'Bar', '' ),
1073 true
1074 ];
1075 yield [
1076 Title::makeTitle( NS_MAIN, 'Foo', 'Bar', '' ),
1077 Title::makeTitle( NS_MAIN, 'Foo', 'Baz', '' ),
1078 true
1079 ];
1080 yield [
1081 Title::makeTitle( NS_MAIN, 'Foo', 'Bar', '' ),
1082 Title::makeTitle( NS_MAIN, 'Foo', '', '' ),
1083 true
1084 ];
1085 yield [
1086 Title::makeTitle( NS_MAIN, 'Foo', '', 'baz' ),
1087 Title::makeTitle( NS_MAIN, 'Foo', '', 'baz' ),
1088 true
1089 ];
1090 yield [
1091 Title::makeTitle( NS_MAIN, 'Foo', '', '' ),
1092 Title::makeTitle( NS_MAIN, 'Foo', '', 'baz' ),
1093 false
1094 ];
1095 }
1096
1097 /**
1098 * @covers Title::equals
1099 * @dataProvider provideEquals
1100 */
1101 public function testEquals( Title $firstValue, /* LinkTarget */ $secondValue, $expectedSame ) {
1102 $this->assertSame(
1103 $expectedSame,
1104 $firstValue->equals( $secondValue )
1105 );
1106 }
1107
1108 /**
1109 * @covers Title::newMainPage
1110 */
1111 public function testNewMainPage() {
1112 $msgCache = TestingAccessWrapper::newFromClass( MessageCache::class );
1113 $msgCache->instance = $this->createMock( MessageCache::class );
1114 $msgCache->instance->method( 'get' )->willReturn( 'Foresheet' );
1115 $msgCache->instance->method( 'transform' )->willReturn( 'Foresheet' );
1116
1117 $this->assertSame(
1118 'Foresheet',
1119 Title::newMainPage()->getText()
1120 );
1121 }
1122
1123 /**
1124 * @covers Title::newMainPage
1125 */
1126 public function testNewMainPageWithLocal() {
1127 $local = $this->createMock( MessageLocalizer::class );
1128 $local->method( 'msg' )->willReturn( new RawMessage( 'Prime Article' ) );
1129
1130 $this->assertSame(
1131 'Prime Article',
1132 Title::newMainPage( $local )->getText()
1133 );
1134 }
1135 }