-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
OutputPage.php
4878 lines (4369 loc) · 151 KB
/
OutputPage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Preparation for the final page rendering.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
*/
namespace MediaWiki\Output;
use Article;
use Content;
use CSSJanus;
use Exception;
use ExtensionRegistry;
use File;
use HtmlArmor;
use InvalidArgumentException;
use Language;
use LanguageCode;
use MediaWiki\Cache\LinkCache;
use MediaWiki\Config\Config;
use MediaWiki\Content\JavaScriptContent;
use MediaWiki\Content\TextContent;
use MediaWiki\Context\ContextSource;
use MediaWiki\Context\IContextSource;
use MediaWiki\Context\RequestContext;
use MediaWiki\Debug\MWDebug;
use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
use MediaWiki\Html\Html;
use MediaWiki\Linker\LinkTarget;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiServices;
use MediaWiki\Message\Message;
use MediaWiki\Page\PageRecord;
use MediaWiki\Page\PageReference;
use MediaWiki\Parser\Parser;
use MediaWiki\Parser\ParserOutput;
use MediaWiki\Parser\ParserOutputFlags;
use MediaWiki\Parser\Sanitizer;
use MediaWiki\Permissions\PermissionStatus;
use MediaWiki\Request\ContentSecurityPolicy;
use MediaWiki\Request\FauxRequest;
use MediaWiki\Request\WebRequest;
use MediaWiki\ResourceLoader as RL;
use MediaWiki\ResourceLoader\ResourceLoader;
use MediaWiki\Session\SessionManager;
use MediaWiki\SpecialPage\SpecialPage;
use MediaWiki\Title\Title;
use MediaWiki\Title\TitleValue;
use MediaWiki\Utils\MWTimestamp;
use MessageSpecifier;
use OOUI\Element;
use OOUI\Theme;
use ParserOptions;
use RuntimeException;
use Skin;
use Wikimedia\AtEase\AtEase;
use Wikimedia\Bcp47Code\Bcp47Code;
use Wikimedia\LightweightObjectStore\ExpirationAwareness;
use Wikimedia\Parsoid\Core\TOCData;
use Wikimedia\Rdbms\IResultWrapper;
use Wikimedia\RelPath;
use Wikimedia\WrappedString;
use Wikimedia\WrappedStringList;
/**
* This is one of the Core classes and should
* be read at least once by any new developers. Also documented at
* https://www.mediawiki.org/wiki/Manual:Architectural_modules/OutputPage
*
* This class is used to prepare the final rendering. A skin is then
* applied to the output parameters (links, javascript, html, categories ...).
*
* @todo FIXME: Another class handles sending the whole page to the client.
*
* Some comments comes from a pairing session between Zak Greant and Antoine Musso
* in November 2010.
*
* @todo document
*/
class OutputPage extends ContextSource {
use ProtectedHookAccessorTrait;
/** Output CSP policies as headers */
public const CSP_HEADERS = 'headers';
/** Output CSP policies as meta tags */
public const CSP_META = 'meta';
// Constants for getJSVars()
private const JS_VAR_EARLY = 1;
private const JS_VAR_LATE = 2;
// Core config vars that opt-in to JS_VAR_LATE.
// Extensions use the 'LateJSConfigVarNames' attribute instead.
private const CORE_LATE_JS_CONFIG_VAR_NAMES = [];
/** @var bool Whether setupOOUI() has been called */
private static $oouiSetupDone = false;
/** @var string[][] Should be private. Used with addMeta() which adds "<meta>" */
protected $mMetatags = [];
/** @var array */
protected $mLinktags = [];
/** @var string|false */
protected $mCanonicalUrl = false;
/**
* @var string The contents of <h1>
*/
private $mPageTitle = '';
/**
* @var string The displayed title of the page. Different from page title
* if overridden by display title magic word or hooks. Can contain safe
* HTML. Different from page title which may contain messages such as
* "Editing X" which is displayed in h1. This can be used for other places
* where the page name is referred on the page.
*/
private $displayTitle;
/** @var bool See OutputPage::couldBePublicCached. */
private $cacheIsFinal = false;
/**
* @var string Contains all of the "<body>" content. Should be private we
* got set/get accessors and the append() method.
*/
public $mBodytext = '';
/** @var string Stores contents of "<title>" tag */
private $mHTMLtitle = '';
/**
* @var bool Is the displayed content related to the source of the
* corresponding wiki article.
*/
private $mIsArticle = false;
/** @var bool Stores "article flag" toggle. */
private $mIsArticleRelated = true;
/** @var bool Is the content subject to copyright */
private $mHasCopyright = false;
/**
* @var bool We have to set isPrintable(). Some pages should
* never be printed (ex: redirections).
*/
private $mPrintable = false;
/**
* @var ?TOCData Table of Contents information from ParserOutput, or
* null if no TOCData was ever set.
*/
private $tocData;
/**
* @var array Contains the page subtitle. Special pages usually have some
* links here. Don't confuse with site subtitle added by skins.
*/
private $mSubtitle = [];
/** @var string */
public $mRedirect = '';
/** @var int */
protected $mStatusCode;
/**
* @var string Used for sending cache control.
* The whole caching system should probably be moved into its own class.
*/
protected $mLastModified = '';
/**
* @var string[][]
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mCategoryLinks = [];
/**
* @var string[][]
* @deprecated since 1.38, will be made private (T301020)
*/
protected $mCategories = [
'hidden' => [],
'normal' => [],
];
/**
* @var string[]
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mIndicators = [];
/**
* @var string[] Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page')
*/
private $mLanguageLinks = [];
/**
* Used for JavaScript (predates ResourceLoader)
* @todo We should split JS / CSS.
* mScripts content is inserted as is in "<head>" by Skin. This might
* contain either a link to a stylesheet or inline CSS.
*/
private $mScripts = '';
/** @var string Inline CSS styles. Use addInlineStyle() sparingly */
protected $mInlineStyles = '';
/**
* Additional <html> classes; This should be rarely modified; prefer mAdditionalBodyClasses.
* @var array
*/
protected $mAdditionalHtmlClasses = [];
/**
* @var string[] Array of elements in "<head>". Parser might add its own headers!
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mHeadItems = [];
/** @var array Additional <body> classes; there are also <body> classes from other sources */
protected $mAdditionalBodyClasses = [];
/**
* @var array
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mModules = [];
/**
* @var array
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mModuleStyles = [];
/** @var ResourceLoader */
protected $mResourceLoader;
/** @var RL\ClientHtml */
private $rlClient;
/** @var RL\Context */
private $rlClientContext;
/** @var array */
private $rlExemptStyleModules;
/**
* @var array
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mJsConfigVars = [];
/**
* @var array<int,array<string,int>>
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mTemplateIds = [];
/** @var array */
protected $mImageTimeKeys = [];
/** @var string */
public $mRedirectCode = '';
protected $mFeedLinksAppendQuery = null;
/** @var array
* What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
* @see RL\Module::$origin
* RL\Module::ORIGIN_ALL is assumed unless overridden;
*/
protected $mAllowedModules = [
RL\Module::TYPE_COMBINED => RL\Module::ORIGIN_ALL,
];
/** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
protected $mDoNothing = false;
// Parser related.
/**
* lazy initialised, use parserOptions()
* @var ParserOptions
*/
protected $mParserOptions = null;
/**
* Handles the Atom / RSS links.
* We probably only support Atom in 2011.
* @see $wgAdvertisedFeedTypes
*/
private $mFeedLinks = [];
/**
* @var bool Set to false to send no-cache headers, disabling
* client-side caching. (This variable should really be named
* in the opposite sense; see ::disableClientCache().)
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mEnableClientCache = true;
/** @var bool Flag if output should only contain the body of the article. */
private $mArticleBodyOnly = false;
/**
* @var bool
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mNewSectionLink = false;
/**
* @var bool
* @deprecated since 1.38; will be made private (T301020)
*/
protected $mHideNewSectionLink = false;
/**
* @var bool Comes from the parser. This was probably made to load CSS/JS
* only if we had "<gallery>". Used directly in CategoryPage.php.
* Looks like ResourceLoader can replace this.
* @deprecated since 1.38; will be made private (T301020)
*/
public $mNoGallery = false;
/** @var int Cache stuff. Looks like mEnableClientCache */
protected $mCdnMaxage = 0;
/** @var int Upper limit on mCdnMaxage */
protected $mCdnMaxageLimit = INF;
/**
* @var bool Controls if anti-clickjacking / frame-breaking headers will
* be sent. This should be done for pages where edit actions are possible.
* Setter: $this->setPreventClickjacking()
*/
protected $mPreventClickjacking = true;
/** @var int|null To include the variable {{REVISIONID}} */
private $mRevisionId = null;
/** @var bool|null */
private $mRevisionIsCurrent = null;
/** @var string */
private $mRevisionTimestamp = null;
/** @var array */
protected $mFileVersion = null;
/**
* @var array An array of stylesheet filenames (relative from skins path),
* with options for CSS media, IE conditions, and RTL/LTR direction.
* For internal use; add settings in the skin via $this->addStyle()
*
* Style again! This seems like a code duplication since we already have
* mStyles. This is what makes Open Source amazing.
*/
protected $styles = [];
private $mIndexPolicy = 'index';
private $mFollowPolicy = 'follow';
/** @var array */
private $mRobotsOptions = [ 'max-image-preview' => 'standard' ];
/**
* @var array Headers that cause the cache to vary. Key is header name,
* value should always be null. (Value was an array of options for
* the `Key` header, which was deprecated in 1.32 and removed in 1.34.)
*/
private $mVaryHeader = [
'Accept-Encoding' => null,
];
/**
* If the current page was reached through a redirect, $mRedirectedFrom contains the title
* of the redirect.
*
* @var PageReference
*/
private $mRedirectedFrom = null;
/**
* Additional key => value data
*/
private $mProperties = [];
/**
* @var string|null ResourceLoader target for load.php links. If null, will be omitted
*/
private $mTarget = null;
/**
* @var bool Whether parser output contains a table of contents
*/
private $mEnableTOC = false;
/**
* @var array<string,bool> Flags set in the ParserOutput
*/
private $mOutputFlags = [];
/**
* @var string|null The URL to send in a <link> element with rel=license
*/
private $copyrightUrl;
/**
* @var Language|null
*/
private $contentLang;
/** @var array Profiling data */
private $limitReportJSData = [];
/** @var array Map Title to Content */
private $contentOverrides = [];
/** @var callable[] */
private $contentOverrideCallbacks = [];
/**
* Link: header contents
*/
private $mLinkHeader = [];
/**
* @var ContentSecurityPolicy
*/
private $CSP;
private string $cspOutputMode = self::CSP_HEADERS;
/**
* @var array A cache of the names of the cookies that will influence the cache
*/
private static $cacheVaryCookies = null;
/**
* Constructor for OutputPage. This should not be called directly.
* Instead a new RequestContext should be created and it will implicitly create
* a OutputPage tied to that context.
* @param IContextSource $context
*/
public function __construct( IContextSource $context ) {
$this->setContext( $context );
$this->CSP = new ContentSecurityPolicy(
$context->getRequest()->response(),
$context->getConfig(),
$this->getHookContainer()
);
}
/**
* Redirect to $url rather than displaying the normal page
*
* @param string $url
* @param string|int $responsecode HTTP status code
*/
public function redirect( $url, $responsecode = '302' ) {
# Strip newlines as a paranoia check for header injection in PHP<5.1.2
$this->mRedirect = str_replace( "\n", '', $url );
$this->mRedirectCode = (string)$responsecode;
}
/**
* Get the URL to redirect to, or an empty string if not redirect URL set
*
* @return string
*/
public function getRedirect() {
return $this->mRedirect;
}
/**
* Set the copyright URL to send with the output.
* Empty string to omit, null to reset.
*
* @since 1.26
*
* @param string|null $url
*/
public function setCopyrightUrl( $url ) {
$this->copyrightUrl = $url;
}
/**
* Set the HTTP status code to send with the output.
*
* @param int $statusCode
*/
public function setStatusCode( $statusCode ) {
$this->mStatusCode = $statusCode;
}
/**
* Add a new "<meta>" tag
* To add an http-equiv meta tag, precede the name with "http:"
*
* @param string $name Name of the meta tag
* @param string $val Value of the meta tag
*/
public function addMeta( $name, $val ) {
$this->mMetatags[] = [ $name, $val ];
}
/**
* Returns the current <meta> tags
*
* @since 1.25
* @return array
*/
public function getMetaTags() {
return $this->mMetatags;
}
/**
* Add a new \<link\> tag to the page header.
*
* Note: use setCanonicalUrl() for rel=canonical.
*
* @param array $linkarr Associative array of attributes.
*/
public function addLink( array $linkarr ) {
$this->mLinktags[] = $linkarr;
}
/**
* Returns the current <link> tags
*
* @since 1.25
* @return array
*/
public function getLinkTags() {
return $this->mLinktags;
}
/**
* Set the URL to be used for the <link rel=canonical>. This should be used
* in preference to addLink(), to avoid duplicate link tags.
* @param string $url
*/
public function setCanonicalUrl( $url ) {
$this->mCanonicalUrl = $url;
}
/**
* Returns the URL to be used for the <link rel=canonical> if
* one is set.
*
* @since 1.25
* @return bool|string
*/
public function getCanonicalUrl() {
return $this->mCanonicalUrl;
}
/**
* Add raw HTML to the list of scripts (including \<script\> tag, etc.)
* Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
* if possible.
*
* @param string $script Raw HTML
* @param-taint $script exec_html
*/
public function addScript( $script ) {
$this->mScripts .= $script;
}
/**
* Add a JavaScript file to be loaded as `<script>` on this page.
*
* Internal use only. Use OutputPage::addModules() if possible.
*
* @param string $file URL to file (absolute path, protocol-relative, or full url)
* @param string|null $unused Previously used to change the cache-busting query parameter
*/
public function addScriptFile( $file, $unused = null ) {
$this->addScript( Html::linkedScript( $file ) );
}
/**
* Add a self-contained script tag with the given contents
* Internal use only. Use OutputPage::addModules() if possible.
*
* @param string $script JavaScript text, no script tags
* @param-taint $script exec_html
*/
public function addInlineScript( $script ) {
$this->mScripts .= Html::inlineScript( "\n$script\n" ) . "\n";
}
/**
* Filter an array of modules to remove insufficiently trustworthy members, and modules
* which are no longer registered (eg a page is cached before an extension is disabled)
* @param string[] $modules
* @param string|null $position Unused
* @param string $type
* @return string[]
*/
protected function filterModules( array $modules, $position = null,
$type = RL\Module::TYPE_COMBINED
) {
$resourceLoader = $this->getResourceLoader();
$filteredModules = [];
foreach ( $modules as $val ) {
$module = $resourceLoader->getModule( $val );
if ( $module instanceof RL\Module
&& $module->getOrigin() <= $this->getAllowedModules( $type )
) {
$filteredModules[] = $val;
}
}
return $filteredModules;
}
/**
* Get the list of modules to include on this page
*
* @param bool $filter Whether to filter out insufficiently trustworthy modules
* @param string|null $position Unused
* @param string $param
* @param string $type
* @return string[] Array of module names
*/
public function getModules( $filter = false, $position = null, $param = 'mModules',
$type = RL\Module::TYPE_COMBINED
) {
$modules = array_values( array_unique( $this->$param ) );
return $filter
? $this->filterModules( $modules, null, $type )
: $modules;
}
/**
* Load one or more ResourceLoader modules on this page.
*
* @param string|array $modules Module name (string) or array of module names
*/
public function addModules( $modules ) {
$this->mModules = array_merge( $this->mModules, (array)$modules );
}
/**
* Get the list of style-only modules to load on this page.
*
* @param bool $filter
* @param string|null $position Unused
* @return string[] Array of module names
*/
public function getModuleStyles( $filter = false, $position = null ) {
return $this->getModules( $filter, null, 'mModuleStyles',
RL\Module::TYPE_STYLES
);
}
/**
* Load the styles of one or more style-only ResourceLoader modules on this page.
*
* Module styles added through this function will be loaded as a stylesheet,
* using a standard `<link rel=stylesheet>` HTML tag, rather than as a combined
* Javascript and CSS package. Thus, they will even load when JavaScript is disabled.
*
* @param string|array $modules Module name (string) or array of module names
*/
public function addModuleStyles( $modules ) {
$this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
}
/**
* @return null|string ResourceLoader target
*/
public function getTarget() {
return $this->mTarget;
}
/**
* Force the given Content object for the given page, for things like page preview.
* @see self::addContentOverrideCallback()
* @since 1.32
* @param LinkTarget|PageReference $target
* @param Content $content
*/
public function addContentOverride( $target, Content $content ) {
if ( !$this->contentOverrides ) {
// Register a callback for $this->contentOverrides on the first call
$this->addContentOverrideCallback( function ( $target ) {
$key = $target->getNamespace() . ':' . $target->getDBkey();
return $this->contentOverrides[$key] ?? null;
} );
}
$key = $target->getNamespace() . ':' . $target->getDBkey();
$this->contentOverrides[$key] = $content;
}
/**
* Add a callback for mapping from a Title to a Content object, for things
* like page preview.
* @see RL\Context::getContentOverrideCallback()
* @since 1.32
* @param callable $callback
*/
public function addContentOverrideCallback( callable $callback ) {
$this->contentOverrideCallbacks[] = $callback;
}
/**
* Add a class to the <html> element. This should rarely be used.
* Instead use OutputPage::addBodyClasses() if possible.
*
* @unstable Experimental since 1.35. Prefer OutputPage::addBodyClasses()
* @param string|string[] $classes One or more classes to add
*/
public function addHtmlClasses( $classes ) {
$this->mAdditionalHtmlClasses = array_merge( $this->mAdditionalHtmlClasses, (array)$classes );
}
/**
* Get an array of head items
*
* @return string[]
*/
public function getHeadItemsArray() {
return $this->mHeadItems;
}
/**
* Add or replace a head item to the output
*
* Whenever possible, use more specific options like ResourceLoader modules,
* OutputPage::addLink(), OutputPage::addMeta() and OutputPage::addFeedLink()
* Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
* OutputPage::addInlineScript() and OutputPage::addInlineStyle()
* This would be your very LAST fallback.
*
* @param string $name Item name
* @param string $value Raw HTML
* @param-taint $value exec_html
*/
public function addHeadItem( $name, $value ) {
$this->mHeadItems[$name] = $value;
}
/**
* Add one or more head items to the output
*
* @since 1.28
* @param string|string[] $values Raw HTML
* @param-taint $values exec_html
*/
public function addHeadItems( $values ) {
$this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
}
/**
* Check if the header item $name is already set
*
* @param string $name Item name
* @return bool
*/
public function hasHeadItem( $name ) {
return isset( $this->mHeadItems[$name] );
}
/**
* Add a class to the <body> element
*
* @since 1.30
* @param string|string[] $classes One or more classes to add
*/
public function addBodyClasses( $classes ) {
$this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
}
/**
* Set whether the output should only contain the body of the article,
* without any skin, sidebar, etc.
* Used e.g. when calling with "action=render".
*
* @param bool $only Whether to output only the body of the article
*/
public function setArticleBodyOnly( $only ) {
$this->mArticleBodyOnly = $only;
}
/**
* Return whether the output will contain only the body of the article
*
* @return bool
*/
public function getArticleBodyOnly() {
return $this->mArticleBodyOnly;
}
/**
* Set an additional output property
* @since 1.21
*
* @param string $name
* @param mixed $value
*/
public function setProperty( $name, $value ) {
$this->mProperties[$name] = $value;
}
/**
* Get an additional output property
* @since 1.21
*
* @param string $name
* @return mixed Property value or null if not found
*/
public function getProperty( $name ) {
return $this->mProperties[$name] ?? null;
}
/**
* checkLastModified tells the client to use the client-cached page if
* possible. If successful, the OutputPage is disabled so that
* any future call to OutputPage->output() have no effect.
*
* Side effect: sets mLastModified for Last-Modified header
*
* @param string $timestamp
*
* @return bool True if cache-ok headers was sent.
*/
public function checkLastModified( $timestamp ) {
if ( !$timestamp || $timestamp == '19700101000000' ) {
wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP" );
return false;
}
$config = $this->getConfig();
if ( !$config->get( MainConfigNames::CachePages ) ) {
wfDebug( __METHOD__ . ": CACHE DISABLED" );
return false;
}
$timestamp = wfTimestamp( TS_MW, $timestamp );
$modifiedTimes = [
'page' => $timestamp,
'user' => $this->getUser()->getTouched(),
'epoch' => $config->get( MainConfigNames::CacheEpoch )
];
if ( $config->get( MainConfigNames::UseCdn ) ) {
$modifiedTimes['sepoch'] = wfTimestamp( TS_MW, $this->getCdnCacheEpoch(
time(),
$config->get( MainConfigNames::CdnMaxAge )
) );
}
$this->getHookRunner()->onOutputPageCheckLastModified( $modifiedTimes, $this );
$maxModified = max( $modifiedTimes );
$this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
$clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
if ( $clientHeader === false ) {
wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
return false;
}
# IE sends sizes after the date like this:
# Wed, 20 Aug 2003 06:51:19 GMT; length=5202
# this breaks strtotime().
$clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
// E_STRICT system time warnings
AtEase::suppressWarnings();
$clientHeaderTime = strtotime( $clientHeader );
AtEase::restoreWarnings();
if ( !$clientHeaderTime ) {
wfDebug( __METHOD__
. ": unable to parse the client's If-Modified-Since header: $clientHeader" );
return false;
}
$clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
# Make debug info
$info = '';
foreach ( $modifiedTimes as $name => $value ) {
if ( $info !== '' ) {
$info .= ', ';
}
$info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
}
wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
wfDebug( __METHOD__ . ": effective Last-Modified: " .
wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
if ( $clientHeaderTime < $maxModified ) {
wfDebug( __METHOD__ . ": STALE, $info", 'private' );
return false;
}
# Not modified
# Give a 304 Not Modified response code and disable body output
wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
ini_set( 'zlib.output_compression', 0 );
$this->getRequest()->response()->statusHeader( 304 );
$this->sendCacheControl();
$this->disable();
// Don't output a compressed blob when using ob_gzhandler;
// it's technically against HTTP spec and seems to confuse
// Firefox when the response gets split over two packets.
wfResetOutputBuffers( false );
return true;
}
/**
* @param int $reqTime Time of request (eg. now)
* @param int $maxAge Cache TTL in seconds
* @return int Timestamp
*/
private function getCdnCacheEpoch( $reqTime, $maxAge ) {
// Ensure Last-Modified is never more than $wgCdnMaxAge in the past,
// because even if the wiki page content hasn't changed since, static
// resources may have changed (skin HTML, interface messages, urls, etc.)
// and must roll-over in a timely manner (T46570)
return $reqTime - $maxAge;
}
/**
* Override the last modified timestamp
*
* @param string $timestamp New timestamp, in a format readable by
* wfTimestamp()
*/
public function setLastModified( $timestamp ) {
$this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
}
/**
* Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
*
* @param string $policy The literal string to output as the contents of
* the meta tag. Will be parsed according to the spec and output in
* standardized form.
*/
public function setRobotPolicy( $policy ) {
$policy = Article::formatRobotPolicy( $policy );
if ( isset( $policy['index'] ) ) {
$this->setIndexPolicy( $policy['index'] );
}
if ( isset( $policy['follow'] ) ) {
$this->setFollowPolicy( $policy['follow'] );
}
}
/**
* Get the current robot policy for the page as a string in the form
* <index policy>,<follow policy>.
*
* @return string
*/
public function getRobotPolicy() {
return "{$this->mIndexPolicy},{$this->mFollowPolicy}";
}
/**
* Format an array of robots options as a string of directives.
*
* @return string The robots policy options.
*/
private function formatRobotsOptions(): string {
$options = $this->mRobotsOptions;
// Check if options array has any non-integer keys.
if ( count( array_filter( array_keys( $options ), 'is_string' ) ) > 0 ) {
// Robots meta tags can have directives that are single strings or
// have parameters that should be formatted like <directive>:<setting>.
// If the options keys are strings, format them accordingly.
// https://developers.google.com/search/docs/advanced/robots/robots_meta_tag
array_walk( $options, static function ( &$value, $key ) {
$value = is_string( $key ) ? "{$key}:{$value}" : "{$value}";
} );
}