Debian Codegraph @

tests/phpunit/includes/Output/OutputPageTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Config\HashConfig;
4 use MediaWiki\Config\MultiConfig;
5 use MediaWiki\Context\RequestContext;
6 use MediaWiki\Html\Html;
7 use MediaWiki\Language\ILanguageConverter;
8 use MediaWiki\Language\Language;
9 use MediaWiki\Language\LanguageCode;
10 use MediaWiki\Language\RawMessage;
11 use MediaWiki\Languages\LanguageConverterFactory;
12 use MediaWiki\MainConfigNames;
13 use MediaWiki\Output\OutputPage;
14 use MediaWiki\Page\PageIdentity;
15 use MediaWiki\Page\PageReference;
16 use MediaWiki\Page\PageReferenceValue;
17 use MediaWiki\Page\PageStoreRecord;
18 use MediaWiki\Parser\ParserOutput;
19 use MediaWiki\Parser\ParserOutputFlags;
20 use MediaWiki\Permissions\Authority;
21 use MediaWiki\Permissions\PermissionStatus;
22 use MediaWiki\Request\FauxRequest;
23 use MediaWiki\Request\WebRequest;
24 use MediaWiki\ResourceLoader as RL;
25 use MediaWiki\ResourceLoader\ResourceLoader;
26 use MediaWiki\Tests\ResourceLoader\ResourceLoaderTestCase;
27 use MediaWiki\Tests\ResourceLoader\ResourceLoaderTestModule;
28 use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait;
29 use MediaWiki\Title\Title;
30 use MediaWiki\Title\TitleValue;
31 use MediaWiki\User\User;
32 use MediaWiki\Utils\MWTimestamp;
33 use PHPUnit\Framework\MockObject\MockObject;
34 use Wikimedia\DependencyStore\KeyValueDependencyStore;
35 use Wikimedia\LightweightObjectStore\ExpirationAwareness;
36 use Wikimedia\Rdbms\FakeResultWrapper;
37 use Wikimedia\TestingAccessWrapper;
38
39 /**
40 * @author Matthew Flaschen
41 *
42 * @group Database
43 * @group Output
44 * @covers \MediaWiki\Output\OutputPage
45 */
46 class OutputPageTest extends MediaWikiIntegrationTestCase {
47 use MockAuthorityTrait;
48 use MockTitleTrait;
49
50 private const SCREEN_MEDIA_QUERY = 'screen and (min-width: 982px)';
51 private const SCREEN_ONLY_MEDIA_QUERY = 'only screen and (min-width: 982px)';
52 private const RSS_RC_LINK = '<link rel="alternate" type="application/rss+xml" title=" RSS feed" href="/w/index.php?title=Special:RecentChanges&amp;feed=rss">';
53 private const ATOM_RC_LINK = '<link rel="alternate" type="application/atom+xml" title=" Atom feed" href="/w/index.php?title=Special:RecentChanges&amp;feed=atom">';
54
55 private const RSS_TEST_LINK = '<link rel="alternate" type="application/rss+xml" title="&quot;Test&quot; RSS feed" href="fake-link">';
56 private const ATOM_TEST_LINK = '<link rel="alternate" type="application/atom+xml" title="&quot;Test&quot; Atom feed" href="fake-link">';
57 // phpcs:enable
58
59 // Ensure that we don't affect the global ResourceLoader state.
60 protected function setUp(): void {
61 parent::setUp();
62 ResourceLoader::clearCache();
63
64 $this->overrideConfigValues( [
65 MainConfigNames::ScriptPath => '/mw',
66 MainConfigNames::Script => '/mw/index.php',
67 MainConfigNames::ArticlePath => '/wikipage/$1',
68 MainConfigNames::Server => 'http://example.org',
69 MainConfigNames::CanonicalServer => 'https://www.example.org',
70 ] );
71 $this->overrideConfigValue( MainConfigNames::LanguageCode, 'en' );
72 }
73
74 protected function tearDown(): void {
75 ResourceLoader::clearCache();
76 parent::tearDown();
77 }
78
79 /**
80 * @dataProvider provideRedirect
81 */
82 public function testRedirect( $url, $code = null ) {
83 $op = $this->newInstance();
84 if ( isset( $code ) ) {
85 $op->redirect( $url, $code );
86 } else {
87 $op->redirect( $url );
88 }
89 $expectedUrl = str_replace( "\n", '', $url );
90 $this->assertSame( $expectedUrl, $op->getRedirect() );
91 $this->assertSame( $expectedUrl, $op->mRedirect );
92 $this->assertSame( $code ?? '302', $op->mRedirectCode );
93 }
94
95 public static function provideRedirect() {
96 return [
97 [ 'http://example.com' ],
98 [ 'http://example.com', '400' ],
99 [ 'http://example.com', 'squirrels!!!' ],
100 [ "a\nb" ],
101 ];
102 }
103
104 private function setupFeedLinks( $feed, $types ): OutputPage {
105 $outputPage = $this->newInstance( [
106 MainConfigNames::AdvertisedFeedTypes => $types,
107 MainConfigNames::Feed => $feed,
108 MainConfigNames::OverrideSiteFeed => false,
109 MainConfigNames::Script => '/w',
110 MainConfigNames::Sitename => false,
111 ] );
112 $outputPage->setTitle( Title::makeTitle( NS_MAIN, 'Test' ) );
113 $this->overrideConfigValue( MainConfigNames::Script, '/w/index.php' );
114 return $outputPage;
115 }
116
117 private function assertFeedLinks( OutputPage $outputPage, $message, $present, $non_present ) {
118 $links = $outputPage->getHeadLinksArray();
119 foreach ( $present as $link ) {
120 $this->assertContains( $link, $links, $message );
121 }
122 foreach ( $non_present as $link ) {
123 $this->assertNotContains( $link, $links, $message );
124 }
125 }
126
127 private function assertFeedUILinks( OutputPage $outputPage, $ui_links ) {
128 if ( $ui_links ) {
129 $this->assertTrue( $outputPage->isSyndicated(), 'Syndication should be offered' );
130 $this->assertGreaterThan( 0, count( $outputPage->getSyndicationLinks() ),
131 'Some syndication links should be there' );
132 } else {
133 $this->assertFalse( $outputPage->isSyndicated(), 'No syndication should be offered' );
134 $this->assertSame( [], $outputPage->getSyndicationLinks(),
135 'No syndication links should be there' );
136 }
137 }
138
139 public static function provideFeedLinkData() {
140 return [
141 [
142 true, [ 'rss' ], 'Only RSS RC link should be offerred',
143 [ self::RSS_RC_LINK ], [ self::ATOM_RC_LINK ]
144 ],
145 [
146 true, [ 'atom' ], 'Only Atom RC link should be offerred',
147 [ self::ATOM_RC_LINK ], [ self::RSS_RC_LINK ]
148 ],
149 [
150 true, [], 'No RC feed formats should be offerred',
151 [], [ self::ATOM_RC_LINK, self::RSS_RC_LINK ]
152 ],
153 [
154 false, [ 'atom' ], 'No RC feeds should be offerred',
155 [], [ self::ATOM_RC_LINK, self::RSS_RC_LINK ]
156 ],
157 ];
158 }
159
160 public function testSetCanonicalUrl() {
161 $op = $this->newInstance();
162 $op->setCanonicalUrl( 'http://example.comm' );
163 $op->setCanonicalUrl( 'http://example.com' );
164
165 $this->assertSame( 'http://example.com', $op->getCanonicalUrl() );
166
167 $headLinks = $op->getHeadLinksArray();
168
169 $this->assertContains( Html::element( 'link', [
170 'rel' => 'canonical', 'href' => 'http://example.com'
171 ] ), $headLinks );
172
173 $this->assertNotContains( Html::element( 'link', [
174 'rel' => 'canonical', 'href' => 'http://example.comm'
175 ] ), $headLinks );
176 }
177
178 public static function provideGetHeadLinksArray() {
179 return [
180 [
181 [ MainConfigNames::EnableCanonicalServerLink => true ],
182 'https://www.example.org/xyzzy/Hello',
183 true,
184 '/xyzzy/Hello'
185 ],
186 [
187 [ MainConfigNames::EnableCanonicalServerLink => true ],
188 'https://www.example.org/wikipage/My_test_page',
189 true,
190 null
191 ],
192 [
193 [ MainConfigNames::EnableCanonicalServerLink => true ],
194 'https://www.mediawiki.org/wiki/Manual:FauxRequest.php',
195 false,
196 null
197 ],
198 ];
199 }
200
201 /**
202 * @dataProvider provideGetHeadLinksArray
203 */
204 public function testGetHeadLinksArray( $config, $canonicalUrl, $isArticleRelated, $canonicalUrlToSet = null ) {
205 $request = new FauxRequest();
206 $request->setRequestURL( 'https://www.mediawiki.org/wiki/Manual:FauxRequest.php' );
207 $op = $this->newInstance( $config, $request );
208 if ( $canonicalUrlToSet ) {
209 $op->setCanonicalUrl( $canonicalUrlToSet );
210 }
211 $op->setArticleRelated( $isArticleRelated );
212 $headLinks = $op->getHeadLinksArray();
213 $this->assertSame(
214 Html::element( 'link',
215 [ 'rel' => 'canonical', 'href' => $canonicalUrl ]
216 ),
217 $headLinks['link-canonical']
218 );
219 }
220
221 /**
222 * Test the generation of hreflang Tags when site language has variants
223 */
224 public function testGetLanguageVariantUrl() {
225 $this->overrideConfigValue( MainConfigNames::LanguageCode, 'zh' );
226
227 $op = $this->newInstance();
228 $headLinks = $op->getHeadLinksArray();
229
230 # T123901, T305540, T108443: Don't use language variant link for mixed-variant variant
231 # (the language code with converter / the main code)
232 $this->assertSame(
233 Html::element( 'link', [ 'rel' => 'alternate', 'hreflang' => 'zh',
234 'href' => 'http://example.org/wikipage/My_test_page' ] ),
235 $headLinks['link-alternate-language-zh']
236 );
237
238 # Make sure alternate URLs use BCP 47 codes in hreflang
239 $this->assertSame(
240 Html::element( 'link', [ 'rel' => 'alternate', 'hreflang' => 'zh-Hant-TW',
241 'href' => 'http://example.org/mw/index.php?title=My_test_page&variant=zh-tw' ] ),
242 $headLinks['link-alternate-language-zh-hant-tw']
243 );
244
245 # Make sure $wgVariantArticlePath work
246 # We currently use MediaWiki internal language code as the primary variant URL parameter
247 $this->overrideConfigValues( [
248 MainConfigNames::LanguageCode => 'zh',
249 MainConfigNames::VariantArticlePath => '/$2/$1',
250 ] );
251
252 $op = $this->newInstance();
253 $headLinks = $op->getHeadLinksArray();
254
255 $this->assertSame(
256 Html::element( 'link', [ 'rel' => 'alternate', 'hreflang' => 'zh-Hant-TW',
257 'href' => 'http://example.org/zh-tw/My_test_page' ] ),
258 $headLinks['link-alternate-language-zh-hant-tw']
259 );
260 }
261
262 public static function provideCanonicalUrlAndAlternateUrlData() {
263 # $messsage, $action, $urlVariant, $canonicalUrl, $altUrlLangCode, $present, $nonpresent
264 return [
265 [
266 'Non-specified variant with view action - '
267 . 'We currently use MediaWiki internal codes as the primary URL parameter',
268 null,
269 null,
270 'https://www.example.org/wikipage/My_test_page',
271 'zh-tw',
272 'http://example.org/mw/index.php?title=My_test_page&variant=zh-tw',
273 'http://example.org/mw/index.php?title=My_test_page&variant=zh-hant-tw',
274 ],
275 [
276 'Specified zh-tw variant with view action - '
277 . 'Canonical URL and alternate URL should be the same; '
278 . 'Alternate URL should be kept even when it is the current page view language',
279 null,
280 'zh-tw',
281 'https://www.example.org/mw/index.php?title=My_test_page&variant=zh-tw',
282 'zh-tw',
283 'http://example.org/mw/index.php?title=My_test_page&variant=zh-tw',
284 'http://example.org/mw/index.php?title=My_test_page&variant=zh-hant-tw',
285 ],
286 [
287 'Non-specified variant with history action - '
288 . 'There should be no alternate URLs for language variants'
289 . 'There should be no alternate URLs for language variants',
290 'history',
291 null,
292 'https://www.example.org/mw/index.php?title=My_test_page&action=history',
293 'zh-tw',
294 null,
295 'https://www.example.org/mw/index.php?title=My_test_page&action=history&variant=zh-tw',
296 ],
297 [
298 'Specified zh-tw variant with history action - '
299 . 'There should be no alternate URLs for language variants',
300 'history',
301 'zh-tw',
302 'https://www.example.org/mw/index.php?title=My_test_page&action=history',
303 'zh-tw',
304 null,
305 'https://www.example.org/mw/index.php?title=My_test_page&action=history&variant=zh-tw',
306 ],
307 ];
308 }
309
310 /**
311 * @dataProvider provideCanonicalUrlAndAlternateUrlData
312 */
313 public function testCanonicalUrlAndAlternateUrls(
314 $messsage, $action, $urlVariant, $canonicalUrl, $altUrlLangCode, $present, $nonpresent
315 ) {
316 $req = new FauxRequest( [
317 'title' => 'My_test_page',
318 'action' => $action,
319 'variant' => $urlVariant,
320 ] );
321 $this->setRequest( $req );
322 $this->overrideConfigValue( MainConfigNames::LanguageCode, 'zh' );
323 $op = $this->newInstance( [ MainConfigNames::EnableCanonicalServerLink => true ], $req );
324 $bcp47 = LanguageCode::bcp47( $altUrlLangCode );
325 $bcp47Lowercase = strtolower( $bcp47 );
326 $headLinks = $op->getHeadLinksArray();
327
328 $this->assertSame(
329 Html::element( 'link', [ 'rel' => 'canonical', 'href' => $canonicalUrl ] ),
330 $headLinks['link-canonical'],
331 $messsage
332 );
333
334 if ( isset( $present ) ) {
335 $this->assertSame(
336 Html::element(
337 'link',
338 [
339 'rel' => 'alternate',
340 'hreflang' => $bcp47,
341 'href' => $present,
342 ]
343 ),
344 $headLinks['link-alternate-language-' . $bcp47Lowercase],
345 $messsage
346 );
347 }
348
349 $this->assertNotContains(
350 Html::element(
351 'link',
352 [ 'rel' => 'alternate', 'hreflang' => $bcp47, 'href' => $nonpresent, ]
353 ),
354 $headLinks,
355 $messsage
356 );
357 }
358
359 public function testSetCopyrightUrl() {
360 $op = $this->newInstance();
361 $op->setCopyrightUrl( 'http://example.com' );
362
363 $this->assertSame(
364 Html::element( 'link', [ 'rel' => 'license', 'href' => 'http://example.com' ] ),
365 $op->getHeadLinksArray()['copyright']
366 );
367 }
368
369 /**
370 * @dataProvider provideFeedLinkData
371 */
372 public function testRecentChangesFeed( $feed, $advertised_feed_types,
373 $message, $present, $non_present ) {
374 $outputPage = $this->setupFeedLinks( $feed, $advertised_feed_types );
375 $this->assertFeedLinks( $outputPage, $message, $present, $non_present );
376 }
377
378 public static function provideAdditionalFeedData() {
379 return [
380 [
381 true, [ 'atom' ], 'Additional Atom feed should be offered',
382 'atom',
383 [ self::ATOM_TEST_LINK, self::ATOM_RC_LINK ],
384 [ self::RSS_TEST_LINK, self::RSS_RC_LINK ],
385 true,
386 ],
387 [
388 true, [ 'rss' ], 'Additional RSS feed should be offered',
389 'rss',
390 [ self::RSS_TEST_LINK, self::RSS_RC_LINK ],
391 [ self::ATOM_TEST_LINK, self::ATOM_RC_LINK ],
392 true,
393 ],
394 [
395 true, [ 'rss' ], 'Additional Atom feed should NOT be offered with RSS enabled',
396 'atom',
397 [ self::RSS_RC_LINK ],
398 [ self::RSS_TEST_LINK, self::ATOM_TEST_LINK, self::ATOM_RC_LINK ],
399 false,
400 ],
401 [
402 false, [ 'atom' ], 'Additional Atom feed should NOT be offered, all feeds disabled',
403 'atom',
404 [],
405 [
406 self::RSS_TEST_LINK, self::ATOM_TEST_LINK,
407 self::ATOM_RC_LINK, self::ATOM_RC_LINK,
408 ],
409 false,
410 ],
411 ];
412 }
413
414 /**
415 * @dataProvider provideAdditionalFeedData
416 */
417 public function testAdditionalFeeds( $feed, $advertised_feed_types, $message,
418 $additional_feed_type, $present, $non_present, $any_ui_links ) {
419 $outputPage = $this->setupFeedLinks( $feed, $advertised_feed_types );
420 $outputPage->addFeedLink( $additional_feed_type, 'fake-link' );
421 $this->assertFeedLinks( $outputPage, $message, $present, $non_present );
422 $this->assertFeedUILinks( $outputPage, $any_ui_links );
423 }
424
425 // @todo How to test setStatusCode?
426
427 public function testMetaTags() {
428 $op = $this->newInstance();
429 $op->addMeta( 'http:expires', '0' );
430 $op->addMeta( 'keywords', 'first' );
431 $op->addMeta( 'keywords', 'second' );
432 $op->addMeta( 'og:title', 'Ta-duh' );
433
434 $expected = [
435 [ 'http:expires', '0' ],
436 [ 'keywords', 'first' ],
437 [ 'keywords', 'second' ],
438 [ 'og:title', 'Ta-duh' ],
439 ];
440 $this->assertSame( $expected, $op->getMetaTags() );
441
442 $links = $op->getHeadLinksArray();
443 $this->assertContains( '<meta http-equiv="expires" content="0">', $links );
444 $this->assertContains( '<meta name="keywords" content="first">', $links );
445 $this->assertContains( '<meta name="keywords" content="second">', $links );
446 $this->assertContains( '<meta property="og:title" content="Ta-duh">', $links );
447 $this->assertArrayHasKey( 'meta-robots', $links );
448 }
449
450 public function testAddLink() {
451 $op = $this->newInstance();
452
453 $links = [
454 [],
455 [ 'rel' => 'foo', 'href' => 'http://example.com' ],
456 ];
457
458 foreach ( $links as $link ) {
459 $op->addLink( $link );
460 }
461
462 $this->assertSame( $links, $op->getLinkTags() );
463
464 $result = $op->getHeadLinksArray();
465
466 foreach ( $links as $link ) {
467 $this->assertContains( Html::element( 'link', $link ), $result );
468 }
469 }
470
471 public function testAddScript() {
472 $op = $this->newInstance();
473 $op->addScript( 'some random string' );
474
475 $this->assertStringContainsString(
476 "\nsome random string\n",
477 "\n" . $op->getBottomScripts() . "\n"
478 );
479 }
480
481 public function testAddScriptFile() {
482 $op = $this->newInstance();
483 $op->addScriptFile( '/somescript.js' );
484 $op->addScriptFile( '//example.com/somescript.js' );
485
486 $this->assertStringContainsString(
487 "\n" . Html::linkedScript( '/somescript.js' ) .
488 Html::linkedScript( '//example.com/somescript.js' ) . "\n",
489 "\n" . $op->getBottomScripts() . "\n"
490 );
491 }
492
493 public function testAddInlineScript() {
494 $op = $this->newInstance();
495 $op->addInlineScript( 'let foo = "bar";' );
496 $op->addInlineScript( 'alert( foo );' );
497
498 $this->assertStringContainsString(
499 "\n" . Html::inlineScript( "\nlet foo = \"bar\";\n" ) . "\n" .
500 Html::inlineScript( "\nalert( foo );\n" ) . "\n",
501 "\n" . $op->getBottomScripts() . "\n"
502 );
503 }
504
505 // @todo How to test addContentOverride(Callback)?
506
507 public function testHeadItems() {
508 $op = $this->newInstance();
509 $op->addHeadItem( 'a', 'b' );
510 $op->addHeadItems( [ 'c' => '<d>&amp;', 'e' => 'f', 'a' => 'q' ] );
511 $op->addHeadItem( 'e', 'g' );
512 $op->addHeadItems( 'x' );
513
514 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&amp;', 'e' => 'g', 'x' ],
515 $op->getHeadItemsArray() );
516
517 $this->assertTrue( $op->hasHeadItem( 'a' ) );
518 $this->assertTrue( $op->hasHeadItem( 'c' ) );
519 $this->assertTrue( $op->hasHeadItem( 'e' ) );
520 $this->assertTrue( $op->hasHeadItem( '0' ) );
521
522 $this->assertStringContainsString( "\nq\n<d>&amp;\ng\nx\n",
523 '' . $op->headElement( $op->getContext()->getSkin() ) );
524 }
525
526 public function testHeadItemsParserOutput() {
527 $op = $this->newInstance();
528 $stubPO1 = $this->createParserOutputStub( 'getHeadItems', [ 'a' => 'b' ] );
529 $op->addParserOutputMetadata( $stubPO1 );
530 $stubPO2 = $this->createParserOutputStub( 'getHeadItems',
531 [ 'c' => '<d>&amp;', 'e' => 'f', 'a' => 'q' ] );
532 $op->addParserOutputMetadata( $stubPO2 );
533 $stubPO3 = $this->createParserOutputStub( 'getHeadItems', [ 'e' => 'g' ] );
534 $op->addParserOutput( $stubPO3 );
535 $stubPO4 = $this->createParserOutputStub( 'getHeadItems', [ 'x' ] );
536 $op->addParserOutputMetadata( $stubPO4 );
537
538 $this->assertSame( [ 'a' => 'q', 'c' => '<d>&amp;', 'e' => 'g', 'x' ],
539 $op->getHeadItemsArray() );
540
541 $this->assertTrue( $op->hasHeadItem( 'a' ) );
542 $this->assertTrue( $op->hasHeadItem( 'c' ) );
543 $this->assertTrue( $op->hasHeadItem( 'e' ) );
544 $this->assertTrue( $op->hasHeadItem( '0' ) );
545 $this->assertFalse( $op->hasHeadItem( 'b' ) );
546
547 $this->assertStringContainsString( "\nq\n<d>&amp;\ng\nx\n",
548 '' . $op->headElement( $op->getContext()->getSkin() ) );
549 }
550
551 public function testCSPParserOutput() {
552 $this->overrideConfigValue( MainConfigNames::CSPHeader, [] );
553 foreach ( [ 'Default', 'Script', 'Style' ] as $type ) {
554 $op = $this->newInstance();
555 $ltype = strtolower( $type );
556 $stubPO1 = $this->createParserOutputStub( "getExtraCSP{$type}Srcs", [ "{$ltype}src.com" ] );
557 $op->addParserOutputMetadata( $stubPO1 );
558 $csp = TestingAccessWrapper::newFromObject( $op->getCSP() );
559 $actual = $csp->makeCSPDirectives( [ 'default-src' => [] ], false );
560 $regex = '/(^|;)\s*' . $ltype . '-src\s[^;]*' . $ltype . 'src\.com[\s;]/';
561 $this->assertMatchesRegularExpression( $regex, $actual, $type );
562 }
563 }
564
565 public function testAddBodyClasses() {
566 $op = $this->newInstance();
567 $op->addBodyClasses( 'a' );
568 $op->addBodyClasses( 'mediawiki' );
569 $op->addBodyClasses( 'b c' );
570 $op->addBodyClasses( [ 'd', 'e' ] );
571 $op->addBodyClasses( 'a' );
572
573 $this->assertStringContainsString( '<body class="a mediawiki b c d e ',
574 '' . $op->headElement( $op->getContext()->getSkin() ) );
575 }
576
577 public function testArticleBodyOnly() {
578 $op = $this->newInstance();
579 $this->assertFalse( $op->getArticleBodyOnly() );
580
581 $op->setArticleBodyOnly( true );
582 $this->assertTrue( $op->getArticleBodyOnly() );
583
584 $op->addHTML( '<b>a</b>' );
585
586 $this->assertSame( '<b>a</b>', $op->output( true ) );
587 }
588
589 public function testProperties() {
590 $op = $this->newInstance();
591
592 $this->assertNull( $op->getProperty( 'foo' ) );
593
594 $op->setProperty( 'foo', 'bar' );
595 $op->setProperty( 'baz', 'quz' );
596
597 $this->assertSame( 'bar', $op->getProperty( 'foo' ) );
598 $this->assertSame( 'quz', $op->getProperty( 'baz' ) );
599 }
600
601 /**
602 * @dataProvider provideCheckLastModified
603 */
604 public function testCheckLastModified(
605 $timestamp, $ifModifiedSince, $expected, $config = [], $callback = null
606 ) {
607 $request = new FauxRequest();
608 if ( $ifModifiedSince ) {
609 if ( is_numeric( $ifModifiedSince ) ) {
610 // Unix timestamp
611 $ifModifiedSince = date( 'D, d M Y H:i:s', $ifModifiedSince ) . ' GMT';
612 }
613 $request->setHeader( 'If-Modified-Since', $ifModifiedSince );
614 }
615
616 // Make sure it's not too recent
617 $config['CacheEpoch'] ??= '20000101000000';
618 $config['CachePages'] ??= true;
619
620 $op = $this->newInstance( $config, $request );
621
622 if ( $callback ) {
623 $callback( $op, $this );
624 }
625
626 // Ignore complaint about not being able to disable compression
627 $this->assertEquals( $expected, @$op->checkLastModified( $timestamp ) );
628 }
629
630 public function provideCheckLastModified() {
631 $lastModified = time() - 3600;
632 return [
633 'Timestamp 0' =>
634 [ '0', $lastModified, false ],
635 'Timestamp Unix epoch' =>
636 [ '19700101000000', $lastModified, false ],
637 'Timestamp same as If-Modified-Since' =>
638 [ $lastModified, $lastModified, true ],
639 'Timestamp one second after If-Modified-Since' =>
640 [ $lastModified + 1, $lastModified, false ],
641 'No If-Modified-Since' =>
642 [ $lastModified + 1, null, false ],
643 'Malformed If-Modified-Since' =>
644 [ $lastModified + 1, 'GIBBERING WOMBATS !!!', false ],
645 'Non-standard IE-style If-Modified-Since' =>
646 [ $lastModified, date( 'D, d M Y H:i:s', $lastModified ) . ' GMT; length=5202',
647 true ],
648 // @todo Should we fix this behavior to match the spec? Probably no reason to.
649 'If-Modified-Since not per spec but we accept it anyway because strtotime does' =>
650 [ $lastModified, "@$lastModified", true ],
651 '$wgCachePages = false' =>
652 [ $lastModified, $lastModified, false, [ MainConfigNames::CachePages => false ] ],
653 '$wgCacheEpoch' =>
654 [ $lastModified, $lastModified, false,
655 [ MainConfigNames::CacheEpoch => wfTimestamp( TS_MW, $lastModified + 1 ) ] ],
656 'Recently-touched user' =>
657 [ $lastModified, $lastModified, false, [],
658 function ( OutputPage $op ) {
659 $op->getContext()->setUser( $this->getTestUser()->getUser() );
660 } ],
661 'After CDN expiry' =>
662 [ $lastModified, $lastModified, false,
663 [ MainConfigNames::UseCdn => true, MainConfigNames::CdnMaxAge => 3599 ] ],
664 'Hook allows cache use' =>
665 [ $lastModified + 1, $lastModified, true, [],
666 static function ( $op, $that ) {
667 $that->setTemporaryHook( 'OutputPageCheckLastModified',
668 static function ( &$modifiedTimes ) {
669 $modifiedTimes = [ 1 ];
670 }
671 );
672 } ],
673 'Hooks prohibits cache use' =>
674 [ $lastModified, $lastModified, false, [],
675 static function ( $op, $that ) {
676 $that->setTemporaryHook( 'OutputPageCheckLastModified',
677 static function ( &$modifiedTimes ) {
678 $modifiedTimes = [ max( $modifiedTimes ) + 1 ];
679 }
680 );
681 } ],
682 ];
683 }
684
685 // @todo How to test setLastModified?
686
687 public function testSetRobotPolicy() {
688 $op = $this->newInstance();
689 $op->setRobotPolicy( 'noindex, nofollow' );
690
691 $links = $op->getHeadLinksArray();
692 $this->assertContains( '<meta name="robots" content="noindex,nofollow,max-image-preview:standard">', $links );
693 }
694
695 public function testSetRobotsOptions() {
696 $op = $this->newInstance();
697 $op->setRobotPolicy( 'nofollow' );
698 $op->setRobotsOptions( [ 'max-snippet' => '500' ] );
699 $op->setIndexPolicy( 'index' );
700
701 $links = $op->getHeadLinksArray();
702 $this->assertContains( '<meta name="robots" content="index,nofollow,max-image-preview:standard,max-snippet:500">', $links );
703
704 $op->setFollowPolicy( 'follow' );
705 $links = $op->getHeadLinksArray();
706 $this->assertContains(
707 '<meta name="robots" content="max-image-preview:standard,max-snippet:500">',
708 $links,
709 'When index,follow (browser default) omit'
710 );
711
712 $op->setIndexPolicy( 'noindex' );
713 $links = $op->getHeadLinksArray();
714 $this->assertContains(
715 '<meta name="robots" content="noindex,follow,max-image-preview:standard,max-snippet:500">',
716 $links,
717 'noindex takes precedence over index'
718 );
719
720 // Deprecated behavior: for OutputPage (unlike ParserOutput) we can
721 // reset to 'index' after 'noindex' has been set.
722 $this->filterDeprecated( '/OutputPage::setIndexPolicy with index after noindex/' );
723 $op->setIndexPolicy( 'index' );
724 $links = $op->getHeadLinksArray();
725 $this->assertContains(
726 '<meta name="robots" content="max-image-preview:standard,max-snippet:500">',
727 $links,
728 'index can reset noindex (deprecated)'
729 );
730 }
731
732 public function testGetRobotPolicy() {
733 $op = $this->newInstance();
734 $op->setRobotPolicy( 'noindex, follow' );
735
736 $policy = $op->getRobotPolicy();
737 $this->assertSame( 'noindex,follow', $policy );
738 }
739
740 /**
741 * This test is safe to remove once ::setIndexPolicy() is removed.
742 * @covers \MediaWiki\Output\OutputPage::setIndexPolicy
743 */
744 public function testSetIndexPoliciesBackCompat() {
745 $op = $this->newInstance();
746 $this->assertSame( "", $op->getMetadata()->getIndexPolicy() );
747 $op->setIndexPolicy( 'index' );
748 $this->assertEquals( "index", $op->getIndexPolicy() );
749 $this->assertEquals( "index", $op->getMetadata()->getIndexPolicy() );
750 $op->setIndexPolicy( 'noindex' );
751 $this->assertEquals( "noindex", $op->getIndexPolicy() );
752 $this->assertEquals( "noindex", $op->getMetadata()->getIndexPolicy() );
753 }
754
755 /**
756 * @covers \MediaWiki\Output\OutputPage::getMetadata
757 * @covers \MediaWiki\Output\OutputPage::getIndexPolicy
758 * @covers \MediaWiki\Output\OutputPage::setFollowPolicy
759 * @covers \MediaWiki\Output\OutputPage::getHeadLinksArray
760 */
761 public function testSetIndexFollowPolicies() {
762 $op = $this->newInstance();
763 $this->assertSame( "", $op->getMetadata()->getIndexPolicy() );
764 $this->assertEquals( "index", $op->getIndexPolicy() );
765 $op->getMetadata()->setIndexPolicy( 'noindex' );
766 $this->assertEquals( "noindex", $op->getIndexPolicy() );
767 $op->setFollowPolicy( 'nofollow' );
768
769 $links = $op->getHeadLinksArray();
770 $this->assertContains( '<meta name="robots" content="noindex,nofollow,max-image-preview:standard">', $links );
771 }
772
773 private function extractHTMLTitle( OutputPage $op ) {
774 $html = $op->headElement( $op->getContext()->getSkin() );
775
776 // OutputPage should always output the title in a nice format such that regexes will work
777 // fine. If it doesn't, we'll fail the tests.
778 preg_match_all( '!<title>(.*?)</title>!', $html, $matches );
779
780 $this->assertLessThanOrEqual( 1, count( $matches[1] ), 'More than one <title>!' );
781
782 return $matches[1][0] ?? null;
783 }
784
785 /**
786 * Shorthand for getting the text of a message, in content language.
787 * @param MessageLocalizer $op
788 * @param mixed ...$msgParams
789 * @return string
790 */
791 private static function getMsgText( MessageLocalizer $op, ...$msgParams ) {
792 return $op->msg( ...$msgParams )->inContentLanguage()->text();
793 }
794
795 public function testHTMLTitle() {
796 $op = $this->newInstance();
797
798 // Default
799 $this->assertSame( '', $op->getHTMLTitle() );
800 $this->assertSame( '', $op->getPageTitle() );
801 $this->assertSame(
802 $this->getMsgText( $op, 'pagetitle', '' ),
803 $this->extractHTMLTitle( $op )
804 );
805
806 // Set to string
807 $op->setHTMLTitle( 'Potatoes will eat me' );
808
809 $this->assertSame( 'Potatoes will eat me', $op->getHTMLTitle() );
810 $this->assertSame( 'Potatoes will eat me', $this->extractHTMLTitle( $op ) );
811 // Shouldn't have changed the page title
812 $this->assertSame( '', $op->getPageTitle() );
813
814 // Set to message
815 $msg = $op->msg( 'mainpage' );
816
817 $op->setHTMLTitle( $msg );
818 $this->assertSame( $msg->text(), $op->getHTMLTitle() );
819 $this->assertSame( $msg->text(), $this->extractHTMLTitle( $op ) );
820 $this->assertSame( '', $op->getPageTitle() );
821 }
822
823 public function testSetRedirectedFrom() {
824 $op = $this->newInstance();
825
826 $op->setRedirectedFrom( new PageReferenceValue( NS_TALK, 'Some page', PageReference::LOCAL ) );
827 $this->assertSame( 'Talk:Some_page', $op->getJSVars()['wgRedirectedFrom'] );
828 }
829
830 public function testPageTitle() {
831 // We don't test the actual HTML output anywhere, because that's up to the skin.
832 $op = $this->newInstance();
833
834 // Test default
835 $this->assertSame( '', $op->getPageTitle() );
836 $this->assertSame( '', $op->getHTMLTitle() );
837
838 // Test set to plain text
839 $op->setPageTitle( 'foobar' );
840
841 $this->assertSame( 'foobar', $op->getPageTitle() );
842 // HTML title should change as well
843 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'foobar' ), $op->getHTMLTitle() );
844
845 // Test set to text with good and bad HTML. We don't try to be *too*
846 // comprehensive here, that belongs in Sanitizer tests, but we'll
847 // address the issues specifically noted in T298401/T67747 at least...
848 $sanitizerTests = [
849 [
850 'input' => '<script>a</script>&amp;<i>b</i>',
851 'getPageTitle' => '&lt;script&gt;a&lt;/script&gt;&amp;<i>b</i>',
852 'getHTMLTitle' => '<script>a</script>&b',
853 ],
854 [
855 'input' => '<code style="display:none">', # T298401
856 'getPageTitle' => '<code style="display:none"></code>',
857 'getHTMLTitle' => '',
858 ],
859 [
860 'input' => '<b>Foo bar<b>', # T67747
861 'getPageTitle' => '<b>Foo bar<b></b></b>',
862 'getHTMLTitle' => 'Foo bar',
863 ],
864 ];
865 foreach ( $sanitizerTests as $case ) {
866 $op->setPageTitle( $case['input'] );
867
868 $this->assertSame( $case['getPageTitle'], $op->getPageTitle() );
869 $this->assertSame(
870 $this->getMsgText( $op, 'pagetitle', $case['getHTMLTitle'] ),
871 $op->getHTMLTitle()
872 );
873 }
874
875 // Test set to message (deprecated unescaped)
876 $text = $this->getMsgText( $op, 'mainpage' );
877
878 $op->setPageTitleMsg( $op->msg( 'mainpage' )->inContentLanguage() );
879 $this->assertSame( $text, $op->getPageTitle() );
880 $this->assertSame( $this->getMsgText( $op, 'pagetitle', $text ), $op->getHTMLTitle() );
881
882 // Test set to message (::setPageTitleMsg(), escaped)
883 $msg = ( new RawMessage( 'nope:<span>$1 yes:$2' ) )
884 ->plaintextParams( '</span>' )
885 ->rawParams( '<span>!</span>' );
886 // preferred ::setPageTitleMsg(Msg)
887 $op->setPageTitleMsg( $msg );
888 $this->assertSame( 'nope:&lt;span&gt;&lt;/span&gt; yes:<span>!</span>', $op->getPageTitle() );
889 // Note that HTML title is unescaped plaintext, it is expected to be
890 // HTML escaped before becoming the <title> element.
891 $this->assertSame( $this->getMsgText( $op, 'pagetitle', 'nope:<span></span> yes:!' ), $op->getHTMLTitle() );
892
893 // deprecated ::setPageTitle(Message), doesn't escape either
894 // the localized message or the plaintext parameters
895 $this->filterDeprecated( '/OutputPage::setPageTitle with Message argument/' );
896 $op->setPageTitle( $msg );
897 $this->assertSame( "nope:<span></span> yes:<span>!</span>", $op->getPageTitle() );
898 }
899
900 public function testSetTitle() {
901 $op = $this->newInstance();
902
903 $this->assertSame( 'My test page', $op->getTitle()->getPrefixedText() );
904
905 $op->setTitle( Title::makeTitle( NS_MAIN, 'Another test page' ) );
906
907 $this->assertSame( 'Another test page', $op->getTitle()->getPrefixedText() );
908 }
909
910 public function testSubtitle() {
911 $op = $this->newInstance();
912
913 $this->assertSame( '', $op->getSubtitle() );
914
915 $op->addSubtitle( '<b>foo</b>' );
916
917 $this->assertSame( '<b>foo</b>', $op->getSubtitle() );
918
919 $op->addSubtitle( $op->msg( 'mainpage' )->inContentLanguage() );
920
921 $this->assertSame(
922 "<b>foo</b><br />\n\t\t\t\t" . $this->getMsgText( $op, 'mainpage' ),
923 $op->getSubtitle()
924 );
925
926 $op->setSubtitle( 'There can be only one' );
927
928 $this->assertSame( 'There can be only one', $op->getSubtitle() );
929
930 $op->clearSubtitle();
931
932 $this->assertSame( '', $op->getSubtitle() );
933 }
934
935 /**
936 * @dataProvider provideBacklinkSubtitle
937 */
938 public function testBuildBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
939 if ( count( $titles ) > 1 ) {
940 // Not applicable
941 $this->assertTrue( true );
942 return;
943 }
944
945 $title = $titles[0];
946 $query = $queries[0];
947
948 $str = OutputPage::buildBacklinkSubtitle( $title, $query )->text();
949
950 foreach ( $contains as $substr ) {
951 $this->assertStringContainsString( $substr, $str );
952 }
953
954 foreach ( $notContains as $substr ) {
955 $this->assertStringNotContainsString( $substr, $str );
956 }
957 }
958
959 /**
960 * @dataProvider provideBacklinkSubtitle
961 */
962 public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
963 $op = $this->newInstance();
964 foreach ( $titles as $i => $unused ) {
965 $op->addBacklinkSubtitle( $titles[$i], $queries[$i] );
966 }
967
968 $str = $op->getSubtitle();
969
970 foreach ( $contains as $substr ) {
971 $this->assertStringContainsString( $substr, $str );
972 }
973
974 foreach ( $notContains as $substr ) {
975 $this->assertStringNotContainsString( $substr, $str );
976 }
977 }
978
979 public function provideBacklinkSubtitle() {
980 $page1title = $this->makeMockTitle( 'Page 1', [ 'redirect' => true ] );
981 $page1ref = new PageReferenceValue( NS_MAIN, 'Page 1', PageReference::LOCAL );
982
983 $row = [
984 'page_id' => 28,
985 'page_namespace' => NS_MAIN,
986 'page_title' => 'Page 2',
987 'page_latest' => 75,
988 'page_is_redirect' => true,
989 'page_is_new' => true,
990 'page_touched' => '20200101221133',
991 'page_lang' => 'en',
992 ];
993 $page2rec = new PageStoreRecord( (object)$row, PageReference::LOCAL );
994
995 $special = new PageReferenceValue( NS_SPECIAL, 'BlankPage', PageReference::LOCAL );
996
997 return [
998 [
999 [ $page1title ],
1000 [ [] ],
1001 [ 'Page 1' ],
1002 [ 'redirect', 'Page 2' ],
1003 ],
1004 [
1005 [ $page2rec ],
1006 [ [] ],
1007 [ 'redirect=no' ],
1008 [ 'Page 1' ],
1009 ],
1010 [
1011 [ $special ],
1012 [ [] ],
1013 [ 'Special:BlankPage' ],
1014 [ 'redirect=no' ],
1015 ],
1016 [
1017 [ $page1ref ],
1018 [ [ 'action' => 'edit' ] ],
1019 [ 'action=edit' ],
1020 [],
1021 ],
1022 [
1023 [ $page1ref, $page2rec ],
1024 [ [], [] ],
1025 [ 'Page 1', 'Page 2', "<br />\n\t\t\t\t" ],
1026 [],
1027 ],
1028 // @todo Anything else to test?
1029 ];
1030 }
1031
1032 public function testPrintable() {
1033 $op = $this->newInstance();
1034
1035 $this->assertFalse( $op->isPrintable() );
1036
1037 $op->setPrintable();
1038
1039 $this->assertTrue( $op->isPrintable() );
1040 }
1041
1042 public function testDisable() {
1043 $op = $this->newInstance();
1044
1045 $this->assertFalse( $op->isDisabled() );
1046 $this->assertNotSame( '', $op->output( true ) );
1047
1048 $op->disable();
1049
1050 $this->assertTrue( $op->isDisabled() );
1051 $this->assertSame( '', $op->output( true ) );
1052 }
1053
1054 public function testShowNewSectionLink() {
1055 $op = $this->newInstance();
1056
1057 $this->assertFalse( $op->showNewSectionLink() );
1058 $this->assertFalse( $op->getOutputFlag( ParserOutputFlags::NEW_SECTION ) );
1059
1060 $pOut1 = $this->createParserOutputStubWithFlags(
1061 [ 'getNewSection' => true ], [ ParserOutputFlags::NEW_SECTION ]
1062 );
1063 $op->addParserOutputMetadata( $pOut1 );
1064 $this->assertTrue( $op->showNewSectionLink() );
1065 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NEW_SECTION ) );
1066
1067 $pOut2 = $this->createParserOutputStub( 'getNewSection', false );
1068 $op->addParserOutput( $pOut2 );
1069 $this->assertFalse( $op->showNewSectionLink() );
1070 // Note that flags are OR'ed together, and not reset.
1071 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NEW_SECTION ) );
1072 }
1073
1074 public function testForceHideNewSectionLink() {
1075 $op = $this->newInstance();
1076
1077 $this->assertFalse( $op->forceHideNewSectionLink() );
1078 $this->assertFalse( $op->getOutputFlag( ParserOutputFlags::HIDE_NEW_SECTION ) );
1079
1080 $pOut1 = $this->createParserOutputStubWithFlags(
1081 [ 'getHideNewSection' => true ], [ ParserOutputFlags::HIDE_NEW_SECTION ]
1082 );
1083 $op->addParserOutputMetadata( $pOut1 );
1084 $this->assertTrue( $op->forceHideNewSectionLink() );
1085 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::HIDE_NEW_SECTION ) );
1086
1087 $pOut2 = $this->createParserOutputStub( 'getHideNewSection', false );
1088 $op->addParserOutput( $pOut2 );
1089 $this->assertFalse( $op->forceHideNewSectionLink() );
1090 // Note that flags are OR'ed together, and not reset.
1091 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::HIDE_NEW_SECTION ) );
1092 }
1093
1094 public function testSetSyndicated() {
1095 $op = $this->newInstance( [ MainConfigNames::Feed => true ] );
1096 $this->assertFalse( $op->isSyndicated() );
1097
1098 $op->setSyndicated();
1099 $this->assertTrue( $op->isSyndicated() );
1100
1101 $op->setSyndicated( false );
1102 $this->assertFalse( $op->isSyndicated() );
1103
1104 $op = $this->newInstance(); // Feed => false by default
1105 $this->assertFalse( $op->isSyndicated() );
1106
1107 $op->setSyndicated();
1108 $this->assertFalse( $op->isSyndicated() );
1109 }
1110
1111 public function testFeedLinks() {
1112 $op = $this->newInstance( [ MainConfigNames::Feed => true ] );
1113 $this->assertSame( [], $op->getSyndicationLinks() );
1114
1115 $op->addFeedLink( 'not a supported format', 'abc' );
1116 $this->assertFalse( $op->isSyndicated() );
1117 $this->assertSame( [], $op->getSyndicationLinks() );
1118
1119 $feedTypes = $op->getConfig()->get( MainConfigNames::AdvertisedFeedTypes );
1120
1121 $op->addFeedLink( $feedTypes[0], 'def' );
1122 $this->assertTrue( $op->isSyndicated() );
1123 $this->assertSame( [ $feedTypes[0] => 'def' ], $op->getSyndicationLinks() );
1124
1125 $op->setFeedAppendQuery( false );
1126 $expected = [];
1127 foreach ( $feedTypes as $type ) {
1128 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type" );
1129 }
1130 $this->assertSame( $expected, $op->getSyndicationLinks() );
1131
1132 $op->setFeedAppendQuery( 'apples=oranges' );
1133 foreach ( $feedTypes as $type ) {
1134 $expected[$type] = $op->getTitle()->getLocalURL( "feed=$type&apples=oranges" );
1135 }
1136 $this->assertSame( $expected, $op->getSyndicationLinks() );
1137
1138 $op = $this->newInstance(); // Feed => false by default
1139 $this->assertSame( [], $op->getSyndicationLinks() );
1140
1141 $op->addFeedLink( $feedTypes[0], 'def' );
1142 $this->assertFalse( $op->isSyndicated() );
1143 $this->assertSame( [], $op->getSyndicationLinks() );
1144 }
1145
1146 public function testArticleFlags() {
1147 $op = $this->newInstance();
1148 $this->assertFalse( $op->isArticle() );
1149 $this->assertTrue( $op->isArticleRelated() );
1150
1151 $op->setArticleRelated( false );
1152 $this->assertFalse( $op->isArticle() );
1153 $this->assertFalse( $op->isArticleRelated() );
1154
1155 $op->setArticleFlag( true );
1156 $this->assertTrue( $op->isArticle() );
1157 $this->assertTrue( $op->isArticleRelated() );
1158
1159 $op->setArticleFlag( false );
1160 $this->assertFalse( $op->isArticle() );
1161 $this->assertTrue( $op->isArticleRelated() );
1162
1163 $op->setArticleFlag( true );
1164 $op->setArticleRelated( false );
1165 $this->assertFalse( $op->isArticle() );
1166 $this->assertFalse( $op->isArticleRelated() );
1167 }
1168
1169 public function testLanguageLinks() {
1170 $op = $this->newInstance();
1171 $this->assertSame( [], $op->getLanguageLinks() );
1172
1173 $op->addLanguageLinks( [ 'fr:A#x', 'it:B' ] );
1174 $this->assertSame( [ 'fr:A#x', 'it:B' ], $op->getLanguageLinks() );
1175
1176 $op->addLanguageLinks( [
1177 TitleValue::tryNew( NS_MAIN, 'C', '', 'de' ),
1178 TitleValue::tryNew( NS_MAIN, 'D', '', 'es' ),
1179 ] );
1180 $this->assertSame( [ 'fr:A#x', 'it:B', 'de:C', 'es:D' ], $op->getLanguageLinks() );
1181
1182 $op->setLanguageLinks( [ TitleValue::tryNew( NS_MAIN, 'E', '', 'pt' ) ] );
1183 $this->assertSame( [ 'pt:E' ], $op->getLanguageLinks() );
1184
1185 $pOut1 = $this->createParserOutputStub( 'getLanguageLinks', [ 'he:F', 'ar:G#y' ] );
1186 $op->addParserOutputMetadata( $pOut1 );
1187 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G#y' ], $op->getLanguageLinks() );
1188
1189 # Duplicates are removed in OutputPage (T26502)
1190 $pOut2 = $this->createParserOutputStub( 'getLanguageLinks', [ 'pt:H' ] );
1191 $op->addParserOutput( $pOut2 );
1192 $this->assertSame( [ 'pt:E', 'he:F', 'ar:G#y' ], $op->getLanguageLinks() );
1193 }
1194
1195 // @todo Are these category links tests too abstract and complicated for what they test? Would
1196 // it make sense to just write out all the tests by hand with maybe some copy-and-paste?
1197
1198 /**
1199 * @dataProvider provideGetCategories
1200 *
1201 *
1202 * @param array $args Array of form [ category name => sort key ]
1203 * @param array $fakeResults Array of form [ category name => value to return from mocked
1204 * LinkBatch ]
1205 * @param callable|null $variantLinkCallback Callback to replace findVariantLink() call
1206 * @param array $expectedNormal Expected return value of getCategoryLinks['normal']
1207 * @param array $expectedHidden Expected return value of getCategoryLinks['hidden']
1208 */
1209 public function testAddCategoryLinks(
1210 array $args, array $fakeResults, ?callable $variantLinkCallback,
1211 array $expectedNormal, array $expectedHidden
1212 ) {
1213 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
1214 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
1215
1216 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1217
1218 $op->addCategoryLinks( $args );
1219
1220 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1221 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1222 }
1223
1224 /**
1225 * @dataProvider provideGetCategories
1226 */
1227 public function testAddCategoryLinksOneByOne(
1228 array $args, array $fakeResults, ?callable $variantLinkCallback,
1229 array $expectedNormal, array $expectedHidden
1230 ) {
1231 if ( count( $args ) <= 1 ) {
1232 // @todo Should this be skipped instead of passed?
1233 $this->assertTrue( true );
1234 return;
1235 }
1236
1237 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'onebyone' );
1238 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'onebyone' );
1239
1240 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1241
1242 foreach ( $args as $key => $val ) {
1243 $op->addCategoryLinks( [ $key => $val ] );
1244 }
1245
1246 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1247 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1248 }
1249
1250 /**
1251 * @dataProvider provideGetCategories
1252 */
1253 public function testSetCategoryLinks(
1254 array $args, array $fakeResults, ?callable $variantLinkCallback,
1255 array $expectedNormal, array $expectedHidden
1256 ) {
1257 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'set' );
1258 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'set' );
1259
1260 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1261
1262 $this->filterDeprecated( '/OutputPage::setCategoryLinks was deprecated/' );
1263 $op->setCategoryLinks( [ 'Initial page' => 'Initial page' ] );
1264 $op->setCategoryLinks( $args );
1265
1266 // We don't reset the categories, for some reason, only the links
1267 $expectedNormalCats = array_merge( [ 'Initial page' ], $expectedNormal );
1268
1269 $this->doCategoryAsserts( $op, $expectedNormalCats, $expectedHidden );
1270 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1271 }
1272
1273 /**
1274 * @dataProvider provideGetCategories
1275 */
1276 public function testParserOutputCategoryLinks(
1277 array $args, array $fakeResults, ?callable $variantLinkCallback,
1278 array $expectedNormal, array $expectedHidden
1279 ) {
1280 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'pout' );
1281 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'pout' );
1282
1283 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1284
1285 $stubPO = $this->createParserOutputStub( [
1286 'getCategoryMap' => $args,
1287 ] );
1288
1289 // addParserOutput and addParserOutputMetadata should behave identically for us, so
1290 // alternate to get coverage for both without adding extra tests
1291 static $idx = 0;
1292 $idx++;
1293 $method = [ 'addParserOutputMetadata', 'addParserOutput' ][$idx % 2];
1294 $op->$method( $stubPO );
1295
1296 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1297 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1298 }
1299
1300 /**
1301 * @dataProvider provideGetCategories
1302 */
1303 public function testOutputPageRenderCategoryLinkHook(
1304 array $args, array $fakeResults, ?callable $variantLinkCallback,
1305 array $expectedNormal, array $expectedHidden, array $expectedText
1306 ) {
1307 $expectedNormal = $this->extractExpectedCategories( $expectedNormal, 'add' );
1308 $expectedHidden = $this->extractExpectedCategories( $expectedHidden, 'add' );
1309
1310 $op = $this->setupCategoryTests( $fakeResults, $variantLinkCallback );
1311
1312 $tf = $this->getServiceContainer()->getTitleFormatter();
1313 $this->setTemporaryHook( 'OutputPageRenderCategoryLink',
1314 static function ( $outputPage, $categoryTitle, $text, &$link ) use ( $tf ) {
1315 $link = 'Custom link: ' . $tf->getPrefixedText( $categoryTitle ) . ", text: ($text)";
1316 }
1317 );
1318 $op->addCategoryLinks( $args );
1319
1320 $this->doCategoryAsserts( $op, $expectedNormal, $expectedHidden );
1321 $this->doCategoryLinkAsserts( $op, $expectedNormal, $expectedHidden );
1322 $i = 0;
1323 foreach ( $op->getCategoryLinks() as $type => $actual ) {
1324 foreach ( $actual as $link ) {
1325 $text = $expectedText[$i++];
1326 $this->assertStringContainsString( 'Custom link: Category:', $link );
1327 $this->assertStringContainsString( ", text: ($text)", $link );
1328 }
1329 }
1330 $this->assertCount( $i, $expectedText );
1331 }
1332
1333 /**
1334 * We allow different expectations for different tests as an associative array, like
1335 * [ 'set' => [ ... ], 'default' => [ ... ] ] if setCategoryLinks() will give a different
1336 * result.
1337 * @param array $expected
1338 * @param string $key
1339 * @return array
1340 */
1341 private function extractExpectedCategories( array $expected, $key ) {
1342 if ( !$expected || isset( $expected[0] ) ) {
1343 return $expected;
1344 }
1345 return $expected[$key] ?? $expected['default'];
1346 }
1347
1348 private function setupCategoryTests(
1349 array $fakeResults, ?callable $variantLinkCallback = null
1350 ): OutputPage {
1351 $this->overrideConfigValue( MainConfigNames::UsePigLatinVariant, true );
1352
1353 if ( $variantLinkCallback ) {
1354 $mockLanguageConverter = $this
1355 ->createMock( ILanguageConverter::class );
1356 $mockLanguageConverter
1357 ->method( 'findVariantLink' )
1358 ->willReturnCallback( $variantLinkCallback );
1359 $mockLanguageConverter
1360 ->method( 'convertHtml' )
1361 ->willReturnCallback( 'strrev' );
1362
1363 $languageConverterFactory = $this
1364 ->createMock( LanguageConverterFactory::class );
1365 $languageConverterFactory
1366 ->method( 'getLanguageConverter' )
1367 ->willReturn( $mockLanguageConverter );
1368 $this->setService(
1369 'LanguageConverterFactory',
1370 $languageConverterFactory
1371 );
1372 }
1373
1374 $op = $this->getMockBuilder( OutputPage::class )
1375 ->setConstructorArgs( [ new RequestContext() ] )
1376 ->onlyMethods( [ 'addCategoryLinksToLBAndGetResult', 'getTitle' ] )
1377 ->getMock();
1378
1379 $title = Title::makeTitle( NS_MAIN, 'My test page' );
1380 $op->method( 'getTitle' )
1381 ->willReturn( $title );
1382
1383 $op->method( 'addCategoryLinksToLBAndGetResult' )
1384 ->willReturnCallback( static function ( array $categories ) use ( $fakeResults ) {
1385 $return = [];
1386 foreach ( $categories as $category => $unused ) {
1387 if ( isset( $fakeResults[$category] ) ) {
1388 $return[] = $fakeResults[$category];
1389 }
1390 }
1391 return new FakeResultWrapper( $return );
1392 } );
1393
1394 $this->assertSame( [], $op->getCategories() );
1395
1396 return $op;
1397 }
1398
1399 private function doCategoryAsserts( OutputPage $op, $expectedNormal, $expectedHidden ) {
1400 $this->assertSame( array_merge( $expectedHidden, $expectedNormal ), $op->getCategories() );
1401 $this->assertSame( $expectedNormal, $op->getCategories( 'normal' ) );
1402 $this->assertSame( $expectedHidden, $op->getCategories( 'hidden' ) );
1403 }
1404
1405 private function doCategoryLinkAsserts( OutputPage $op, $expectedNormal, $expectedHidden ) {
1406 $catLinks = $op->getCategoryLinks();
1407 $this->assertCount( (bool)$expectedNormal + (bool)$expectedHidden, $catLinks );
1408 if ( $expectedNormal ) {
1409 $this->assertSameSize( $expectedNormal, $catLinks['normal'] );
1410 }
1411 if ( $expectedHidden ) {
1412 $this->assertSameSize( $expectedHidden, $catLinks['hidden'] );
1413 }
1414
1415 foreach ( $expectedNormal as $i => $name ) {
1416 $this->assertStringContainsString( $name, $catLinks['normal'][$i] );
1417 }
1418 foreach ( $expectedHidden as $i => $name ) {
1419 $this->assertStringContainsString( $name, $catLinks['hidden'][$i] );
1420 }
1421 }
1422
1423 public static function provideGetCategories() {
1424 return [
1425 'No categories' => [ [], [], null, [], [], [] ],
1426 'Simple test' => [
1427 [ 'Test1' => 'Some sortkey', 'Test2' => 'A different sortkey' ],
1428 [ 'Test1' => (object)[ 'pp_value' => 1, 'page_title' => 'Test1' ],
1429 'Test2' => (object)[ 'page_title' => 'Test2' ] ],
1430 null,
1431 [ 'Test2' ],
1432 [ 'Test1' ],
1433 [ 'Test1', 'Test2' ],
1434 ],
1435 'Invalid title' => [
1436 [ '[' => '[', 'Test' => 'Test' ],
1437 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1438 null,
1439 [ 'Test' ],
1440 [],
1441 [ 'Test' ],
1442 ],
1443 'Variant link' => [
1444 [ 'Test' => 'Test', 'Estay' => 'Estay' ],
1445 [ 'Test' => (object)[ 'page_title' => 'Test' ] ],
1446 static function ( &$link, &$title ) {
1447 if ( $link === 'Estay' ) {
1448 $link = 'Test';
1449 $title = Title::makeTitleSafe( NS_CATEGORY, $link );
1450 }
1451 },
1452 // For adding one by one, the variant gets added as well as the original category,
1453 // but if you add them all together the second time gets skipped.
1454 [ 'onebyone' => [ 'Test', 'Test' ], 'default' => [ 'Test' ] ],
1455 [],
1456 [ 'tseT' ],
1457 ],
1458 ];
1459 }
1460
1461 public function testGetCategoriesInvalid() {
1462 $this->expectException( InvalidArgumentException::class );
1463 $this->expectExceptionMessage( 'Invalid category type given: hiddne' );
1464
1465 $op = $this->newInstance();
1466 $op->getCategories( 'hiddne' );
1467 }
1468
1469 // @todo Should we test addCategoryLinksToLBAndGetResult? If so, how? Insert some test rows in
1470 // the DB?
1471
1472 public function testIndicators() {
1473 $op = $this->newInstance();
1474 $this->assertSame( [], $op->getIndicators() );
1475
1476 $op->setIndicators( [] );
1477 $this->assertSame( [], $op->getIndicators() );
1478
1479 // Test sorting alphabetically
1480 $op->setIndicators( [ 'b' => 'x', 'a' => 'y' ] );
1481 $this->assertSame( [ 'a' => 'y', 'b' => 'x' ], $op->getIndicators() );
1482
1483 // Test overwriting existing keys
1484 $op->setIndicators( [ 'c' => 'z', 'a' => 'w' ] );
1485 $this->assertSame( [ 'a' => 'w', 'b' => 'x', 'c' => 'z' ], $op->getIndicators() );
1486
1487 // Test with addParserOutputMetadata
1488 // Note that the indicators are wrapped.
1489 $pOut1 = $this->createParserOutputStub( [
1490 'getIndicators' => [ 'c' => 'u', 'd' => 'v' ],
1491 'getWrapperDivClass' => 'wrapper1',
1492 ] );
1493 $op->addParserOutputMetadata( $pOut1 );
1494 $this->assertSame( [
1495 'a' => 'w',
1496 'b' => 'x',
1497 'c' => '<div class="wrapper1">u</div>',
1498 'd' => '<div class="wrapper1">v</div>',
1499 ], $op->getIndicators() );
1500
1501 // Test with addParserOutput
1502 $pOut2 = $this->createParserOutputStub( [
1503 'getIndicators' => [ 'a' => '!!!' ],
1504 'getWrapperDivClass' => 'wrapper2',
1505 ] );
1506 $op->addParserOutput( $pOut2 );
1507 $this->assertSame( [
1508 'a' => '<div class="wrapper2">!!!</div>',
1509 'b' => 'x',
1510 'c' => '<div class="wrapper1">u</div>',
1511 'd' => '<div class="wrapper1">v</div>',
1512 ], $op->getIndicators() );
1513 }
1514
1515 public function testAddHelpLink() {
1516 $op = $this->newInstance();
1517
1518 $op->addHelpLink( 'Manual:PHP unit testing' );
1519 $indicators = $op->getIndicators();
1520 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1521 $this->assertStringContainsString( 'Manual:PHP_unit_testing', $indicators['mw-helplink'] );
1522
1523 $op->addHelpLink( 'https://phpunit.de', true );
1524 $indicators = $op->getIndicators();
1525 $this->assertSame( [ 'mw-helplink' ], array_keys( $indicators ) );
1526 $this->assertStringContainsString( 'https://phpunit.de', $indicators['mw-helplink'] );
1527 $this->assertStringNotContainsString( 'mediawiki', $indicators['mw-helplink'] );
1528 $this->assertStringNotContainsString( 'Manual:PHP', $indicators['mw-helplink'] );
1529 }
1530
1531 public function testBodyHTML() {
1532 $op = $this->newInstance();
1533 $this->assertSame( '', $op->getHTML() );
1534
1535 $op->addHTML( 'a' );
1536 $this->assertSame( 'a', $op->getHTML() );
1537
1538 $op->addHTML( 'b' );
1539 $this->assertSame( 'ab', $op->getHTML() );
1540
1541 $op->prependHTML( 'c' );
1542 $this->assertSame( 'cab', $op->getHTML() );
1543
1544 $op->addElement( 'p', [ 'id' => 'foo' ], 'd' );
1545 $this->assertSame( 'cab<p id="foo">d</p>', $op->getHTML() );
1546
1547 $op->clearHTML();
1548 $this->assertSame( '', $op->getHTML() );
1549 }
1550
1551 /**
1552 * @dataProvider provideRevisionId
1553 */
1554 public function testRevisionId( $newVal, $expected ) {
1555 $op = $this->newInstance();
1556
1557 $this->assertNull( $op->setRevisionId( $newVal ) );
1558 $this->assertSame( $expected, $op->getRevisionId() );
1559 $this->assertSame( $expected, $op->setRevisionId( null ) );
1560 $this->assertNull( $op->getRevisionId() );
1561 }
1562
1563 public static function provideRevisionId() {
1564 return [
1565 [ null, null ],
1566 [ 7, 7 ],
1567 [ -1, -1 ],
1568 [ 3.2, 3 ],
1569 [ '0', 0 ],
1570 [ '32% finished', 32 ],
1571 [ false, 0 ],
1572 ];
1573 }
1574
1575 public function testRevisionTimestamp() {
1576 $op = $this->newInstance();
1577 $this->assertNull( $op->getRevisionTimestamp() );
1578
1579 $this->assertNull( $op->setRevisionTimestamp( 'abc' ) );
1580 $this->assertSame( 'abc', $op->getRevisionTimestamp() );
1581 $this->assertSame( 'abc', $op->setRevisionTimestamp( null ) );
1582 $this->assertNull( $op->getRevisionTimestamp() );
1583 }
1584
1585 public function testFileVersion() {
1586 $op = $this->newInstance();
1587 $this->assertNull( $op->getFileVersion() );
1588
1589 $stubFile = $this->createMock( File::class );
1590 $stubFile->method( 'exists' )->willReturn( true );
1591 $stubFile->method( 'getTimestamp' )->willReturn( '12211221123321' );
1592 $stubFile->method( 'getSha1' )->willReturn( 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' );
1593
1594 /** @var File $stubFile */
1595 $op->setFileVersion( $stubFile );
1596
1597 $this->assertEquals(
1598 [ 'time' => '12211221123321', 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05' ],
1599 $op->getFileVersion()
1600 );
1601
1602 $stubMissingFile = $this->createMock( File::class );
1603 $stubMissingFile->method( 'exists' )->willReturn( false );
1604
1605 /** @var File $stubMissingFile */
1606 $op->setFileVersion( $stubMissingFile );
1607 $this->assertNull( $op->getFileVersion() );
1608
1609 $op->setFileVersion( $stubFile );
1610 $this->assertNotNull( $op->getFileVersion() );
1611
1612 $op->setFileVersion( null );
1613 $this->assertNull( $op->getFileVersion() );
1614 }
1615
1616 /**
1617 * Call either with arguments $methodName, $returnValue; or an array
1618 * [ $methodName => $returnValue, $methodName => $returnValue, ... ]
1619 * @param mixed ...$args
1620 * @return ParserOutput
1621 */
1622 private function createParserOutputStub( ...$args ): ParserOutput {
1623 if ( count( $args ) === 0 ) {
1624 $retVals = [];
1625 } elseif ( count( $args ) === 1 ) {
1626 $retVals = $args[0];
1627 } elseif ( count( $args ) === 2 ) {
1628 $retVals = [ $args[0] => $args[1] ];
1629 }
1630 return $this->createParserOutputStubWithFlags( $retVals, [] );
1631 }
1632
1633 /**
1634 * First argument is an array
1635 * [ $methodName => $returnValue, $methodName => $returnValue, ... ]
1636 * Second argument is an array of parser flags for which ::getOutputFlag()
1637 * should return 'TRUE'.
1638 * @param array $retVals
1639 * @param array $flags
1640 * @return ParserOutput
1641 */
1642 private function createParserOutputStubWithFlags( array $retVals, array $flags ): ParserOutput {
1643 $pOut = $this->createMock( ParserOutput::class );
1644
1645 $mockedRunOutputPipeline = false;
1646 foreach ( $retVals as $method => $retVal ) {
1647 $pOut->method( $method )->willReturn( $retVal );
1648 if ( $method === 'runOutputPipeline' ) {
1649 $mockedRunOutputPipeline = true;
1650 }
1651 }
1652
1653 // Needed to ensure OutputPage::getParserOutputText doesn't return null
1654 if ( !$mockedRunOutputPipeline ) {
1655 $pOut->method( 'runOutputPipeline' )->willReturn( new ParserOutput( '' ) );
1656 }
1657
1658 $arrayReturningMethods = [
1659 'getCategoryNames',
1660 'getCategoryMap',
1661 'getFileSearchOptions',
1662 'getHeadItems',
1663 'getImages',
1664 'getIndicators',
1665 'getSections',
1666 'getModules',
1667 'getModuleStyles',
1668 'getJsConfigVars',
1669 'getLanguageLinks',
1670 'getLinkList',
1671 'getTemplateIds',
1672 'getExtraCSPDefaultSrcs',
1673 'getExtraCSPStyleSrcs',
1674 'getExtraCSPScriptSrcs',
1675 'getLimitReportJSData',
1676 'getAllFlags',
1677 ];
1678
1679 foreach ( $arrayReturningMethods as $method ) {
1680 $pOut->method( $method )->willReturn( [] );
1681 }
1682
1683 $pOut->method( 'getOutputFlag' )->willReturnCallback( static function ( $name ) use ( $flags ) {
1684 return in_array( $name, $flags, true );
1685 } );
1686
1687 return $pOut;
1688 }
1689
1690 public function testTemplateIds() {
1691 $op = $this->newInstance();
1692 $this->assertSame( [], $op->getTemplateIds() );
1693
1694 // Test with no template id's
1695 $stubPOEmpty = $this->createParserOutputStub();
1696 $op->addParserOutputMetadata( $stubPOEmpty );
1697 $this->assertSame( [], $op->getTemplateIds() );
1698
1699 // Test with some arbitrary template id's
1700 $ids = [
1701 NS_MAIN => [ 'A' => 3, 'B' => 17 ],
1702 NS_TALK => [ 'C' => 31 ],
1703 NS_MEDIA => [ 'D' => -1 ],
1704 ];
1705
1706 $stubPO1 = $this->createParserOutputStub( 'getTemplateIds', $ids );
1707
1708 $op->addParserOutputMetadata( $stubPO1 );
1709 $this->assertSame( $ids, $op->getTemplateIds() );
1710
1711 // Test merging with a second set of id's
1712 $stubPO2 = $this->createParserOutputStub( 'getTemplateIds', [
1713 NS_MAIN => [ 'E' => 1234 ],
1714 NS_PROJECT => [ 'F' => 5678 ],
1715 ] );
1716
1717 $finalIds = [
1718 NS_MAIN => [ 'E' => 1234, 'A' => 3, 'B' => 17 ],
1719 NS_TALK => [ 'C' => 31 ],
1720 NS_MEDIA => [ 'D' => -1 ],
1721 NS_PROJECT => [ 'F' => 5678 ],
1722 ];
1723
1724 $op->addParserOutput( $stubPO2 );
1725 $this->assertSame( $finalIds, $op->getTemplateIds() );
1726
1727 // Test merging with an empty set of id's
1728 $op->addParserOutputMetadata( $stubPOEmpty );
1729 $this->assertSame( $finalIds, $op->getTemplateIds() );
1730 }
1731
1732 public function testFileSearchOptions() {
1733 $op = $this->newInstance();
1734 $this->assertSame( [], $op->getFileSearchOptions() );
1735
1736 // Test with no files
1737 $stubPOEmpty = $this->createParserOutputStub();
1738
1739 $op->addParserOutputMetadata( $stubPOEmpty );
1740 $this->assertSame( [], $op->getFileSearchOptions() );
1741
1742 // Test with some arbitrary files
1743 $files1 = [
1744 'A' => [ 'time' => null, 'sha1' => '' ],
1745 'B' => [
1746 'time' => '12211221123321',
1747 'sha1' => 'bf3ffa7047dc080f5855377a4f83cd18887e3b05',
1748 ],
1749 ];
1750
1751 $stubPO1 = $this->createParserOutputStub( 'getFileSearchOptions', $files1 );
1752
1753 $op->addParserOutput( $stubPO1 );
1754 $this->assertSame( $files1, $op->getFileSearchOptions() );
1755
1756 // Test merging with a second set of files
1757 $files2 = [
1758 'C' => [ 'time' => null, 'sha1' => '' ],
1759 'B' => [ 'time' => null, 'sha1' => '' ],
1760 ];
1761
1762 $stubPO2 = $this->createParserOutputStub( 'getFileSearchOptions', $files2 );
1763
1764 $op->addParserOutputMetadata( $stubPO2 );
1765 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1766
1767 // Test merging with an empty set of files
1768 $op->addParserOutput( $stubPOEmpty );
1769 $this->assertSame( array_merge( $files1, $files2 ), $op->getFileSearchOptions() );
1770 }
1771
1772 /**
1773 * @dataProvider provideAddWikiText
1774 */
1775 public function testAddWikiText( $method, array $args, $expected ) {
1776 $op = $this->newInstance();
1777 $this->assertSame( '', $op->getHTML() );
1778
1779 if ( in_array(
1780 $method,
1781 [ 'addWikiTextAsInterface', 'addWikiTextAsContent' ]
1782 ) && count( $args ) >= 3 && $args[2] === null ) {
1783 // Special placeholder because we can't get the actual title in the provider
1784 $args[2] = $op->getTitle();
1785 }
1786
1787 $op->$method( ...$args );
1788 $this->assertSame( $expected, $op->getHTML() );
1789 }
1790
1791 public static function provideAddWikiText() {
1792 $somePageRef = new PageReferenceValue( NS_TALK, 'Some page', PageReference::LOCAL );
1793
1794 $tests = [
1795 'addWikiTextAsInterface' => [
1796 'Simple wikitext' => [
1797 [ "'''Bold'''" ],
1798 "<p><b>Bold</b>\n</p>",
1799 ], 'Untidy wikitext' => [
1800 [ "<b>Bold" ],
1801 "<p><b>Bold\n</b></p>",
1802 ], 'List at start' => [
1803 [ '* List' ],
1804 "<ul><li>List</li></ul>\n",
1805 ], 'List not at start' => [
1806 [ '* Not a list', false ],
1807 '<p>* Not a list</p>',
1808 ], 'No section edit links' => [
1809 [ '== Title ==' ],
1810 '<div class="mw-heading mw-heading2"><h2 id="Title">Title</h2></div>',
1811 ], 'With title at start' => [
1812 [ '* {{PAGENAME}}', true, Title::makeTitle( NS_TALK, 'Some page' ) ],
1813 "<ul><li>Some page</li></ul>\n",
1814 ], 'With title not at start' => [
1815 [ '* {{PAGENAME}}', false, Title::makeTitle( NS_TALK, 'Some page' ) ],
1816 "<p>* Some page</p>",
1817 ], 'Untidy input' => [
1818 [ '<b>{{PAGENAME}}', true, $somePageRef ],
1819 "<p><b>Some page\n</b></p>",
1820 ],
1821 ],
1822 'addWikiTextAsContent' => [
1823 'SpecialNewimages' => [
1824 [ "<p lang='en' dir='ltr'>\nMy message" ],
1825 '<p lang="en" dir="ltr">' . "\nMy message</p>"
1826 ], 'List at start' => [
1827 [ '* List' ],
1828 "<ul><li>List</li></ul>",
1829 ], 'List not at start' => [
1830 [ '* <b>Not a list', false ],
1831 '<p>* <b>Not a list</b></p>',
1832 ], 'With title at start' => [
1833 [ '* {{PAGENAME}}', true, Title::makeTitle( NS_TALK, 'Some page' ) ],
1834 "<ul><li>Some page</li></ul>",
1835 ], 'With title not at start' => [
1836 [ '* {{PAGENAME}}', false, Title::makeTitle( NS_TALK, 'Some page' ) ],
1837 "<p>* Some page</p>",
1838 ], 'EditPage' => [
1839 [ "<div class='mw-editintro'>{{PAGENAME}}", true, $somePageRef ],
1840 '<div class="mw-editintro">' . "Some page</div>"
1841 ],
1842 ],
1843 'wrapWikiTextAsInterface' => [
1844 'Simple' => [
1845 [ 'wrapperClass', 'text' ],
1846 "<div class=\"mw-content-ltr wrapperClass\" lang=\"en\" dir=\"ltr\"><p>text\n</p></div>"
1847 ], 'Spurious </div>' => [
1848 [ 'wrapperClass', 'text</div><div>more' ],
1849 "<div class=\"mw-content-ltr wrapperClass\" lang=\"en\" dir=\"ltr\"><p>text</p><div>more</div></div>"
1850 ], 'Extra newlines would break <p> wrappers' => [
1851 [ 'two classes', "1\n\n2\n\n3" ],
1852 "<div class=\"mw-content-ltr two classes\" lang=\"en\" dir=\"ltr\"><p>1\n</p><p>2\n</p><p>3\n</p></div>"
1853 ], 'Other unclosed tags' => [
1854 [ 'error', 'a<b>c<i>d' ],
1855 "<div class=\"mw-content-ltr error\" lang=\"en\" dir=\"ltr\"><p>a<b>c<i>d\n</i></b></p></div>"
1856 ],
1857 ],
1858 ];
1859
1860 // We have to reformat our array to match what PHPUnit wants
1861 $ret = [];
1862 foreach ( $tests as $key => $subarray ) {
1863 foreach ( $subarray as $subkey => $val ) {
1864 $val = array_merge( [ $key ], $val );
1865 $ret[$subkey] = $val;
1866 }
1867 }
1868
1869 return $ret;
1870 }
1871
1872 public function testAddWikiTextAsInterfaceNoTitle() {
1873 $this->expectException( RuntimeException::class );
1874 $this->expectExceptionMessage( 'No title' );
1875
1876 $op = $this->newInstance( [], null, 'notitle' );
1877 $op->addWikiTextAsInterface( 'a' );
1878 }
1879
1880 public function testAddWikiTextAsContentNoTitle() {
1881 $this->expectException( RuntimeException::class );
1882 $this->expectExceptionMessage( 'No title' );
1883
1884 $op = $this->newInstance( [], null, 'notitle' );
1885 $op->addWikiTextAsContent( 'a' );
1886 }
1887
1888 public function testAddWikiMsg() {
1889 $msg = wfMessage( 'parentheses' );
1890 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1891
1892 $op = $this->newInstance();
1893 $this->assertSame( '', $op->getHTML() );
1894 $op->addWikiMsg( 'parentheses', "<b>a" );
1895 // The input is bad unbalanced HTML, but the output is tidied
1896 $this->assertSame( "<p>(<b>a)\n</b></p>", $op->getHTML() );
1897 }
1898
1899 public function testWrapWikiMsg() {
1900 $msg = wfMessage( 'parentheses' );
1901 $this->assertSame( '(a)', $msg->rawParams( 'a' )->plain() );
1902
1903 $op = $this->newInstance();
1904 $this->assertSame( '', $op->getHTML() );
1905 $op->wrapWikiMsg( '[$1]', [ 'parentheses', "<b>a" ] );
1906 // The input is bad unbalanced HTML, but the output is tidied
1907 $this->assertSame( "<p>[(<b>a)]\n</b></p>", $op->getHTML() );
1908 }
1909
1910 public function testNoGallery() {
1911 $op = $this->newInstance();
1912 $this->assertFalse( $op->getNoGallery() );
1913 $this->assertFalse( $op->getOutputFlag( ParserOutputFlags::NO_GALLERY ) );
1914
1915 $stubPO1 = $this->createParserOutputStubWithFlags(
1916 [ 'getNoGallery' => true ], [ ParserOutputFlags::NO_GALLERY ]
1917 );
1918 $op->addParserOutputMetadata( $stubPO1 );
1919 $this->assertTrue( $op->getNoGallery() );
1920 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NO_GALLERY ) );
1921
1922 $stubPO2 = $this->createParserOutputStub( 'getNoGallery', false );
1923 $op->addParserOutput( $stubPO2 );
1924 $this->assertFalse( $op->getNoGallery() );
1925 // Note that flags are OR'ed together, and not reset.
1926 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NO_GALLERY ) );
1927 }
1928
1929 // @todo Make sure to test the following in addParserOutputMetadata() as well when we add tests
1930 // for them:
1931 // * addModules()
1932 // * addModuleStyles()
1933 // * addJsConfigVars()
1934 // * enableOOUI()
1935 // Otherwise those lines of addParserOutputMetadata() will be reported as covered, but we won't
1936 // be testing they actually work.
1937
1938 public function testAddParserOutputText() {
1939 $op = $this->newInstance();
1940 $this->assertSame( '', $op->getHTML() );
1941
1942 $text = '<some text>';
1943 $pOut = $this->createParserOutputStub( 'runOutputPipeline', new ParserOutput( $text ) );
1944
1945 $op->addParserOutputMetadata( $pOut );
1946 $this->assertSame( '', $op->getHTML() );
1947
1948 $op->addParserOutputText( $text );
1949 $this->assertSame( '<some text>', $op->getHTML() );
1950 }
1951
1952 public function testAddParserOutput() {
1953 $op = $this->newInstance();
1954 $this->assertSame( '', $op->getHTML() );
1955 $this->assertFalse( $op->showNewSectionLink() );
1956 $this->assertFalse( $op->getOutputFlag( ParserOutputFlags::NEW_SECTION ) );
1957
1958 $pOut = $this->createParserOutputStubWithFlags( [
1959 'getContentHolderText' => '<some text>',
1960 'getNewSection' => true,
1961 ], [
1962 ParserOutputFlags::NEW_SECTION,
1963 ] );
1964
1965 $op->addParserOutput( $pOut );
1966 $this->assertSame( '<some text>', $op->getHTML() );
1967 $this->assertTrue( $op->showNewSectionLink() );
1968 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NEW_SECTION ) );
1969 }
1970
1971 public function testAddTemplate() {
1972 $template = $this->createMock( QuickTemplate::class );
1973 $template->method( 'getHTML' )->willReturn( '<abc>&def;' );
1974
1975 $op = $this->newInstance();
1976 $op->addTemplate( $template );
1977
1978 $this->assertSame( '<abc>&def;', $op->getHTML() );
1979 }
1980
1981 /**
1982 * @dataProvider provideParseAs
1983 */
1984 public function testParseAsContent(
1985 array $args, $expectedHTML, $expectedHTMLInline = null
1986 ) {
1987 $op = $this->newInstance();
1988 $this->assertSame( $expectedHTML, $op->parseAsContent( ...$args ) );
1989 }
1990
1991 /**
1992 * @dataProvider provideParseAs
1993 */
1994 public function testParseAsInterface(
1995 array $args, $expectedHTML, $expectedHTMLInline = null
1996 ) {
1997 $op = $this->newInstance();
1998 $this->assertSame( $expectedHTML, $op->parseAsInterface( ...$args ) );
1999 }
2000
2001 /**
2002 * @dataProvider provideParseAs
2003 */
2004 public function testParseInlineAsInterface(
2005 array $args, $expectedHTML, $expectedHTMLInline = null
2006 ) {
2007 $op = $this->newInstance();
2008 $this->assertSame(
2009 $expectedHTMLInline ?? $expectedHTML,
2010 $op->parseInlineAsInterface( ...$args )
2011 );
2012 }
2013
2014 public static function provideParseAs() {
2015 return [
2016 'List at start of line' => [
2017 [ '* List', true ],
2018 "<ul><li>List</li></ul>",
2019 ],
2020 'List not at start' => [
2021 [ "* ''Not'' list", false ],
2022 '<p>* <i>Not</i> list</p>',
2023 '* <i>Not</i> list',
2024 ],
2025 'Italics' => [
2026 [ "''Italic''", true ],
2027 "<p><i>Italic</i>\n</p>",
2028 '<i>Italic</i>',
2029 ],
2030 'formatnum' => [
2031 [ '{{formatnum:123456.789}}', true ],
2032 "<p>123,456.789\n</p>",
2033 "123,456.789",
2034 ],
2035 'No section edit links' => [
2036 [ '== Header ==' ],
2037 '<div class="mw-heading mw-heading2"><h2 id="Header">Header</h2></div>',
2038 ]
2039 ];
2040 }
2041
2042 public function testParseAsContentNullTitle() {
2043 $this->expectException( RuntimeException::class );
2044 $this->expectExceptionMessage( 'No title' );
2045 $op = $this->newInstance( [], null, 'notitle' );
2046 $op->parseAsContent( '' );
2047 }
2048
2049 public function testParseAsInterfaceNullTitle() {
2050 $this->expectException( RuntimeException::class );
2051 $this->expectExceptionMessage( 'No title' );
2052 $op = $this->newInstance( [], null, 'notitle' );
2053 $op->parseAsInterface( '' );
2054 }
2055
2056 public function testParseInlineAsInterfaceNullTitle() {
2057 $this->expectException( RuntimeException::class );
2058 $this->expectExceptionMessage( 'No title' );
2059 $op = $this->newInstance( [], null, 'notitle' );
2060 $op->parseInlineAsInterface( '' );
2061 }
2062
2063 public function testCdnMaxage() {
2064 $op = $this->newInstance();
2065 $wrapper = TestingAccessWrapper::newFromObject( $op );
2066 $this->assertSame( 0, $wrapper->mCdnMaxage );
2067
2068 $op->setCdnMaxage( -1 );
2069 $this->assertSame( -1, $wrapper->mCdnMaxage );
2070
2071 $op->setCdnMaxage( 120 );
2072 $this->assertSame( 120, $wrapper->mCdnMaxage );
2073
2074 $op->setCdnMaxage( 60 );
2075 $this->assertSame( 60, $wrapper->mCdnMaxage );
2076
2077 $op->setCdnMaxage( 180 );
2078 $this->assertSame( 180, $wrapper->mCdnMaxage );
2079
2080 $op->lowerCdnMaxage( 240 );
2081 $this->assertSame( 180, $wrapper->mCdnMaxage );
2082
2083 $op->setCdnMaxage( 300 );
2084 $this->assertSame( 240, $wrapper->mCdnMaxage );
2085
2086 $op->lowerCdnMaxage( 120 );
2087 $this->assertSame( 120, $wrapper->mCdnMaxage );
2088
2089 $op->setCdnMaxage( 180 );
2090 $this->assertSame( 120, $wrapper->mCdnMaxage );
2091
2092 $op->setCdnMaxage( 60 );
2093 $this->assertSame( 60, $wrapper->mCdnMaxage );
2094
2095 $op->setCdnMaxage( 240 );
2096 $this->assertSame( 120, $wrapper->mCdnMaxage );
2097 }
2098
2099 /** @var int Faked time to set for tests that need it */
2100 private static $fakeTime;
2101
2102 /**
2103 * @dataProvider provideAdaptCdnTTL
2104 * @param array $args To pass to adaptCdnTTL()
2105 * @param int $expected Expected new value of mCdnMaxageLimit
2106 * @param array $options Associative array:
2107 * initialMaxage => Maxage to set before calling adaptCdnTTL() (default 86400)
2108 */
2109 public function testAdaptCdnTTL( array $args, $expected, array $options = [] ) {
2110 MWTimestamp::setFakeTime( self::$fakeTime );
2111
2112 $op = $this->newInstance();
2113 // Set a high maxage so that it will get reduced by adaptCdnTTL(). The default maxage
2114 // is 0, so adaptCdnTTL() won't mutate the object at all.
2115 $initial = $options['initialMaxage'] ?? 86400;
2116 $op->setCdnMaxage( $initial );
2117 $op->adaptCdnTTL( ...$args );
2118
2119 $wrapper = TestingAccessWrapper::newFromObject( $op );
2120
2121 // Special rules for false/null
2122 if ( $args[0] === null || $args[0] === false ) {
2123 $this->assertSame( $initial, $wrapper->mCdnMaxage, 'member value' );
2124 $op->setCdnMaxage( $expected + 1 );
2125 $this->assertSame( $expected + 1, $wrapper->mCdnMaxage, 'member value after new set' );
2126 return;
2127 }
2128
2129 $this->assertSame( $expected, $wrapper->mCdnMaxageLimit, 'limit value' );
2130
2131 if ( $initial >= $expected ) {
2132 $this->assertSame( $expected, $wrapper->mCdnMaxage, 'member value' );
2133 } else {
2134 $this->assertSame( $initial, $wrapper->mCdnMaxage, 'member value' );
2135 }
2136
2137 $op->setCdnMaxage( $expected + 1 );
2138 $this->assertSame( $expected, $wrapper->mCdnMaxage, 'member value after new set' );
2139 }
2140
2141 public static function provideAdaptCdnTTL() {
2142 global $wgCdnMaxAge;
2143 $now = time();
2144 self::$fakeTime = $now;
2145 return [
2146 'Five minutes ago' => [ [ $now - 300 ], 270 ],
2147 'Now' => [ [ +0 ], ExpirationAwareness::TTL_MINUTE ],
2148 'Five minutes from now' => [ [ $now + 300 ], ExpirationAwareness::TTL_MINUTE ],
2149 'Five minutes ago, initial maxage four minutes' =>
2150 [ [ $now - 300 ], 270, [ 'initialMaxage' => 240 ] ],
2151 'A very long time ago' => [ [ $now - 1000000000 ], $wgCdnMaxAge ],
2152 'Initial maxage zero' => [ [ $now - 300 ], 270, [ 'initialMaxage' => 0 ] ],
2153
2154 'false' => [ [ false ], ExpirationAwareness::TTL_MINUTE ],
2155 'null' => [ [ null ], ExpirationAwareness::TTL_MINUTE ],
2156 "'0'" => [ [ '0' ], ExpirationAwareness::TTL_MINUTE ],
2157 'Empty string' => [ [ '' ], ExpirationAwareness::TTL_MINUTE ],
2158 // @todo These give incorrect results due to timezones, how to test?
2159 //"'now'" => [ [ 'now' ], ExpirationAwareness::TTL_MINUTE ],
2160 //"'parse error'" => [ [ 'parse error' ], ExpirationAwareness::TTL_MINUTE ],
2161
2162 'Now, minTTL 0' => [ [ $now, 0 ], ExpirationAwareness::TTL_MINUTE ],
2163 'Now, minTTL 0.000001' => [ [ $now, 0.000001 ], 0 ],
2164 'A very long time ago, maxTTL even longer' =>
2165 [ [ $now - 1000000000, 0, 1000000001 ], 900000000 ],
2166 ];
2167 }
2168
2169 public function testClientCache() {
2170 $op = $this->newInstance();
2171 $op->considerCacheSettingsFinal();
2172
2173 // Test initial value
2174 $this->assertSame( true, $op->couldBePublicCached() );
2175
2176 // Test setting to false
2177 $op->disableClientCache();
2178 $this->assertSame( false, $op->couldBePublicCached() );
2179
2180 // Test setting to true
2181 $op->enableClientCache();
2182 $this->assertSame( true, $op->couldBePublicCached() );
2183
2184 // set back to false
2185 $op->disableClientCache();
2186
2187 // Test that a cacheable ParserOutput doesn't set to true
2188 $pOutCacheable = $this->createParserOutputStub( 'isCacheable', true );
2189 $op->addParserOutputMetadata( $pOutCacheable );
2190 $this->assertSame( false, $op->couldBePublicCached() );
2191
2192 // Reset to true
2193 $op = $this->newInstance();
2194 $op->considerCacheSettingsFinal();
2195 $this->assertSame( true, $op->couldBePublicCached() );
2196
2197 // Test that an uncacheable ParserOutput does set to false
2198 $pOutUncacheable = $this->createParserOutputStub( 'isCacheable', false );
2199 $op->addParserOutput( $pOutUncacheable );
2200 $this->assertSame( false, $op->couldBePublicCached() );
2201 }
2202
2203 public function testGetCacheVaryCookies() {
2204 global $wgCookiePrefix, $wgDBname;
2205 $op = $this->newInstance();
2206 $prefix = $wgCookiePrefix !== false ? $wgCookiePrefix : $wgDBname;
2207 $expectedCookies = [
2208 "{$prefix}Token",
2209 "{$prefix}LoggedOut",
2210 "{$prefix}_session",
2211 'forceHTTPS',
2212 'cookie1',
2213 'cookie2',
2214 ];
2215
2216 // We have to reset the cookies because getCacheVaryCookies may have already been called
2217 TestingAccessWrapper::newFromClass( OutputPage::class )->cacheVaryCookies = null;
2218
2219 $this->overrideConfigValue( MainConfigNames::CacheVaryCookies, [ 'cookie1' ] );
2220 $this->setTemporaryHook( 'GetCacheVaryCookies',
2221 function ( $innerOP, &$cookies ) use ( $op, $expectedCookies ) {
2222 $this->assertSame( $op, $innerOP );
2223 $cookies[] = 'cookie2';
2224 $this->assertSame( $expectedCookies, $cookies );
2225 }
2226 );
2227
2228 $this->assertSame( $expectedCookies, $op->getCacheVaryCookies() );
2229 }
2230
2231 public function testHaveCacheVaryCookies() {
2232 $request = new FauxRequest();
2233 $op = $this->newInstance( [], $request );
2234
2235 // No cookies are set.
2236 $this->assertFalse( $op->haveCacheVaryCookies() );
2237
2238 // 'Token' is present but empty, so it shouldn't count.
2239 $request->setCookie( 'Token', '' );
2240 $this->assertFalse( $op->haveCacheVaryCookies() );
2241
2242 // 'Token' present and nonempty.
2243 $request->setCookie( 'Token', '123' );
2244 $this->assertTrue( $op->haveCacheVaryCookies() );
2245 }
2246
2247 /**
2248 * @dataProvider provideVaryHeaders
2249 *
2250 *
2251 * @param array[] $calls For each array, call addVaryHeader() with those arguments
2252 * @param string[] $cookies Array of cookie names to vary on
2253 * @param string $vary Text of expected Vary header (including the 'Vary: ')
2254 */
2255 public function testVaryHeaders( array $calls, array $cookies, $vary ) {
2256 // Get rid of default Vary fields
2257 $op = $this->getMockBuilder( OutputPage::class )
2258 ->setConstructorArgs( [ new RequestContext() ] )
2259 ->onlyMethods( [ 'getCacheVaryCookies' ] )
2260 ->getMock();
2261 $op->method( 'getCacheVaryCookies' )
2262 ->willReturn( $cookies );
2263 TestingAccessWrapper::newFromObject( $op )->mVaryHeader = [];
2264
2265 foreach ( $calls as $call ) {
2266 $op->addVaryHeader( ...$call );
2267 }
2268 $this->assertEquals( $vary, $op->getVaryHeader(), 'Vary:' );
2269 }
2270
2271 public static function provideVaryHeaders() {
2272 return [
2273 'No header' => [
2274 [],
2275 [],
2276 'Vary: ',
2277 ],
2278 'Single header' => [
2279 [
2280 [ 'Cookie' ],
2281 ],
2282 [],
2283 'Vary: Cookie',
2284 ],
2285 'Non-unique headers' => [
2286 [
2287 [ 'Cookie' ],
2288 [ 'Accept-Language' ],
2289 [ 'Cookie' ],
2290 ],
2291 [],
2292 'Vary: Cookie, Accept-Language',
2293 ],
2294 'Two headers with single options' => [
2295 // Options are deprecated since 1.34
2296 [
2297 [ 'Cookie', [ 'param=phpsessid' ] ],
2298 [ 'Accept-Language', [ 'substr=en' ] ],
2299 ],
2300 [],
2301 'Vary: Cookie, Accept-Language',
2302 ],
2303 'One header with multiple options' => [
2304 // Options are deprecated since 1.34
2305 [
2306 [ 'Cookie', [ 'param=phpsessid', 'param=userId' ] ],
2307 ],
2308 [],
2309 'Vary: Cookie',
2310 ],
2311 'Duplicate option' => [
2312 // Options are deprecated since 1.34
2313 [
2314 [ 'Cookie', [ 'param=phpsessid' ] ],
2315 [ 'Cookie', [ 'param=phpsessid' ] ],
2316 [ 'Accept-Language', [ 'substr=en', 'substr=en' ] ],
2317 ],
2318 [],
2319 'Vary: Cookie, Accept-Language',
2320 ],
2321 'Same header, different options' => [
2322 // Options are deprecated since 1.34
2323 [
2324 [ 'Cookie', [ 'param=phpsessid' ] ],
2325 [ 'Cookie', [ 'param=userId' ] ],
2326 ],
2327 [],
2328 'Vary: Cookie',
2329 ],
2330 'No header, vary cookies' => [
2331 [],
2332 [ 'cookie1', 'cookie2' ],
2333 'Vary: Cookie',
2334 ],
2335 'Cookie header with option plus vary cookies' => [
2336 // Options are deprecated since 1.34
2337 [
2338 [ 'Cookie', [ 'param=cookie1' ] ],
2339 ],
2340 [ 'cookie2', 'cookie3' ],
2341 'Vary: Cookie',
2342 ],
2343 'Non-cookie header plus vary cookies' => [
2344 [
2345 [ 'Accept-Language' ],
2346 ],
2347 [ 'cookie' ],
2348 'Vary: Accept-Language, Cookie',
2349 ],
2350 'Cookie and non-cookie headers plus vary cookies' => [
2351 // Options are deprecated since 1.34
2352 [
2353 [ 'Cookie', [ 'param=cookie1' ] ],
2354 [ 'Accept-Language' ],
2355 ],
2356 [ 'cookie2' ],
2357 'Vary: Cookie, Accept-Language',
2358 ],
2359 ];
2360 }
2361
2362 public function testVaryHeaderDefault() {
2363 $op = $this->newInstance();
2364 $this->assertSame( 'Vary: Accept-Encoding, Cookie', $op->getVaryHeader() );
2365 }
2366
2367 /**
2368 * @dataProvider provideLinkHeaders
2369 */
2370 public function testLinkHeaders( array $headers, $result ) {
2371 $op = $this->newInstance();
2372
2373 foreach ( $headers as $header ) {
2374 $op->addLinkHeader( $header );
2375 }
2376
2377 $this->assertEquals( $result, $op->getLinkHeader() );
2378 }
2379
2380 public static function provideLinkHeaders() {
2381 return [
2382 [
2383 [],
2384 false
2385 ],
2386 [
2387 [ '<https://foo/bar.jpg>;rel=preload;as=image' ],
2388 'Link: <https://foo/bar.jpg>;rel=preload;as=image',
2389 ],
2390 [
2391 [
2392 '<https://foo/bar.jpg>;rel=preload;as=image',
2393 '<https://foo/baz.jpg>;rel=preload;as=image'
2394 ],
2395 'Link: <https://foo/bar.jpg>;rel=preload;as=image,<https://foo/baz.jpg>;' .
2396 'rel=preload;as=image',
2397 ],
2398 ];
2399 }
2400
2401 /**
2402 * @dataProvider provideAddAcceptLanguage
2403 */
2404 public function testAddAcceptLanguage(
2405 $code, array $variants, $expected, array $options = []
2406 ) {
2407 $req = new FauxRequest( in_array( 'varianturl', $options ) ? [ 'variant' => 'x' ] : [] );
2408 $op = $this->newInstance( [], $req, in_array( 'notitle', $options ) ? 'notitle' : null );
2409
2410 if ( !in_array( 'notitle', $options ) ) {
2411 $mockLang = $this->createMock( Language::class );
2412 $mockLang->method( 'getCode' )->willReturn( $code );
2413
2414 $mockLanguageConverter = $this
2415 ->createMock( ILanguageConverter::class );
2416 if ( in_array( 'varianturl', $options ) ) {
2417 $mockLanguageConverter->expects( $this->never() )->method( $this->anything() );
2418 } else {
2419 $mockLanguageConverter->method( 'hasVariants' )->willReturn( count( $variants ) > 1 );
2420 $mockLanguageConverter->method( 'getVariants' )->willReturn( $variants );
2421 }
2422
2423 $languageConverterFactory = $this
2424 ->createMock( LanguageConverterFactory::class );
2425 $languageConverterFactory
2426 ->method( 'getLanguageConverter' )
2427 ->willReturn( $mockLanguageConverter );
2428 $this->setService(
2429 'LanguageConverterFactory',
2430 $languageConverterFactory
2431 );
2432
2433 $mockTitle = $this->createMock( Title::class );
2434 $mockTitle->method( 'getPageLanguage' )->willReturn( $mockLang );
2435
2436 $op->setTitle( $mockTitle );
2437 }
2438
2439 // This will run addAcceptLanguage()
2440 $op->sendCacheControl();
2441 $this->assertSame( "Vary: $expected", $op->getVaryHeader() );
2442 }
2443
2444 public static function provideAddAcceptLanguage() {
2445 return [
2446 'No variants' => [
2447 'en',
2448 [ 'en' ],
2449 'Accept-Encoding, Cookie',
2450 ],
2451 'One simple variant' => [
2452 'en',
2453 [ 'en', 'en-x-piglatin' ],
2454 'Accept-Encoding, Cookie, Accept-Language',
2455 ],
2456 'Multiple variants with BCP47 alternatives' => [
2457 'zh',
2458 [ 'zh', 'zh-hans', 'zh-cn', 'zh-tw' ],
2459 'Accept-Encoding, Cookie, Accept-Language',
2460 ],
2461 'No title' => [
2462 'en',
2463 [ 'en', 'en-x-piglatin' ],
2464 'Accept-Encoding, Cookie',
2465 [ 'notitle' ]
2466 ],
2467 'Variant in URL' => [
2468 'en',
2469 [ 'en', 'en-x-piglatin' ],
2470 'Accept-Encoding, Cookie',
2471 [ 'varianturl' ]
2472 ],
2473 ];
2474 }
2475
2476 public function testClickjacking() {
2477 $op = $this->newInstance();
2478 $this->assertTrue( $op->getPreventClickjacking() );
2479
2480 $op->setPreventClickjacking( false );
2481 $this->assertFalse( $op->getPreventClickjacking() );
2482
2483 $op->setPreventClickjacking( true );
2484 $this->assertTrue( $op->getPreventClickjacking() );
2485
2486 $op->setPreventClickjacking( false );
2487 $this->assertFalse( $op->getPreventClickjacking() );
2488
2489 $pOut1 = $this->createParserOutputStub( 'getPreventClickjacking', true );
2490 $op->addParserOutputMetadata( $pOut1 );
2491 $this->assertTrue( $op->getPreventClickjacking() );
2492
2493 // The ParserOutput can't allow, only prevent
2494 $pOut2 = $this->createParserOutputStub( 'getPreventClickjacking', false );
2495 $op->addParserOutputMetadata( $pOut2 );
2496 $this->assertTrue( $op->getPreventClickjacking() );
2497
2498 // Reset to test with addParserOutput()
2499 $op->setPreventClickjacking( false );
2500 $this->assertFalse( $op->getPreventClickjacking() );
2501
2502 $op->addParserOutput( $pOut1 );
2503 $this->assertTrue( $op->getPreventClickjacking() );
2504
2505 $op->addParserOutput( $pOut2 );
2506 $this->assertTrue( $op->getPreventClickjacking() );
2507 }
2508
2509 /**
2510 * @dataProvider provideGetFrameOptions
2511 */
2512 public function testGetFrameOptions(
2513 $breakFrames, $preventClickjacking, $editPageFrameOptions, $expected
2514 ) {
2515 $op = $this->newInstance( [
2516 MainConfigNames::BreakFrames => $breakFrames,
2517 MainConfigNames::EditPageFrameOptions => $editPageFrameOptions,
2518 ] );
2519 $op->setPreventClickjacking( $preventClickjacking );
2520
2521 $this->assertSame( $expected, $op->getFrameOptions() );
2522 }
2523
2524 public static function provideGetFrameOptions() {
2525 return [
2526 'BreakFrames true' => [ true, false, false, 'DENY' ],
2527 'Allow clickjacking locally' => [ false, false, 'DENY', false ],
2528 'Allow clickjacking globally' => [ false, true, false, false ],
2529 'DENY globally' => [ false, true, 'DENY', 'DENY' ],
2530 'SAMEORIGIN' => [ false, true, 'SAMEORIGIN', 'SAMEORIGIN' ],
2531 'BreakFrames with SAMEORIGIN' => [ true, true, 'SAMEORIGIN', 'DENY' ],
2532 ];
2533 }
2534
2535 /**
2536 * See ClientHtmlTest for full coverage.
2537 *
2538 * @dataProvider provideMakeResourceLoaderLink
2539 */
2540 public function testMakeResourceLoaderLink( $args, $expectedHtml ) {
2541 $this->overrideConfigValues( [
2542 MainConfigNames::ResourceLoaderDebug => false,
2543 MainConfigNames::LoadScript => 'http://127.0.0.1:8080/w/load.php',
2544 MainConfigNames::CSPReportOnlyHeader => true,
2545 ] );
2546 $ctx = new RequestContext();
2547 $skinFactory = $this->getServiceContainer()->getSkinFactory();
2548 $ctx->setSkin( $skinFactory->makeSkin( 'fallback' ) );
2549 $ctx->setLanguage( 'en' );
2550 /** @var OutputPage $out */
2551 $out = TestingAccessWrapper::newFromObject( new OutputPage( $ctx ) );
2552 $rl = $out->getResourceLoader();
2553 $rl->setMessageBlobStore( $this->createMock( RL\MessageBlobStore::class ) );
2554 $rl->setDependencyStore( $this->createMock( KeyValueDependencyStore::class ) );
2555 $rl->register( [
2556 'test.foo' => [
2557 'class' => ResourceLoaderTestModule::class,
2558 'script' => 'mw.test.foo( { a: true } );',
2559 'styles' => '.mw-test-foo { content: "style"; }',
2560 ],
2561 'test.bar' => [
2562 'class' => ResourceLoaderTestModule::class,
2563 'script' => 'mw.test.bar( { a: true } );',
2564 'styles' => '.mw-test-bar { content: "style"; }',
2565 ],
2566 'test.baz' => [
2567 'class' => ResourceLoaderTestModule::class,
2568 'script' => 'mw.test.baz( { a: true } );',
2569 'styles' => '.mw-test-baz { content: "style"; }',
2570 ],
2571 'test.quux' => [
2572 'class' => ResourceLoaderTestModule::class,
2573 'script' => 'mw.test.baz( { token: 123 } );',
2574 'styles' => '/* pref-animate=off */ .mw-icon { transition: none; }',
2575 'group' => 'private',
2576 ],
2577 'test.noscript' => [
2578 'class' => ResourceLoaderTestModule::class,
2579 'styles' => '.stuff { color: red; }',
2580 'group' => 'noscript',
2581 ],
2582 'test.group.foo' => [
2583 'class' => ResourceLoaderTestModule::class,
2584 'script' => 'mw.doStuff( "foo" );',
2585 'group' => 'foo',
2586 ],
2587 'test.group.bar' => [
2588 'class' => ResourceLoaderTestModule::class,
2589 'script' => 'mw.doStuff( "bar" );',
2590 'group' => 'bar',
2591 ],
2592 ] );
2593 $links = $out->makeResourceLoaderLink( ...$args );
2594 $actualHtml = strval( $links );
2595 $this->assertEquals( $expectedHtml, $actualHtml );
2596 }
2597
2598 public static function provideMakeResourceLoaderLink() {
2599 return [
2600 // Single only=scripts load
2601 [
2602 [ 'test.foo', RL\Module::TYPE_SCRIPTS ],
2603 "<script>(RLQ=window.RLQ||[]).push(function(){"
2604 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.foo\u0026only=scripts");'
2605 . "});</script>"
2606 ],
2607 // Multiple only=styles load
2608 [
2609 [ [ 'test.baz', 'test.foo', 'test.bar' ], RL\Module::TYPE_STYLES ],
2610
2611 '<link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&amp;modules=test.bar%2Cbaz%2Cfoo&amp;only=styles">'
2612 ],
2613 // Private embed (only=scripts)
2614 [
2615 [ 'test.quux', RL\Module::TYPE_SCRIPTS ],
2616 "<script>(RLQ=window.RLQ||[]).push(function(){"
2617 . "mw.test.baz({token:123});\nmw.loader.state({\"test.quux\":\"ready\"});"
2618 . "});</script>"
2619 ],
2620 // Load private module (combined)
2621 [
2622 [ 'test.quux', RL\Module::TYPE_COMBINED ],
2623 "<script>(RLQ=window.RLQ||[]).push(function(){"
2624 . "mw.loader.impl(function(){return[\"test.quux@1b4i1\",function($,jQuery,require,module){"
2625 . "mw.test.baz({token:123});\n"
2626 . "},{\"css\":[\".mw-icon{transition:none}"
2627 . "\"]}];});});</script>"
2628 ],
2629 // Load no modules
2630 [
2631 [ [], RL\Module::TYPE_COMBINED ],
2632 '',
2633 ],
2634 // noscript group
2635 [
2636 [ 'test.noscript', RL\Module::TYPE_STYLES ],
2637 '<noscript><link rel="stylesheet" href="http://127.0.0.1:8080/w/load.php?lang=en&amp;modules=test.noscript&amp;only=styles"></noscript>'
2638 ],
2639 // Load two modules in separate groups
2640 [
2641 [ [ 'test.group.foo', 'test.group.bar' ], RL\Module::TYPE_COMBINED ],
2642 "<script>(RLQ=window.RLQ||[]).push(function(){"
2643 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.bar");'
2644 . 'mw.loader.load("http://127.0.0.1:8080/w/load.php?lang=en\u0026modules=test.group.foo");'
2645 . "});</script>"
2646 ],
2647 ];
2648 // phpcs:enable
2649 }
2650
2651 /**
2652 * @dataProvider provideBuildExemptModules
2653 */
2654 public function testBuildExemptModules( array $exemptStyleModules, $expect ) {
2655 $this->overrideConfigValues( [
2656 MainConfigNames::ResourceLoaderDebug => false,
2657 MainConfigNames::LoadScript => '/w/load.php',
2658 // Stub wgCacheEpoch as it influences getVersionHash used for the
2659 // urls in the expected HTML
2660 MainConfigNames::CacheEpoch => '20140101000000',
2661 ] );
2662
2663 // Set up stubs
2664 $ctx = new RequestContext();
2665 $skinFactory = $this->getServiceContainer()->getSkinFactory();
2666 $ctx->setSkin( $skinFactory->makeSkin( 'fallback' ) );
2667 $ctx->setLanguage( 'en' );
2668 $op = $this->getMockBuilder( OutputPage::class )
2669 ->setConstructorArgs( [ $ctx ] )
2670 ->onlyMethods( [ 'buildCssLinksArray' ] )
2671 ->getMock();
2672 $op->method( 'buildCssLinksArray' )
2673 ->willReturn( [] );
2674 /** @var OutputPage $op */
2675 $rl = $op->getResourceLoader();
2676 $rl->setMessageBlobStore( $this->createMock( RL\MessageBlobStore::class ) );
2677
2678 // Register custom modules
2679 $rl->register( [
2680 'example.site.a' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'site' ],
2681 'example.site.b' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'site' ],
2682 'example.user' => [ 'class' => ResourceLoaderTestModule::class, 'group' => 'user' ],
2683 ] );
2684
2685 $op = TestingAccessWrapper::newFromObject( $op );
2686 $op->rlExemptStyleModules = $exemptStyleModules;
2687 $expect = strtr( $expect, [
2688 '{blankCombi}' => ResourceLoaderTestCase::BLANK_COMBI,
2689 ] );
2690 $this->assertEquals(
2691 $expect,
2692 strval( $op->buildExemptModules() )
2693 );
2694 }
2695
2696 public static function provideBuildExemptModules() {
2697 return [
2698 'empty' => [
2699 'exemptStyleModules' => [],
2700 '',
2701 ],
2702 'empty sets' => [
2703 'exemptStyleModules' => [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ],
2704 '',
2705 ],
2706 'default logged-out' => [
2707 'exemptStyleModules' => [ 'site' => [ 'site.styles' ] ],
2708 '<meta name="ResourceLoaderDynamicStyles" content="">' . "\n" .
2709 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles">',
2710 ],
2711 'default logged-in' => [
2712 'exemptStyleModules' => [ 'site' => [ 'site.styles' ], 'user' => [ 'user.styles' ] ],
2713 '<meta name="ResourceLoaderDynamicStyles" content="">' . "\n" .
2714 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles">' . "\n" .
2715 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=user.styles&amp;only=styles&amp;version=94mvi">',
2716 ],
2717 'custom modules' => [
2718 'exemptStyleModules' => [
2719 'site' => [ 'site.styles', 'example.site.a', 'example.site.b' ],
2720 'user' => [ 'user.styles', 'example.user' ],
2721 ],
2722 '<meta name="ResourceLoaderDynamicStyles" content="">' . "\n" .
2723 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=example.site.a%2Cb&amp;only=styles">' . "\n" .
2724 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=site.styles&amp;only=styles">' . "\n" .
2725 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=example.user&amp;only=styles&amp;version={blankCombi}">' . "\n" .
2726 '<link rel="stylesheet" href="/w/load.php?lang=en&amp;modules=user.styles&amp;only=styles&amp;version=94mvi">',
2727 ],
2728 ];
2729 // phpcs:enable
2730 }
2731
2732 /**
2733 * @dataProvider provideTransformFilePath
2734 */
2735 public function testTransformResourcePath( $baseDir, $basePath, $uploadDir = null,
2736 $uploadPath = null, $path = null, $expected = null
2737 ) {
2738 if ( $path === null ) {
2739 // Skip optional $uploadDir and $uploadPath
2740 $path = $uploadDir;
2741 $expected = $uploadPath;
2742 $uploadDir = "$baseDir/images";
2743 $uploadPath = "$basePath/images";
2744 }
2745 $conf = new HashConfig( [
2746 MainConfigNames::ResourceBasePath => $basePath,
2747 MainConfigNames::UploadDirectory => $uploadDir,
2748 MainConfigNames::UploadPath => $uploadPath,
2749 MainConfigNames::BaseDirectory => $baseDir
2750 ] );
2751
2752 // Some of these paths don't exist and will cause warnings
2753 $actual = @OutputPage::transformResourcePath( $conf, $path );
2754
2755 $this->assertEquals( $expected ?: $path, $actual );
2756 }
2757
2758 public static function provideTransformFilePath() {
2759 $baseDir = dirname( __DIR__ ) . '/../data/media';
2760 return [
2761 // File that matches basePath, and exists. Hash found and appended.
2762 [
2763 'baseDir' => $baseDir, 'basePath' => '/w',
2764 '/w/test.jpg',
2765 '/w/test.jpg?edcf2'
2766 ],
2767 // File that matches basePath, but not found on disk. Empty query.
2768 [
2769 'baseDir' => $baseDir, 'basePath' => '/w',
2770 '/w/unknown.png',
2771 '/w/unknown.png'
2772 ],
2773 // File not matching basePath. Ignored.
2774 [
2775 'baseDir' => $baseDir, 'basePath' => '/w',
2776 '/files/test.jpg'
2777 ],
2778 // Empty string. Ignored.
2779 [
2780 'baseDir' => $baseDir, 'basePath' => '/w',
2781 '',
2782 ''
2783 ],
2784 // Similar path, but with domain component. Ignored.
2785 [
2786 'baseDir' => $baseDir, 'basePath' => '/w',
2787 '//example.org/w/test.jpg'
2788 ],
2789 [
2790 'baseDir' => $baseDir, 'basePath' => '/w',
2791 'https://www.example.org/w/test.jpg'
2792 ],
2793 // Unrelated path with domain component. Ignored.
2794 [
2795 'baseDir' => $baseDir, 'basePath' => '/w',
2796 'https://www.example.org/files/test.jpg'
2797 ],
2798 [
2799 'baseDir' => $baseDir, 'basePath' => '/w',
2800 '//example.org/files/test.jpg'
2801 ],
2802 // Unrelated path with domain, and empty base path (root mw install). Ignored.
2803 [
2804 'baseDir' => $baseDir, 'basePath' => '',
2805 'https://www.example.org/files/test.jpg'
2806 ],
2807 [
2808 'baseDir' => $baseDir, 'basePath' => '',
2809 // T155310
2810 '//example.org/files/test.jpg'
2811 ],
2812 // Check UploadPath before ResourceBasePath (T155146)
2813 [
2814 'baseDir' => dirname( $baseDir ), 'basePath' => '',
2815 'uploadDir' => $baseDir, 'uploadPath' => '/images',
2816 '/images/test.jpg',
2817 '/images/test.jpg?edcf2'
2818 ],
2819 ];
2820 }
2821
2822 /**
2823 * Tests a particular case of transformCssMedia, using the given input, globals,
2824 * expected return, and message
2825 *
2826 * Asserts that $expectedReturn is returned.
2827 *
2828 * options['queryData'] - value of query string
2829 * options['media'] - passed into the method under the same name
2830 * options['expectedReturn'] - expected return value
2831 * options['message'] - PHPUnit message for assertion
2832 *
2833 * @param array $args Key-value array of arguments as shown above
2834 */
2835 protected function assertTransformCssMediaCase( $args ) {
2836 $queryData = $args['queryData'] ?? [];
2837
2838 $fauxRequest = new FauxRequest( $queryData, false );
2839 $this->setRequest( $fauxRequest );
2840
2841 $actualReturn = OutputPage::transformCssMedia( $args['media'] );
2842 $this->assertSame( $args['expectedReturn'], $actualReturn, $args['message'] );
2843 }
2844
2845 public function testPrintRequests() {
2846 $this->assertTransformCssMediaCase( [
2847 'queryData' => [ 'printable' => '1' ],
2848 'media' => 'screen',
2849 'expectedReturn' => null,
2850 'message' => 'On printable request, screen returns null'
2851 ] );
2852
2853 $this->assertTransformCssMediaCase( [
2854 'queryData' => [ 'printable' => '1' ],
2855 'media' => self::SCREEN_MEDIA_QUERY,
2856 'expectedReturn' => null,
2857 'message' => 'On printable request, screen media query returns null'
2858 ] );
2859
2860 $this->assertTransformCssMediaCase( [
2861 'queryData' => [ 'printable' => '1' ],
2862 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2863 'expectedReturn' => null,
2864 'message' => 'On printable request, screen media query with only returns null'
2865 ] );
2866
2867 $this->assertTransformCssMediaCase( [
2868 'queryData' => [ 'printable' => '1' ],
2869 'media' => 'print',
2870 'expectedReturn' => '',
2871 'message' => 'On printable request, media print returns empty string'
2872 ] );
2873 }
2874
2875 /**
2876 * Test screen requests, without either query parameter set
2877 */
2878 public function testScreenRequests() {
2879 $this->assertTransformCssMediaCase( [
2880 'media' => 'screen',
2881 'expectedReturn' => 'screen',
2882 'message' => 'On screen request, screen media type is preserved'
2883 ] );
2884
2885 $this->assertTransformCssMediaCase( [
2886 'media' => 'handheld',
2887 'expectedReturn' => 'handheld',
2888 'message' => 'On screen request, handheld media type is preserved'
2889 ] );
2890
2891 $this->assertTransformCssMediaCase( [
2892 'media' => self::SCREEN_MEDIA_QUERY,
2893 'expectedReturn' => self::SCREEN_MEDIA_QUERY,
2894 'message' => 'On screen request, screen media query is preserved.'
2895 ] );
2896
2897 $this->assertTransformCssMediaCase( [
2898 'media' => self::SCREEN_ONLY_MEDIA_QUERY,
2899 'expectedReturn' => self::SCREEN_ONLY_MEDIA_QUERY,
2900 'message' => 'On screen request, screen media query with only is preserved.'
2901 ] );
2902
2903 $this->assertTransformCssMediaCase( [
2904 'media' => 'print',
2905 'expectedReturn' => 'print',
2906 'message' => 'On screen request, print media type is preserved'
2907 ] );
2908 }
2909
2910 public function testIsTOCEnabled() {
2911 $op = $this->newInstance();
2912 $this->assertFalse( $op->isTOCEnabled() );
2913 $this->assertFalse( $op->getOutputFlag( ParserOutputFlags::SHOW_TOC ) );
2914
2915 $pOut1 = $this->createParserOutputStub();
2916 $op->addParserOutputMetadata( $pOut1 );
2917 $this->assertFalse( $op->isTOCEnabled() );
2918 $this->assertFalse( $op->getOutputFlag( ParserOutputFlags::SHOW_TOC ) );
2919
2920 $pOut2 = $this->createParserOutputStubWithFlags(
2921 [], [ ParserOutputFlags::SHOW_TOC ]
2922 );
2923 $op->addParserOutput( $pOut2 );
2924 $this->assertTrue( $op->isTOCEnabled() );
2925 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::SHOW_TOC ) );
2926
2927 // The parser output doesn't disable the TOC after it was enabled
2928 $op->addParserOutputMetadata( $pOut1 );
2929 $this->assertTrue( $op->isTOCEnabled() );
2930 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::SHOW_TOC ) );
2931 }
2932
2933 public function testNoTOC() {
2934 $op = $this->newInstance();
2935 $this->assertFalse( $op->getOutputFlag( ParserOutputFlags::NO_TOC ) );
2936
2937 $stubPO1 = $this->createParserOutputStubWithFlags(
2938 [], [ ParserOutputFlags::NO_TOC ]
2939 );
2940 $op->addParserOutputMetadata( $stubPO1 );
2941 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NO_TOC ) );
2942
2943 $stubPO2 = $this->createParserOutputStub();
2944 $this->assertFalse( $stubPO2->getOutputFlag( ParserOutputFlags::NO_TOC ) );
2945 $op->addParserOutput( $stubPO2 );
2946 // Note that flags are OR'ed together, and not reset.
2947 $this->assertTrue( $op->getOutputFlag( ParserOutputFlags::NO_TOC ) );
2948 }
2949
2950 /**
2951 * @dataProvider providePreloadLinkHeaders
2952 * @covers \MediaWiki\ResourceLoader\SkinModule
2953 */
2954 public function testPreloadLinkHeaders( $config, $result ) {
2955 $ctx = $this->createMock( RL\Context::class );
2956 $module = new RL\SkinModule();
2957 $module->setConfig( new HashConfig( $config + ResourceLoaderTestCase::getSettings() ) );
2958
2959 $this->assertEquals( [ $result ], $module->getHeaders( $ctx ) );
2960 }
2961
2962 public static function providePreloadLinkHeaders() {
2963 return [
2964 [
2965 [
2966 MainConfigNames::ResourceBasePath => '/w',
2967 MainConfigNames::Logo => '/img/default.png',
2968 MainConfigNames::Logos => [
2969 '1.5x' => '/img/one-point-five.png',
2970 '2x' => '/img/two-x.png',
2971 ],
2972 ],
2973 'Link: </img/default.png>;rel=preload;as=image;media=' .
2974 'not all and (min-resolution: 1.5dppx),' .
2975 '</img/one-point-five.png>;rel=preload;as=image;media=' .
2976 '(min-resolution: 1.5dppx) and (max-resolution: 1.999999dppx),' .
2977 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
2978 ],
2979 [
2980 [
2981 MainConfigNames::ResourceBasePath => '/w',
2982 MainConfigNames::Logos => [
2983 '1x' => '/img/default.png',
2984 ],
2985 ],
2986 'Link: </img/default.png>;rel=preload;as=image'
2987 ],
2988 [
2989 [
2990 MainConfigNames::ResourceBasePath => '/w',
2991 MainConfigNames::Logos => [
2992 '1x' => '/img/default.png',
2993 '2x' => '/img/two-x.png',
2994 ],
2995 ],
2996 'Link: </img/default.png>;rel=preload;as=image;media=' .
2997 'not all and (min-resolution: 2dppx),' .
2998 '</img/two-x.png>;rel=preload;as=image;media=(min-resolution: 2dppx)'
2999 ],
3000 [
3001 [
3002 MainConfigNames::ResourceBasePath => '/w',
3003 MainConfigNames::Logos => [
3004 '1x' => '/img/default.png',
3005 'svg' => '/img/vector.svg',
3006 ],
3007 ],
3008 'Link: </img/vector.svg>;rel=preload;as=image'
3009
3010 ],
3011 [
3012 [
3013 MainConfigNames::ResourceBasePath => '/w',
3014 MainConfigNames::Logos => [
3015 '1x' => '/w/test.jpg',
3016 ],
3017 MainConfigNames::UploadPath => '/w/images',
3018 MainConfigNames::BaseDirectory => dirname( __DIR__ ) . '/../data/media'
3019 ],
3020 'Link: </w/test.jpg?edcf2>;rel=preload;as=image',
3021 ],
3022 ];
3023 }
3024
3025 /**
3026 * @param int $titleLastRevision Last Title revision to set
3027 * @param int $outputRevision Revision stored in OutputPage
3028 * @param bool $expectedResult Expected result of $output->isRevisionCurrent call
3029 * @dataProvider provideIsRevisionCurrent
3030 */
3031 public function testIsRevisionCurrent( $titleLastRevision, $outputRevision, $expectedResult ) {
3032 $titleMock = $this->createMock( Title::class );
3033 $titleMock->method( 'getLatestRevID' )
3034 ->willReturn( $titleLastRevision );
3035
3036 $output = $this->newInstance( [], null );
3037 $output->setTitle( $titleMock );
3038 $output->setRevisionId( $outputRevision );
3039 $this->assertEquals( $expectedResult, $output->isRevisionCurrent() );
3040 }
3041
3042 public static function provideIsRevisionCurrent() {
3043 return [
3044 [ 10, null, true ],
3045 [ 42, 42, true ],
3046 [ null, 0, true ],
3047 [ 42, 47, false ],
3048 [ 47, 42, false ]
3049 ];
3050 }
3051
3052 /**
3053 * @dataProvider provideSendCacheControl
3054 */
3055 public function testSendCacheControl( array $options = [], array $expectations = [] ) {
3056 $this->overrideConfigValue( MainConfigNames::UsePigLatinVariant, $options['variant'] ?? false );
3057
3058 $output = $this->newInstance( [
3059 MainConfigNames::UseCdn => $options['useCdn'] ?? false,
3060 ] );
3061 $output->considerCacheSettingsFinal();
3062
3063 $cacheable = $options['enableClientCache'] ?? true;
3064 if ( !$cacheable ) {
3065 $output->disableClientCache();
3066 }
3067 $this->assertEquals( $cacheable, $output->couldBePublicCached() );
3068
3069 $output->setCdnMaxage( $options['cdnMaxAge'] ?? 0 );
3070
3071 if ( isset( $options['lastModified'] ) ) {
3072 $output->setLastModified( $options['lastModified'] );
3073 }
3074
3075 $response = $output->getRequest()->response();
3076 if ( isset( $options['cookie'] ) ) {
3077 $response->setCookie( 'test', 1234 );
3078 }
3079
3080 $output->sendCacheControl();
3081
3082 $headers = [
3083 'Vary' => 'Accept-Encoding, Cookie',
3084 'Cache-Control' => 'private, must-revalidate, max-age=0',
3085 'Expires' => true,
3086 'Last-Modified' => false,
3087 ];
3088
3089 foreach ( $headers as $header => $default ) {
3090 $value = $expectations[$header] ?? $default;
3091 if ( $value === true ) {
3092 $this->assertNotEmpty( $response->getHeader( $header ), "$header header" );
3093 } elseif ( $value === false ) {
3094 $this->assertNull( $response->getHeader( $header ), "$header header" );
3095 } else {
3096 $this->assertEquals( $value, $response->getHeader( $header ), "$header header" );
3097 }
3098 }
3099 }
3100
3101 public static function provideSendCacheControl() {
3102 return [
3103 'Vary on variant' => [
3104 [
3105 'variant' => true,
3106 ],
3107 [
3108 'Vary' => 'Accept-Encoding, Cookie, Accept-Language',
3109 ]
3110 ],
3111 'Private by default' => [
3112 [],
3113 [
3114 'Cache-Control' => 'private, must-revalidate, max-age=0',
3115 ],
3116 ],
3117 'Cookies force private' => [
3118 [
3119 'cookie' => true,
3120 'useCdn' => true,
3121 'cdnMaxAge' => 300,
3122 ],
3123 [
3124 'Cache-Control' => 'private, must-revalidate, max-age=0',
3125 ]
3126 ],
3127 'Disable client cache' => [
3128 [
3129 'enableClientCache' => false,
3130 'useCdn' => true,
3131 'cdnMaxAge' => 300,
3132 ],
3133 [
3134 'Cache-Control' => 'no-cache, no-store, max-age=0, must-revalidate',
3135 ],
3136 ],
3137 'Set last modified' => [
3138 [
3139 // 0 is the current time, so we'll use 1 instead.
3140 'lastModified' => 1,
3141 ],
3142 [
3143 'Last-Modified' => 'Thu, 01 Jan 1970 00:00:01 GMT',
3144 ]
3145 ],
3146 'Public' => [
3147 [
3148 'useCdn' => true,
3149 'cdnMaxAge' => 300,
3150 ],
3151 [
3152 'Cache-Control' => 's-maxage=300, must-revalidate, max-age=0',
3153 'Expires' => false,
3154 ],
3155 ],
3156 ];
3157 }
3158
3159 public function provideGetJsVarsEditable() {
3160 yield 'can edit and create' => [
3161 'performer' => $this->mockAnonAuthorityWithPermissions( [ 'edit', 'create' ] ),
3162 'expectedEditableConfig' => [
3163 'wgIsProbablyEditable' => true,
3164 'wgRelevantPageIsProbablyEditable' => true,
3165 ]
3166 ];
3167 yield 'cannot edit or create' => [
3168 'performer' => $this->mockAnonAuthorityWithoutPermissions( [ 'edit', 'create' ] ),
3169 'expectedEditableConfig' => [
3170 'wgIsProbablyEditable' => false,
3171 'wgRelevantPageIsProbablyEditable' => false,
3172 ]
3173 ];
3174 yield 'only can edit relevant title' => [
3175 'performer' => $this->mockAnonAuthority( static function (
3176 string $permission,
3177 PageIdentity $page
3178 ) {
3179 return ( $permission === 'edit' || $permission === 'create' ) && $page->getDBkey() === 'RelevantTitle';
3180 } ),
3181 'expectedEditableConfig' => [
3182 'wgIsProbablyEditable' => false,
3183 'wgRelevantPageIsProbablyEditable' => true,
3184 ]
3185 ];
3186 }
3187
3188 /**
3189 * @dataProvider provideGetJsVarsEditable
3190 */
3191 public function testGetJsVarsEditable( Authority $performer, array $expectedEditableConfig ) {
3192 $op = $this->newInstance( [], null, null, $performer );
3193 $op->getContext()->getSkin()->setRelevantTitle( Title::makeTitle( NS_MAIN, 'RelevantTitle' ) );
3194 $this->assertArraySubmapSame( $expectedEditableConfig, $op->getJSVars() );
3195 }
3196
3197 public function provideJsVarsAboutPageLang() {
3198 // Format:
3199 // - expected
3200 // - title
3201 // - site content language
3202 // - user language
3203 // - wgDefaultLanguageVariant
3204 return [
3205 [ 'fr', [ NS_HELP, 'I_need_somebody' ], 'fr', 'fr', false ],
3206 [ 'es', [ NS_HELP, 'I_need_somebody' ], 'es', 'zh-tw', false ],
3207 [ 'zh', [ NS_HELP, 'I_need_somebody' ], 'zh', 'zh-tw', false ],
3208 [ 'es', [ NS_HELP, 'I_need_somebody' ], 'es', 'zh-tw', 'zh-cn' ],
3209 [ 'es', [ NS_MEDIAWIKI, 'About' ], 'es', 'zh-tw', 'zh-cn' ],
3210 [ 'es', [ NS_MEDIAWIKI, 'About/' ], 'es', 'zh-tw', 'zh-cn' ],
3211 [ 'de', [ NS_MEDIAWIKI, 'About/de' ], 'es', 'zh-tw', 'zh-cn' ],
3212 [ 'en', [ NS_MEDIAWIKI, 'Common.js' ], 'es', 'zh-tw', 'zh-cn' ],
3213 [ 'en', [ NS_MEDIAWIKI, 'Common.css' ], 'es', 'zh-tw', 'zh-cn' ],
3214 [ 'en', [ NS_USER, 'JohnDoe/Common.js' ], 'es', 'zh-tw', 'zh-cn' ],
3215 [ 'en', [ NS_USER, 'JohnDoe/Monobook.css' ], 'es', 'zh-tw', 'zh-cn' ],
3216
3217 [ 'zh-cn', [ NS_HELP, 'I_need_somebody' ], 'zh', 'zh-tw', 'zh-cn' ],
3218 [ 'zh', [ NS_MEDIAWIKI, 'About' ], 'zh', 'zh-tw', 'zh-cn' ],
3219 [ 'zh', [ NS_MEDIAWIKI, 'About/' ], 'zh', 'zh-tw', 'zh-cn' ],
3220 [ 'de', [ NS_MEDIAWIKI, 'About/de' ], 'zh', 'zh-tw', 'zh-cn' ],
3221 [ 'zh-cn', [ NS_MEDIAWIKI, 'About/zh-cn' ], 'zh', 'zh-tw', 'zh-cn' ],
3222 [ 'zh-tw', [ NS_MEDIAWIKI, 'About/zh-tw' ], 'zh', 'zh-tw', 'zh-cn' ],
3223 [ 'en', [ NS_MEDIAWIKI, 'Common.js' ], 'zh', 'zh-tw', 'zh-cn' ],
3224 [ 'en', [ NS_MEDIAWIKI, 'Common.css' ], 'zh', 'zh-tw', 'zh-cn' ],
3225 [ 'en', [ NS_USER, 'JohnDoe/Common.js' ], 'zh', 'zh-tw', 'zh-cn' ],
3226 [ 'en', [ NS_USER, 'JohnDoe/Monobook.css' ], 'zh', 'zh-tw', 'zh-cn' ],
3227
3228 [ 'nl', [ NS_SPECIAL, 'BlankPage' ], 'en', 'nl', false ],
3229 [ 'zh-tw', [ NS_SPECIAL, 'NewPages' ], 'es', 'zh-tw', 'zh-cn' ],
3230 [ 'zh-tw', [ NS_SPECIAL, 'NewPages' ], 'zh', 'zh-tw', 'zh-cn' ],
3231
3232 [ 'sr-ec', [ NS_FILE, 'Example' ], 'sr', 'sr', 'sr-ec' ],
3233 [ 'sr', [ NS_FILE, 'Example' ], 'sr', 'sr', 'sr' ],
3234 [ 'sr-ec', [ NS_MEDIAWIKI, 'Example' ], 'sr-ec', 'sr-ec', 'sr' ],
3235 [ 'sr', [ NS_MEDIAWIKI, 'Example' ], 'sr', 'sr', 'sr-ec' ],
3236 ];
3237 }
3238
3239 /**
3240 * @dataProvider provideJsVarsAboutPageLang
3241 */
3242 public function testGetJsVarsAboutPageLang( $expected, $title, $contLang, $userLang, $variant ) {
3243 $this->overrideConfigValues( [
3244 MainConfigNames::DefaultLanguageVariant => $variant,
3245 ] );
3246 $this->setContentLang( $contLang );
3247 $output = $this->newInstance(
3248 [ MainConfigNames::LanguageCode => $contLang ],
3249 new FauxRequest( [ 'uselang' => $userLang ] ),
3250 'notitle'
3251 );
3252 $output->setTitle( Title::makeTitle( $title[0], $title[1] ) );
3253
3254 $this->assertArraySubmapSame( [
3255 'wgPageViewLanguage' => $expected,
3256 'wgPageContentLanguage' => $expected,
3257 ], $output->getJSVars() );
3258 }
3259
3260 /**
3261 * @param bool $registered
3262 * @param bool $matchToken
3263 * @return MockObject|User
3264 */
3265 private function mockUser( bool $registered, bool $matchToken ) {
3266 $user = $this->createNoOpMock( User::class, [ 'isRegistered', 'matchEditToken' ] );
3267 $user->method( 'isRegistered' )->willReturn( $registered );
3268 $user->method( 'matchEditToken' )->willReturn( $matchToken );
3269 return $user;
3270 }
3271
3272 public function provideUserCanPreview() {
3273 yield 'all good' => [
3274 'performer' => $this->mockUserAuthorityWithPermissions(
3275 $this->mockUser( true, true ),
3276 [ 'edit' ]
3277 ),
3278 'request' => new FauxRequest( [ 'action' => 'submit' ], true ),
3279 true
3280 ];
3281 yield 'get request' => [
3282 'performer' => $this->mockUserAuthorityWithPermissions(
3283 $this->mockUser( true, true ),
3284 [ 'edit' ]
3285 ),
3286 'request' => new FauxRequest( [ 'action' => 'submit' ], false ),
3287 false
3288 ];
3289 yield 'not a submit action' => [
3290 'performer' => $this->mockUserAuthorityWithPermissions(
3291 $this->mockUser( true, true ),
3292 [ 'edit' ]
3293 ),
3294 'request' => new FauxRequest( [ 'action' => 'something' ], true ),
3295 false
3296 ];
3297 yield 'anon can not' => [
3298 'performer' => $this->mockUserAuthorityWithPermissions(
3299 $this->mockUser( false, true ),
3300 [ 'edit' ]
3301 ),
3302 'request' => new FauxRequest( [ 'action' => 'submit' ], true ),
3303 false
3304 ];
3305 yield 'token not match' => [
3306 'performer' => $this->mockUserAuthorityWithPermissions(
3307 $this->mockUser( true, false ),
3308 [ 'edit' ]
3309 ),
3310 'request' => new FauxRequest( [ 'action' => 'submit' ], true ),
3311 false
3312 ];
3313 yield 'no permission' => [
3314 'performer' => $this->mockUserAuthorityWithoutPermissions(
3315 $this->mockUser( true, true ),
3316 [ 'edit' ]
3317 ),
3318 'request' => new FauxRequest( [ 'action' => 'submit' ], true ),
3319 false
3320 ];
3321 }
3322
3323 /**
3324 * @dataProvider provideUserCanPreview
3325 */
3326 public function testUserCanPreview( Authority $performer, WebRequest $request, bool $expected ) {
3327 $op = $this->newInstance( [], $request, null, $performer );
3328 $this->assertSame( $expected, $op->userCanPreview() );
3329 }
3330
3331 public function providePermissionStatus() {
3332 yield 'no errors' => [
3333 PermissionStatus::newEmpty(),
3334 '',
3335 ];
3336
3337 yield 'one message' => [
3338 PermissionStatus::newEmpty()->fatal( 'badaccess-group0' ),
3339 '(permissionserrorstext: 1)
3340
3341 <div class="permissions-errors"><div class="mw-permissionerror-badaccess-group0">(badaccess-group0)</div></div>',
3342 ];
3343
3344 yield 'two messages' => [
3345 PermissionStatus::newEmpty()->fatal( 'badaccess-group0' )->fatal( 'foobar' ),
3346 '(permissionserrorstext: 2)
3347
3348 <ul class="permissions-errors"><li class="mw-permissionerror-badaccess-group0">(badaccess-group0)</li><li class="mw-permissionerror-foobar">(foobar)</li></ul>',
3349 ];
3350 }
3351
3352 public function provideFormatPermissionStatus() {
3353 yield 'RawMessage' => [
3354 PermissionStatus::newEmpty()->fatal( new RawMessage( 'Foo Bar' ) ),
3355 '(permissionserrorstext: 1)
3356
3357 <div class="permissions-errors"><div class="mw-permissionerror-rawmessage">Foo Bar</div></div>',
3358 ];
3359 }
3360
3361 public function provideFormatPermissionsErrorMessage() {
3362 yield 'RawMessage' => [
3363 PermissionStatus::newEmpty()->fatal( new RawMessage( 'Foo Bar' ) ),
3364 '(permissionserrorstext: 1)
3365
3366 <div class="permissions-errors"><div class="mw-permissionerror-rawmessage">(rawmessage: Foo Bar)</div></div>',
3367 ];
3368 }
3369
3370 /**
3371 * @dataProvider providePermissionStatus
3372 * @dataProvider provideFormatPermissionStatus
3373 */
3374 public function testFormatPermissionStatus( PermissionStatus $status, string $expected ) {
3375 $this->overrideConfigValue( MainConfigNames::LanguageCode, 'qqx' );
3376
3377 $actual = self::newInstance()->formatPermissionStatus( $status );
3378 $this->assertEquals( $expected, $actual );
3379 }
3380
3381 /**
3382 * @dataProvider providePermissionStatus
3383 * @dataProvider provideFormatPermissionsErrorMessage
3384 */
3385 public function testFormatPermissionsErrorMessage( PermissionStatus $status, string $expected ) {
3386 $this->overrideConfigValue( MainConfigNames::LanguageCode, 'qqx' );
3387 $this->filterDeprecated( '/OutputPage::formatPermissionsErrorMessage was deprecated/' );
3388
3389 // Unlike formatPermissionStatus, this method doesn't accept good statuses
3390 $actual = $status->isGood() ? '' :
3391 self::newInstance()->formatPermissionsErrorMessage( $status->toLegacyErrorArray() );
3392 $this->assertEquals( $expected, $actual );
3393 }
3394
3395 private function newInstance(
3396 array $config = [],
3397 ?WebRequest $request = null,
3398 $option = null,
3399 ?Authority $performer = null
3400 ): OutputPage {
3401 $this->overrideConfigValues( [
3402 // Avoid configured skin affecting the headings
3403 MainConfigNames::ParserEnableLegacyHeadingDOM => false,
3404 MainConfigNames::DefaultSkin => 'fallback',
3405 MainConfigNames::HiddenPrefs => [ 'skin' ],
3406 ] );
3407
3408 $context = new RequestContext();
3409
3410 $context->setConfig( new MultiConfig( [
3411 new HashConfig( $config + [
3412 MainConfigNames::AppleTouchIcon => false,
3413 MainConfigNames::EnableCanonicalServerLink => false,
3414 MainConfigNames::Favicon => false,
3415 MainConfigNames::Feed => false,
3416 MainConfigNames::LanguageCode => false,
3417 MainConfigNames::ReferrerPolicy => false,
3418 MainConfigNames::RightsPage => false,
3419 MainConfigNames::RightsUrl => false,
3420 MainConfigNames::UniversalEditButton => false,
3421 ] ),
3422 $this->getServiceContainer()->getMainConfig(),
3423 ] ) );
3424
3425 if ( $option !== 'notitle' ) {
3426 $context->setTitle( Title::makeTitle( NS_MAIN, 'My test page' ) );
3427 }
3428
3429 if ( $request ) {
3430 $context->setRequest( $request );
3431 }
3432
3433 if ( $performer ) {
3434 $context->setAuthority( $performer );
3435 }
3436
3437 return new OutputPage( $context );
3438 }
3439 }