a5f9c18151640b16351f76f0a8e8c0322e9e6095
[lhc/web/wiklou.git] / includes / OutputPage.php
1 <?php
2 /**
3 * Preparation for the final page rendering.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\Logger\LoggerFactory;
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Session\SessionManager;
26 use WrappedString\WrappedString;
27 use WrappedString\WrappedStringList;
28
29 /**
30 * This class should be covered by a general architecture document which does
31 * not exist as of January 2011. This is one of the Core classes and should
32 * be read at least once by any new developers.
33 *
34 * This class is used to prepare the final rendering. A skin is then
35 * applied to the output parameters (links, javascript, html, categories ...).
36 *
37 * @todo FIXME: Another class handles sending the whole page to the client.
38 *
39 * Some comments comes from a pairing session between Zak Greant and Antoine Musso
40 * in November 2010.
41 *
42 * @todo document
43 */
44 class OutputPage extends ContextSource {
45 /** @var array Should be private. Used with addMeta() which adds "<meta>" */
46 protected $mMetatags = [];
47
48 /** @var array */
49 protected $mLinktags = [];
50
51 /** @var bool */
52 protected $mCanonicalUrl = false;
53
54 /**
55 * @var array Additional stylesheets. Looks like this is for extensions.
56 * Might be replaced by ResourceLoader.
57 */
58 protected $mExtStyles = [];
59
60 /**
61 * @var string Should be private - has getter and setter. Contains
62 * the HTML title */
63 public $mPagetitle = '';
64
65 /**
66 * @var string Contains all of the "<body>" content. Should be private we
67 * got set/get accessors and the append() method.
68 */
69 public $mBodytext = '';
70
71 /** @var string Stores contents of "<title>" tag */
72 private $mHTMLtitle = '';
73
74 /**
75 * @var bool Is the displayed content related to the source of the
76 * corresponding wiki article.
77 */
78 private $mIsarticle = false;
79
80 /** @var bool Stores "article flag" toggle. */
81 private $mIsArticleRelated = true;
82
83 /**
84 * @var bool We have to set isPrintable(). Some pages should
85 * never be printed (ex: redirections).
86 */
87 private $mPrintable = false;
88
89 /**
90 * @var array Contains the page subtitle. Special pages usually have some
91 * links here. Don't confuse with site subtitle added by skins.
92 */
93 private $mSubtitle = [];
94
95 /** @var string */
96 public $mRedirect = '';
97
98 /** @var int */
99 protected $mStatusCode;
100
101 /**
102 * @var string Used for sending cache control.
103 * The whole caching system should probably be moved into its own class.
104 */
105 protected $mLastModified = '';
106
107 /** @var array */
108 protected $mCategoryLinks = [];
109
110 /** @var array */
111 protected $mCategories = [
112 'hidden' => [],
113 'normal' => [],
114 ];
115
116 /** @var array */
117 protected $mIndicators = [];
118
119 /** @var array Array of Interwiki Prefixed (non DB key) Titles (e.g. 'fr:Test page') */
120 private $mLanguageLinks = [];
121
122 /**
123 * Used for JavaScript (predates ResourceLoader)
124 * @todo We should split JS / CSS.
125 * mScripts content is inserted as is in "<head>" by Skin. This might
126 * contain either a link to a stylesheet or inline CSS.
127 */
128 private $mScripts = '';
129
130 /** @var string Inline CSS styles. Use addInlineStyle() sparingly */
131 protected $mInlineStyles = '';
132
133 /**
134 * @var string Used by skin template.
135 * Example: $tpl->set( 'displaytitle', $out->mPageLinkTitle );
136 */
137 public $mPageLinkTitle = '';
138
139 /** @var array Array of elements in "<head>". Parser might add its own headers! */
140 protected $mHeadItems = [];
141
142 /** @var array Additional <body> classes; there are also <body> classes from other sources */
143 protected $mAdditionalBodyClasses = [];
144
145 /** @var array */
146 protected $mModules = [];
147
148 /** @var array */
149 protected $mModuleScripts = [];
150
151 /** @var array */
152 protected $mModuleStyles = [];
153
154 /** @var ResourceLoader */
155 protected $mResourceLoader;
156
157 /** @var ResourceLoaderClientHtml */
158 private $rlClient;
159
160 /** @var ResourceLoaderContext */
161 private $rlClientContext;
162
163 /** @var string */
164 private $rlUserModuleState;
165
166 /** @var array */
167 private $rlExemptStyleModules;
168
169 /** @var array */
170 protected $mJsConfigVars = [];
171
172 /** @var array */
173 protected $mTemplateIds = [];
174
175 /** @var array */
176 protected $mImageTimeKeys = [];
177
178 /** @var string */
179 public $mRedirectCode = '';
180
181 protected $mFeedLinksAppendQuery = null;
182
183 /** @var array
184 * What level of 'untrustworthiness' is allowed in CSS/JS modules loaded on this page?
185 * @see ResourceLoaderModule::$origin
186 * ResourceLoaderModule::ORIGIN_ALL is assumed unless overridden;
187 */
188 protected $mAllowedModules = [
189 ResourceLoaderModule::TYPE_COMBINED => ResourceLoaderModule::ORIGIN_ALL,
190 ];
191
192 /** @var bool Whether output is disabled. If this is true, the 'output' method will do nothing. */
193 protected $mDoNothing = false;
194
195 // Parser related.
196
197 /** @var int */
198 protected $mContainsNewMagic = 0;
199
200 /**
201 * lazy initialised, use parserOptions()
202 * @var ParserOptions
203 */
204 protected $mParserOptions = null;
205
206 /**
207 * Handles the Atom / RSS links.
208 * We probably only support Atom in 2011.
209 * @see $wgAdvertisedFeedTypes
210 */
211 private $mFeedLinks = [];
212
213 // Gwicke work on squid caching? Roughly from 2003.
214 protected $mEnableClientCache = true;
215
216 /** @var bool Flag if output should only contain the body of the article. */
217 private $mArticleBodyOnly = false;
218
219 /** @var bool */
220 protected $mNewSectionLink = false;
221
222 /** @var bool */
223 protected $mHideNewSectionLink = false;
224
225 /**
226 * @var bool Comes from the parser. This was probably made to load CSS/JS
227 * only if we had "<gallery>". Used directly in CategoryPage.php.
228 * Looks like ResourceLoader can replace this.
229 */
230 public $mNoGallery = false;
231
232 /** @var string */
233 private $mPageTitleActionText = '';
234
235 /** @var int Cache stuff. Looks like mEnableClientCache */
236 protected $mCdnMaxage = 0;
237 /** @var int Upper limit on mCdnMaxage */
238 protected $mCdnMaxageLimit = INF;
239
240 /**
241 * @var bool Controls if anti-clickjacking / frame-breaking headers will
242 * be sent. This should be done for pages where edit actions are possible.
243 * Setters: $this->preventClickjacking() and $this->allowClickjacking().
244 */
245 protected $mPreventClickjacking = true;
246
247 /** @var int To include the variable {{REVISIONID}} */
248 private $mRevisionId = null;
249
250 /** @var string */
251 private $mRevisionTimestamp = null;
252
253 /** @var array */
254 protected $mFileVersion = null;
255
256 /**
257 * @var array An array of stylesheet filenames (relative from skins path),
258 * with options for CSS media, IE conditions, and RTL/LTR direction.
259 * For internal use; add settings in the skin via $this->addStyle()
260 *
261 * Style again! This seems like a code duplication since we already have
262 * mStyles. This is what makes Open Source amazing.
263 */
264 protected $styles = [];
265
266 private $mIndexPolicy = 'index';
267 private $mFollowPolicy = 'follow';
268 private $mVaryHeader = [
269 'Accept-Encoding' => [ 'match=gzip' ],
270 ];
271
272 /**
273 * If the current page was reached through a redirect, $mRedirectedFrom contains the Title
274 * of the redirect.
275 *
276 * @var Title
277 */
278 private $mRedirectedFrom = null;
279
280 /**
281 * Additional key => value data
282 */
283 private $mProperties = [];
284
285 /**
286 * @var string|null ResourceLoader target for load.php links. If null, will be omitted
287 */
288 private $mTarget = null;
289
290 /**
291 * @var bool Whether parser output contains a table of contents
292 */
293 private $mEnableTOC = false;
294
295 /**
296 * @var bool Whether parser output should contain section edit links
297 */
298 private $mEnableSectionEditLinks = true;
299
300 /**
301 * @var string|null The URL to send in a <link> element with rel=license
302 */
303 private $copyrightUrl;
304
305 /** @var array Profiling data */
306 private $limitReportJSData = [];
307
308 /**
309 * Link: header contents
310 */
311 private $mLinkHeader = [];
312
313 /**
314 * Constructor for OutputPage. This should not be called directly.
315 * Instead a new RequestContext should be created and it will implicitly create
316 * a OutputPage tied to that context.
317 * @param IContextSource $context
318 */
319 function __construct( IContextSource $context ) {
320 $this->setContext( $context );
321 }
322
323 /**
324 * Redirect to $url rather than displaying the normal page
325 *
326 * @param string $url URL
327 * @param string $responsecode HTTP status code
328 */
329 public function redirect( $url, $responsecode = '302' ) {
330 # Strip newlines as a paranoia check for header injection in PHP<5.1.2
331 $this->mRedirect = str_replace( "\n", '', $url );
332 $this->mRedirectCode = $responsecode;
333 }
334
335 /**
336 * Get the URL to redirect to, or an empty string if not redirect URL set
337 *
338 * @return string
339 */
340 public function getRedirect() {
341 return $this->mRedirect;
342 }
343
344 /**
345 * Set the copyright URL to send with the output.
346 * Empty string to omit, null to reset.
347 *
348 * @since 1.26
349 *
350 * @param string|null $url
351 */
352 public function setCopyrightUrl( $url ) {
353 $this->copyrightUrl = $url;
354 }
355
356 /**
357 * Set the HTTP status code to send with the output.
358 *
359 * @param int $statusCode
360 */
361 public function setStatusCode( $statusCode ) {
362 $this->mStatusCode = $statusCode;
363 }
364
365 /**
366 * Add a new "<meta>" tag
367 * To add an http-equiv meta tag, precede the name with "http:"
368 *
369 * @param string $name Tag name
370 * @param string $val Tag value
371 */
372 function addMeta( $name, $val ) {
373 array_push( $this->mMetatags, [ $name, $val ] );
374 }
375
376 /**
377 * Returns the current <meta> tags
378 *
379 * @since 1.25
380 * @return array
381 */
382 public function getMetaTags() {
383 return $this->mMetatags;
384 }
385
386 /**
387 * Add a new \<link\> tag to the page header.
388 *
389 * Note: use setCanonicalUrl() for rel=canonical.
390 *
391 * @param array $linkarr Associative array of attributes.
392 */
393 function addLink( array $linkarr ) {
394 array_push( $this->mLinktags, $linkarr );
395 }
396
397 /**
398 * Returns the current <link> tags
399 *
400 * @since 1.25
401 * @return array
402 */
403 public function getLinkTags() {
404 return $this->mLinktags;
405 }
406
407 /**
408 * Add a new \<link\> with "rel" attribute set to "meta"
409 *
410 * @param array $linkarr Associative array mapping attribute names to their
411 * values, both keys and values will be escaped, and the
412 * "rel" attribute will be automatically added
413 */
414 function addMetadataLink( array $linkarr ) {
415 $linkarr['rel'] = $this->getMetadataAttribute();
416 $this->addLink( $linkarr );
417 }
418
419 /**
420 * Set the URL to be used for the <link rel=canonical>. This should be used
421 * in preference to addLink(), to avoid duplicate link tags.
422 * @param string $url
423 */
424 function setCanonicalUrl( $url ) {
425 $this->mCanonicalUrl = $url;
426 }
427
428 /**
429 * Returns the URL to be used for the <link rel=canonical> if
430 * one is set.
431 *
432 * @since 1.25
433 * @return bool|string
434 */
435 public function getCanonicalUrl() {
436 return $this->mCanonicalUrl;
437 }
438
439 /**
440 * Get the value of the "rel" attribute for metadata links
441 *
442 * @return string
443 */
444 public function getMetadataAttribute() {
445 # note: buggy CC software only reads first "meta" link
446 static $haveMeta = false;
447 if ( $haveMeta ) {
448 return 'alternate meta';
449 } else {
450 $haveMeta = true;
451 return 'meta';
452 }
453 }
454
455 /**
456 * Add raw HTML to the list of scripts (including \<script\> tag, etc.)
457 * Internal use only. Use OutputPage::addModules() or OutputPage::addJsConfigVars()
458 * if possible.
459 *
460 * @param string $script Raw HTML
461 */
462 function addScript( $script ) {
463 $this->mScripts .= $script;
464 }
465
466 /**
467 * Register and add a stylesheet from an extension directory.
468 *
469 * @deprecated since 1.27 use addModuleStyles() or addStyle() instead
470 * @param string $url Path to sheet. Provide either a full url (beginning
471 * with 'http', etc) or a relative path from the document root
472 * (beginning with '/'). Otherwise it behaves identically to
473 * addStyle() and draws from the /skins folder.
474 */
475 public function addExtensionStyle( $url ) {
476 wfDeprecated( __METHOD__, '1.27' );
477 array_push( $this->mExtStyles, $url );
478 }
479
480 /**
481 * Get all styles added by extensions
482 *
483 * @deprecated since 1.27
484 * @return array
485 */
486 function getExtStyle() {
487 wfDeprecated( __METHOD__, '1.27' );
488 return $this->mExtStyles;
489 }
490
491 /**
492 * Add a JavaScript file out of skins/common, or a given relative path.
493 * Internal use only. Use OutputPage::addModules() if possible.
494 *
495 * @param string $file Filename in skins/common or complete on-server path
496 * (/foo/bar.js)
497 * @param string $version Style version of the file. Defaults to $wgStyleVersion
498 */
499 public function addScriptFile( $file, $version = null ) {
500 // See if $file parameter is an absolute URL or begins with a slash
501 if ( substr( $file, 0, 1 ) == '/' || preg_match( '#^[a-z]*://#i', $file ) ) {
502 $path = $file;
503 } else {
504 $path = $this->getConfig()->get( 'StylePath' ) . "/common/{$file}";
505 }
506 if ( is_null( $version ) ) {
507 $version = $this->getConfig()->get( 'StyleVersion' );
508 }
509 $this->addScript( Html::linkedScript( wfAppendQuery( $path, $version ) ) );
510 }
511
512 /**
513 * Add a self-contained script tag with the given contents
514 * Internal use only. Use OutputPage::addModules() if possible.
515 *
516 * @param string $script JavaScript text, no script tags
517 */
518 public function addInlineScript( $script ) {
519 $this->mScripts .= Html::inlineScript( $script );
520 }
521
522 /**
523 * Filter an array of modules to remove insufficiently trustworthy members, and modules
524 * which are no longer registered (eg a page is cached before an extension is disabled)
525 * @param array $modules
526 * @param string|null $position If not null, only return modules with this position
527 * @param string $type
528 * @return array
529 */
530 protected function filterModules( array $modules, $position = null,
531 $type = ResourceLoaderModule::TYPE_COMBINED
532 ) {
533 $resourceLoader = $this->getResourceLoader();
534 $filteredModules = [];
535 foreach ( $modules as $val ) {
536 $module = $resourceLoader->getModule( $val );
537 if ( $module instanceof ResourceLoaderModule
538 && $module->getOrigin() <= $this->getAllowedModules( $type )
539 && ( is_null( $position ) || $module->getPosition() == $position )
540 ) {
541 if ( $this->mTarget && !in_array( $this->mTarget, $module->getTargets() ) ) {
542 $this->warnModuleTargetFilter( $module->getName() );
543 continue;
544 }
545 $filteredModules[] = $val;
546 }
547 }
548 return $filteredModules;
549 }
550
551 private function warnModuleTargetFilter( $moduleName ) {
552 static $warnings = [];
553 if ( isset( $warnings[$this->mTarget][$moduleName] ) ) {
554 return;
555 }
556 $warnings[$this->mTarget][$moduleName] = true;
557 $this->getResourceLoader()->getLogger()->debug(
558 'Module "{module}" not loadable on target "{target}".',
559 [
560 'module' => $moduleName,
561 'target' => $this->mTarget,
562 ]
563 );
564 }
565
566 /**
567 * Get the list of modules to include on this page
568 *
569 * @param bool $filter Whether to filter out insufficiently trustworthy modules
570 * @param string|null $position If not null, only return modules with this position
571 * @param string $param
572 * @param string $type
573 * @return array Array of module names
574 */
575 public function getModules( $filter = false, $position = null, $param = 'mModules',
576 $type = ResourceLoaderModule::TYPE_COMBINED
577 ) {
578 $modules = array_values( array_unique( $this->$param ) );
579 return $filter
580 ? $this->filterModules( $modules, $position, $type )
581 : $modules;
582 }
583
584 /**
585 * Add one or more modules recognized by ResourceLoader. Modules added
586 * through this function will be loaded by ResourceLoader when the
587 * page loads.
588 *
589 * @param string|array $modules Module name (string) or array of module names
590 */
591 public function addModules( $modules ) {
592 $this->mModules = array_merge( $this->mModules, (array)$modules );
593 }
594
595 /**
596 * Get the list of module JS to include on this page
597 *
598 * @param bool $filter
599 * @param string|null $position
600 * @return array Array of module names
601 */
602 public function getModuleScripts( $filter = false, $position = null ) {
603 return $this->getModules( $filter, $position, 'mModuleScripts',
604 ResourceLoaderModule::TYPE_SCRIPTS
605 );
606 }
607
608 /**
609 * Add only JS of one or more modules recognized by ResourceLoader. Module
610 * scripts added through this function will be loaded by ResourceLoader when
611 * the page loads.
612 *
613 * @param string|array $modules Module name (string) or array of module names
614 */
615 public function addModuleScripts( $modules ) {
616 $this->mModuleScripts = array_merge( $this->mModuleScripts, (array)$modules );
617 }
618
619 /**
620 * Get the list of module CSS to include on this page
621 *
622 * @param bool $filter
623 * @param string|null $position
624 * @return array Array of module names
625 */
626 public function getModuleStyles( $filter = false, $position = null ) {
627 return $this->getModules( $filter, $position, 'mModuleStyles',
628 ResourceLoaderModule::TYPE_STYLES
629 );
630 }
631
632 /**
633 * Add only CSS of one or more modules recognized by ResourceLoader.
634 *
635 * Module styles added through this function will be added using standard link CSS
636 * tags, rather than as a combined Javascript and CSS package. Thus, they will
637 * load when JavaScript is disabled (unless CSS also happens to be disabled).
638 *
639 * @param string|array $modules Module name (string) or array of module names
640 */
641 public function addModuleStyles( $modules ) {
642 $this->mModuleStyles = array_merge( $this->mModuleStyles, (array)$modules );
643 }
644
645 /**
646 * @return null|string ResourceLoader target
647 */
648 public function getTarget() {
649 return $this->mTarget;
650 }
651
652 /**
653 * Sets ResourceLoader target for load.php links. If null, will be omitted
654 *
655 * @param string|null $target
656 */
657 public function setTarget( $target ) {
658 $this->mTarget = $target;
659 }
660
661 /**
662 * Get an array of head items
663 *
664 * @return array
665 */
666 function getHeadItemsArray() {
667 return $this->mHeadItems;
668 }
669
670 /**
671 * Add or replace a head item to the output
672 *
673 * Whenever possible, use more specific options like ResourceLoader modules,
674 * OutputPage::addLink(), OutputPage::addMetaLink() and OutputPage::addFeedLink()
675 * Fallback options for those are: OutputPage::addStyle, OutputPage::addScript(),
676 * OutputPage::addInlineScript() and OutputPage::addInlineStyle()
677 * This would be your very LAST fallback.
678 *
679 * @param string $name Item name
680 * @param string $value Raw HTML
681 */
682 public function addHeadItem( $name, $value ) {
683 $this->mHeadItems[$name] = $value;
684 }
685
686 /**
687 * Add one or more head items to the output
688 *
689 * @since 1.28
690 * @param string|string[] $values Raw HTML
691 */
692 public function addHeadItems( $values ) {
693 $this->mHeadItems = array_merge( $this->mHeadItems, (array)$values );
694 }
695
696 /**
697 * Check if the header item $name is already set
698 *
699 * @param string $name Item name
700 * @return bool
701 */
702 public function hasHeadItem( $name ) {
703 return isset( $this->mHeadItems[$name] );
704 }
705
706 /**
707 * Add a class to the <body> element
708 *
709 * @since 1.30
710 * @param string|string[] $classes One or more classes to add
711 */
712 public function addBodyClasses( $classes ) {
713 $this->mAdditionalBodyClasses = array_merge( $this->mAdditionalBodyClasses, (array)$classes );
714 }
715
716 /**
717 * @deprecated since 1.28 Obsolete - wgUseETag experiment was removed.
718 * @param string $tag
719 */
720 public function setETag( $tag ) {
721 }
722
723 /**
724 * Set whether the output should only contain the body of the article,
725 * without any skin, sidebar, etc.
726 * Used e.g. when calling with "action=render".
727 *
728 * @param bool $only Whether to output only the body of the article
729 */
730 public function setArticleBodyOnly( $only ) {
731 $this->mArticleBodyOnly = $only;
732 }
733
734 /**
735 * Return whether the output will contain only the body of the article
736 *
737 * @return bool
738 */
739 public function getArticleBodyOnly() {
740 return $this->mArticleBodyOnly;
741 }
742
743 /**
744 * Set an additional output property
745 * @since 1.21
746 *
747 * @param string $name
748 * @param mixed $value
749 */
750 public function setProperty( $name, $value ) {
751 $this->mProperties[$name] = $value;
752 }
753
754 /**
755 * Get an additional output property
756 * @since 1.21
757 *
758 * @param string $name
759 * @return mixed Property value or null if not found
760 */
761 public function getProperty( $name ) {
762 if ( isset( $this->mProperties[$name] ) ) {
763 return $this->mProperties[$name];
764 } else {
765 return null;
766 }
767 }
768
769 /**
770 * checkLastModified tells the client to use the client-cached page if
771 * possible. If successful, the OutputPage is disabled so that
772 * any future call to OutputPage->output() have no effect.
773 *
774 * Side effect: sets mLastModified for Last-Modified header
775 *
776 * @param string $timestamp
777 *
778 * @return bool True if cache-ok headers was sent.
779 */
780 public function checkLastModified( $timestamp ) {
781 if ( !$timestamp || $timestamp == '19700101000000' ) {
782 wfDebug( __METHOD__ . ": CACHE DISABLED, NO TIMESTAMP\n" );
783 return false;
784 }
785 $config = $this->getConfig();
786 if ( !$config->get( 'CachePages' ) ) {
787 wfDebug( __METHOD__ . ": CACHE DISABLED\n" );
788 return false;
789 }
790
791 $timestamp = wfTimestamp( TS_MW, $timestamp );
792 $modifiedTimes = [
793 'page' => $timestamp,
794 'user' => $this->getUser()->getTouched(),
795 'epoch' => $config->get( 'CacheEpoch' )
796 ];
797 if ( $config->get( 'UseSquid' ) ) {
798 // T46570: the core page itself may not change, but resources might
799 $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $config->get( 'SquidMaxage' ) );
800 }
801 Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this ] );
802
803 $maxModified = max( $modifiedTimes );
804 $this->mLastModified = wfTimestamp( TS_RFC2822, $maxModified );
805
806 $clientHeader = $this->getRequest()->getHeader( 'If-Modified-Since' );
807 if ( $clientHeader === false ) {
808 wfDebug( __METHOD__ . ": client did not send If-Modified-Since header", 'private' );
809 return false;
810 }
811
812 # IE sends sizes after the date like this:
813 # Wed, 20 Aug 2003 06:51:19 GMT; length=5202
814 # this breaks strtotime().
815 $clientHeader = preg_replace( '/;.*$/', '', $clientHeader );
816
817 MediaWiki\suppressWarnings(); // E_STRICT system time bitching
818 $clientHeaderTime = strtotime( $clientHeader );
819 MediaWiki\restoreWarnings();
820 if ( !$clientHeaderTime ) {
821 wfDebug( __METHOD__
822 . ": unable to parse the client's If-Modified-Since header: $clientHeader\n" );
823 return false;
824 }
825 $clientHeaderTime = wfTimestamp( TS_MW, $clientHeaderTime );
826
827 # Make debug info
828 $info = '';
829 foreach ( $modifiedTimes as $name => $value ) {
830 if ( $info !== '' ) {
831 $info .= ', ';
832 }
833 $info .= "$name=" . wfTimestamp( TS_ISO_8601, $value );
834 }
835
836 wfDebug( __METHOD__ . ": client sent If-Modified-Since: " .
837 wfTimestamp( TS_ISO_8601, $clientHeaderTime ), 'private' );
838 wfDebug( __METHOD__ . ": effective Last-Modified: " .
839 wfTimestamp( TS_ISO_8601, $maxModified ), 'private' );
840 if ( $clientHeaderTime < $maxModified ) {
841 wfDebug( __METHOD__ . ": STALE, $info", 'private' );
842 return false;
843 }
844
845 # Not modified
846 # Give a 304 Not Modified response code and disable body output
847 wfDebug( __METHOD__ . ": NOT MODIFIED, $info", 'private' );
848 ini_set( 'zlib.output_compression', 0 );
849 $this->getRequest()->response()->statusHeader( 304 );
850 $this->sendCacheControl();
851 $this->disable();
852
853 // Don't output a compressed blob when using ob_gzhandler;
854 // it's technically against HTTP spec and seems to confuse
855 // Firefox when the response gets split over two packets.
856 wfClearOutputBuffers();
857
858 return true;
859 }
860
861 /**
862 * Override the last modified timestamp
863 *
864 * @param string $timestamp New timestamp, in a format readable by
865 * wfTimestamp()
866 */
867 public function setLastModified( $timestamp ) {
868 $this->mLastModified = wfTimestamp( TS_RFC2822, $timestamp );
869 }
870
871 /**
872 * Set the robot policy for the page: <http://www.robotstxt.org/meta.html>
873 *
874 * @param string $policy The literal string to output as the contents of
875 * the meta tag. Will be parsed according to the spec and output in
876 * standardized form.
877 * @return null
878 */
879 public function setRobotPolicy( $policy ) {
880 $policy = Article::formatRobotPolicy( $policy );
881
882 if ( isset( $policy['index'] ) ) {
883 $this->setIndexPolicy( $policy['index'] );
884 }
885 if ( isset( $policy['follow'] ) ) {
886 $this->setFollowPolicy( $policy['follow'] );
887 }
888 }
889
890 /**
891 * Set the index policy for the page, but leave the follow policy un-
892 * touched.
893 *
894 * @param string $policy Either 'index' or 'noindex'.
895 * @return null
896 */
897 public function setIndexPolicy( $policy ) {
898 $policy = trim( $policy );
899 if ( in_array( $policy, [ 'index', 'noindex' ] ) ) {
900 $this->mIndexPolicy = $policy;
901 }
902 }
903
904 /**
905 * Set the follow policy for the page, but leave the index policy un-
906 * touched.
907 *
908 * @param string $policy Either 'follow' or 'nofollow'.
909 * @return null
910 */
911 public function setFollowPolicy( $policy ) {
912 $policy = trim( $policy );
913 if ( in_array( $policy, [ 'follow', 'nofollow' ] ) ) {
914 $this->mFollowPolicy = $policy;
915 }
916 }
917
918 /**
919 * Set the new value of the "action text", this will be added to the
920 * "HTML title", separated from it with " - ".
921 *
922 * @param string $text New value of the "action text"
923 */
924 public function setPageTitleActionText( $text ) {
925 $this->mPageTitleActionText = $text;
926 }
927
928 /**
929 * Get the value of the "action text"
930 *
931 * @return string
932 */
933 public function getPageTitleActionText() {
934 return $this->mPageTitleActionText;
935 }
936
937 /**
938 * "HTML title" means the contents of "<title>".
939 * It is stored as plain, unescaped text and will be run through htmlspecialchars in the skin file.
940 *
941 * @param string|Message $name
942 */
943 public function setHTMLTitle( $name ) {
944 if ( $name instanceof Message ) {
945 $this->mHTMLtitle = $name->setContext( $this->getContext() )->text();
946 } else {
947 $this->mHTMLtitle = $name;
948 }
949 }
950
951 /**
952 * Return the "HTML title", i.e. the content of the "<title>" tag.
953 *
954 * @return string
955 */
956 public function getHTMLTitle() {
957 return $this->mHTMLtitle;
958 }
959
960 /**
961 * Set $mRedirectedFrom, the Title of the page which redirected us to the current page.
962 *
963 * @param Title $t
964 */
965 public function setRedirectedFrom( $t ) {
966 $this->mRedirectedFrom = $t;
967 }
968
969 /**
970 * "Page title" means the contents of \<h1\>. It is stored as a valid HTML
971 * fragment. This function allows good tags like \<sup\> in the \<h1\> tag,
972 * but not bad tags like \<script\>. This function automatically sets
973 * \<title\> to the same content as \<h1\> but with all tags removed. Bad
974 * tags that were escaped in \<h1\> will still be escaped in \<title\>, and
975 * good tags like \<i\> will be dropped entirely.
976 *
977 * @param string|Message $name
978 */
979 public function setPageTitle( $name ) {
980 if ( $name instanceof Message ) {
981 $name = $name->setContext( $this->getContext() )->text();
982 }
983
984 # change "<script>foo&bar</script>" to "&lt;script&gt;foo&amp;bar&lt;/script&gt;"
985 # but leave "<i>foobar</i>" alone
986 $nameWithTags = Sanitizer::normalizeCharReferences( Sanitizer::removeHTMLtags( $name ) );
987 $this->mPagetitle = $nameWithTags;
988
989 # change "<i>foo&amp;bar</i>" to "foo&bar"
990 $this->setHTMLTitle(
991 $this->msg( 'pagetitle' )->rawParams( Sanitizer::stripAllTags( $nameWithTags ) )
992 ->inContentLanguage()
993 );
994 }
995
996 /**
997 * Return the "page title", i.e. the content of the \<h1\> tag.
998 *
999 * @return string
1000 */
1001 public function getPageTitle() {
1002 return $this->mPagetitle;
1003 }
1004
1005 /**
1006 * Set the Title object to use
1007 *
1008 * @param Title $t
1009 */
1010 public function setTitle( Title $t ) {
1011 $this->getContext()->setTitle( $t );
1012 }
1013
1014 /**
1015 * Replace the subtitle with $str
1016 *
1017 * @param string|Message $str New value of the subtitle. String should be safe HTML.
1018 */
1019 public function setSubtitle( $str ) {
1020 $this->clearSubtitle();
1021 $this->addSubtitle( $str );
1022 }
1023
1024 /**
1025 * Add $str to the subtitle
1026 *
1027 * @param string|Message $str String or Message to add to the subtitle. String should be safe HTML.
1028 */
1029 public function addSubtitle( $str ) {
1030 if ( $str instanceof Message ) {
1031 $this->mSubtitle[] = $str->setContext( $this->getContext() )->parse();
1032 } else {
1033 $this->mSubtitle[] = $str;
1034 }
1035 }
1036
1037 /**
1038 * Build message object for a subtitle containing a backlink to a page
1039 *
1040 * @param Title $title Title to link to
1041 * @param array $query Array of additional parameters to include in the link
1042 * @return Message
1043 * @since 1.25
1044 */
1045 public static function buildBacklinkSubtitle( Title $title, $query = [] ) {
1046 if ( $title->isRedirect() ) {
1047 $query['redirect'] = 'no';
1048 }
1049 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1050 return wfMessage( 'backlinksubtitle' )
1051 ->rawParams( $linkRenderer->makeLink( $title, null, [], $query ) );
1052 }
1053
1054 /**
1055 * Add a subtitle containing a backlink to a page
1056 *
1057 * @param Title $title Title to link to
1058 * @param array $query Array of additional parameters to include in the link
1059 */
1060 public function addBacklinkSubtitle( Title $title, $query = [] ) {
1061 $this->addSubtitle( self::buildBacklinkSubtitle( $title, $query ) );
1062 }
1063
1064 /**
1065 * Clear the subtitles
1066 */
1067 public function clearSubtitle() {
1068 $this->mSubtitle = [];
1069 }
1070
1071 /**
1072 * Get the subtitle
1073 *
1074 * @return string
1075 */
1076 public function getSubtitle() {
1077 return implode( "<br />\n\t\t\t\t", $this->mSubtitle );
1078 }
1079
1080 /**
1081 * Set the page as printable, i.e. it'll be displayed with all
1082 * print styles included
1083 */
1084 public function setPrintable() {
1085 $this->mPrintable = true;
1086 }
1087
1088 /**
1089 * Return whether the page is "printable"
1090 *
1091 * @return bool
1092 */
1093 public function isPrintable() {
1094 return $this->mPrintable;
1095 }
1096
1097 /**
1098 * Disable output completely, i.e. calling output() will have no effect
1099 */
1100 public function disable() {
1101 $this->mDoNothing = true;
1102 }
1103
1104 /**
1105 * Return whether the output will be completely disabled
1106 *
1107 * @return bool
1108 */
1109 public function isDisabled() {
1110 return $this->mDoNothing;
1111 }
1112
1113 /**
1114 * Show an "add new section" link?
1115 *
1116 * @return bool
1117 */
1118 public function showNewSectionLink() {
1119 return $this->mNewSectionLink;
1120 }
1121
1122 /**
1123 * Forcibly hide the new section link?
1124 *
1125 * @return bool
1126 */
1127 public function forceHideNewSectionLink() {
1128 return $this->mHideNewSectionLink;
1129 }
1130
1131 /**
1132 * Add or remove feed links in the page header
1133 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1134 * for the new version
1135 * @see addFeedLink()
1136 *
1137 * @param bool $show True: add default feeds, false: remove all feeds
1138 */
1139 public function setSyndicated( $show = true ) {
1140 if ( $show ) {
1141 $this->setFeedAppendQuery( false );
1142 } else {
1143 $this->mFeedLinks = [];
1144 }
1145 }
1146
1147 /**
1148 * Add default feeds to the page header
1149 * This is mainly kept for backward compatibility, see OutputPage::addFeedLink()
1150 * for the new version
1151 * @see addFeedLink()
1152 *
1153 * @param string $val Query to append to feed links or false to output
1154 * default links
1155 */
1156 public function setFeedAppendQuery( $val ) {
1157 $this->mFeedLinks = [];
1158
1159 foreach ( $this->getConfig()->get( 'AdvertisedFeedTypes' ) as $type ) {
1160 $query = "feed=$type";
1161 if ( is_string( $val ) ) {
1162 $query .= '&' . $val;
1163 }
1164 $this->mFeedLinks[$type] = $this->getTitle()->getLocalURL( $query );
1165 }
1166 }
1167
1168 /**
1169 * Add a feed link to the page header
1170 *
1171 * @param string $format Feed type, should be a key of $wgFeedClasses
1172 * @param string $href URL
1173 */
1174 public function addFeedLink( $format, $href ) {
1175 if ( in_array( $format, $this->getConfig()->get( 'AdvertisedFeedTypes' ) ) ) {
1176 $this->mFeedLinks[$format] = $href;
1177 }
1178 }
1179
1180 /**
1181 * Should we output feed links for this page?
1182 * @return bool
1183 */
1184 public function isSyndicated() {
1185 return count( $this->mFeedLinks ) > 0;
1186 }
1187
1188 /**
1189 * Return URLs for each supported syndication format for this page.
1190 * @return array Associating format keys with URLs
1191 */
1192 public function getSyndicationLinks() {
1193 return $this->mFeedLinks;
1194 }
1195
1196 /**
1197 * Will currently always return null
1198 *
1199 * @return null
1200 */
1201 public function getFeedAppendQuery() {
1202 return $this->mFeedLinksAppendQuery;
1203 }
1204
1205 /**
1206 * Set whether the displayed content is related to the source of the
1207 * corresponding article on the wiki
1208 * Setting true will cause the change "article related" toggle to true
1209 *
1210 * @param bool $v
1211 */
1212 public function setArticleFlag( $v ) {
1213 $this->mIsarticle = $v;
1214 if ( $v ) {
1215 $this->mIsArticleRelated = $v;
1216 }
1217 }
1218
1219 /**
1220 * Return whether the content displayed page is related to the source of
1221 * the corresponding article on the wiki
1222 *
1223 * @return bool
1224 */
1225 public function isArticle() {
1226 return $this->mIsarticle;
1227 }
1228
1229 /**
1230 * Set whether this page is related an article on the wiki
1231 * Setting false will cause the change of "article flag" toggle to false
1232 *
1233 * @param bool $v
1234 */
1235 public function setArticleRelated( $v ) {
1236 $this->mIsArticleRelated = $v;
1237 if ( !$v ) {
1238 $this->mIsarticle = false;
1239 }
1240 }
1241
1242 /**
1243 * Return whether this page is related an article on the wiki
1244 *
1245 * @return bool
1246 */
1247 public function isArticleRelated() {
1248 return $this->mIsArticleRelated;
1249 }
1250
1251 /**
1252 * Add new language links
1253 *
1254 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1255 * (e.g. 'fr:Test page')
1256 */
1257 public function addLanguageLinks( array $newLinkArray ) {
1258 $this->mLanguageLinks += $newLinkArray;
1259 }
1260
1261 /**
1262 * Reset the language links and add new language links
1263 *
1264 * @param string[] $newLinkArray Array of interwiki-prefixed (non DB key) titles
1265 * (e.g. 'fr:Test page')
1266 */
1267 public function setLanguageLinks( array $newLinkArray ) {
1268 $this->mLanguageLinks = $newLinkArray;
1269 }
1270
1271 /**
1272 * Get the list of language links
1273 *
1274 * @return string[] Array of interwiki-prefixed (non DB key) titles (e.g. 'fr:Test page')
1275 */
1276 public function getLanguageLinks() {
1277 return $this->mLanguageLinks;
1278 }
1279
1280 /**
1281 * Add an array of categories, with names in the keys
1282 *
1283 * @param array $categories Mapping category name => sort key
1284 */
1285 public function addCategoryLinks( array $categories ) {
1286 global $wgContLang;
1287
1288 if ( !is_array( $categories ) || count( $categories ) == 0 ) {
1289 return;
1290 }
1291
1292 $res = $this->addCategoryLinksToLBAndGetResult( $categories );
1293
1294 # Set all the values to 'normal'.
1295 $categories = array_fill_keys( array_keys( $categories ), 'normal' );
1296
1297 # Mark hidden categories
1298 foreach ( $res as $row ) {
1299 if ( isset( $row->pp_value ) ) {
1300 $categories[$row->page_title] = 'hidden';
1301 }
1302 }
1303
1304 // Avoid PHP 7.1 warning of passing $this by reference
1305 $outputPage = $this;
1306 # Add the remaining categories to the skin
1307 if ( Hooks::run(
1308 'OutputPageMakeCategoryLinks',
1309 [ &$outputPage, $categories, &$this->mCategoryLinks ] )
1310 ) {
1311 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1312 foreach ( $categories as $category => $type ) {
1313 // array keys will cast numeric category names to ints, so cast back to string
1314 $category = (string)$category;
1315 $origcategory = $category;
1316 $title = Title::makeTitleSafe( NS_CATEGORY, $category );
1317 if ( !$title ) {
1318 continue;
1319 }
1320 $wgContLang->findVariantLink( $category, $title, true );
1321 if ( $category != $origcategory && array_key_exists( $category, $categories ) ) {
1322 continue;
1323 }
1324 $text = $wgContLang->convertHtml( $title->getText() );
1325 $this->mCategories[$type][] = $title->getText();
1326 $this->mCategoryLinks[$type][] = $linkRenderer->makeLink( $title, new HtmlArmor( $text ) );
1327 }
1328 }
1329 }
1330
1331 /**
1332 * @param array $categories
1333 * @return bool|ResultWrapper
1334 */
1335 protected function addCategoryLinksToLBAndGetResult( array $categories ) {
1336 # Add the links to a LinkBatch
1337 $arr = [ NS_CATEGORY => $categories ];
1338 $lb = new LinkBatch;
1339 $lb->setArray( $arr );
1340
1341 # Fetch existence plus the hiddencat property
1342 $dbr = wfGetDB( DB_REPLICA );
1343 $fields = array_merge(
1344 LinkCache::getSelectFields(),
1345 [ 'page_namespace', 'page_title', 'pp_value' ]
1346 );
1347
1348 $res = $dbr->select( [ 'page', 'page_props' ],
1349 $fields,
1350 $lb->constructSet( 'page', $dbr ),
1351 __METHOD__,
1352 [],
1353 [ 'page_props' => [ 'LEFT JOIN', [
1354 'pp_propname' => 'hiddencat',
1355 'pp_page = page_id'
1356 ] ] ]
1357 );
1358
1359 # Add the results to the link cache
1360 $lb->addResultToCache( LinkCache::singleton(), $res );
1361
1362 return $res;
1363 }
1364
1365 /**
1366 * Reset the category links (but not the category list) and add $categories
1367 *
1368 * @param array $categories Mapping category name => sort key
1369 */
1370 public function setCategoryLinks( array $categories ) {
1371 $this->mCategoryLinks = [];
1372 $this->addCategoryLinks( $categories );
1373 }
1374
1375 /**
1376 * Get the list of category links, in a 2-D array with the following format:
1377 * $arr[$type][] = $link, where $type is either "normal" or "hidden" (for
1378 * hidden categories) and $link a HTML fragment with a link to the category
1379 * page
1380 *
1381 * @return array
1382 */
1383 public function getCategoryLinks() {
1384 return $this->mCategoryLinks;
1385 }
1386
1387 /**
1388 * Get the list of category names this page belongs to.
1389 *
1390 * @param string $type The type of categories which should be returned. Possible values:
1391 * * all: all categories of all types
1392 * * hidden: only the hidden categories
1393 * * normal: all categories, except hidden categories
1394 * @return array Array of strings
1395 */
1396 public function getCategories( $type = 'all' ) {
1397 if ( $type === 'all' ) {
1398 $allCategories = [];
1399 foreach ( $this->mCategories as $categories ) {
1400 $allCategories = array_merge( $allCategories, $categories );
1401 }
1402 return $allCategories;
1403 }
1404 if ( !isset( $this->mCategories[$type] ) ) {
1405 throw new InvalidArgumentException( 'Invalid category type given: ' . $type );
1406 }
1407 return $this->mCategories[$type];
1408 }
1409
1410 /**
1411 * Add an array of indicators, with their identifiers as array
1412 * keys and HTML contents as values.
1413 *
1414 * In case of duplicate keys, existing values are overwritten.
1415 *
1416 * @param array $indicators
1417 * @since 1.25
1418 */
1419 public function setIndicators( array $indicators ) {
1420 $this->mIndicators = $indicators + $this->mIndicators;
1421 // Keep ordered by key
1422 ksort( $this->mIndicators );
1423 }
1424
1425 /**
1426 * Get the indicators associated with this page.
1427 *
1428 * The array will be internally ordered by item keys.
1429 *
1430 * @return array Keys: identifiers, values: HTML contents
1431 * @since 1.25
1432 */
1433 public function getIndicators() {
1434 return $this->mIndicators;
1435 }
1436
1437 /**
1438 * Adds help link with an icon via page indicators.
1439 * Link target can be overridden by a local message containing a wikilink:
1440 * the message key is: lowercase action or special page name + '-helppage'.
1441 * @param string $to Target MediaWiki.org page title or encoded URL.
1442 * @param bool $overrideBaseUrl Whether $url is a full URL, to avoid MW.o.
1443 * @since 1.25
1444 */
1445 public function addHelpLink( $to, $overrideBaseUrl = false ) {
1446 $this->addModuleStyles( 'mediawiki.helplink' );
1447 $text = $this->msg( 'helppage-top-gethelp' )->escaped();
1448
1449 if ( $overrideBaseUrl ) {
1450 $helpUrl = $to;
1451 } else {
1452 $toUrlencoded = wfUrlencode( str_replace( ' ', '_', $to ) );
1453 $helpUrl = "//www.mediawiki.org/wiki/Special:MyLanguage/$toUrlencoded";
1454 }
1455
1456 $link = Html::rawElement(
1457 'a',
1458 [
1459 'href' => $helpUrl,
1460 'target' => '_blank',
1461 'class' => 'mw-helplink',
1462 ],
1463 $text
1464 );
1465
1466 $this->setIndicators( [ 'mw-helplink' => $link ] );
1467 }
1468
1469 /**
1470 * Do not allow scripts which can be modified by wiki users to load on this page;
1471 * only allow scripts bundled with, or generated by, the software.
1472 * Site-wide styles are controlled by a config setting, since they can be
1473 * used to create a custom skin/theme, but not user-specific ones.
1474 *
1475 * @todo this should be given a more accurate name
1476 */
1477 public function disallowUserJs() {
1478 $this->reduceAllowedModules(
1479 ResourceLoaderModule::TYPE_SCRIPTS,
1480 ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL
1481 );
1482
1483 // Site-wide styles are controlled by a config setting, see T73621
1484 // for background on why. User styles are never allowed.
1485 if ( $this->getConfig()->get( 'AllowSiteCSSOnRestrictedPages' ) ) {
1486 $styleOrigin = ResourceLoaderModule::ORIGIN_USER_SITEWIDE;
1487 } else {
1488 $styleOrigin = ResourceLoaderModule::ORIGIN_CORE_INDIVIDUAL;
1489 }
1490 $this->reduceAllowedModules(
1491 ResourceLoaderModule::TYPE_STYLES,
1492 $styleOrigin
1493 );
1494 }
1495
1496 /**
1497 * Show what level of JavaScript / CSS untrustworthiness is allowed on this page
1498 * @see ResourceLoaderModule::$origin
1499 * @param string $type ResourceLoaderModule TYPE_ constant
1500 * @return int ResourceLoaderModule ORIGIN_ class constant
1501 */
1502 public function getAllowedModules( $type ) {
1503 if ( $type == ResourceLoaderModule::TYPE_COMBINED ) {
1504 return min( array_values( $this->mAllowedModules ) );
1505 } else {
1506 return isset( $this->mAllowedModules[$type] )
1507 ? $this->mAllowedModules[$type]
1508 : ResourceLoaderModule::ORIGIN_ALL;
1509 }
1510 }
1511
1512 /**
1513 * Limit the highest level of CSS/JS untrustworthiness allowed.
1514 *
1515 * If passed the same or a higher level than the current level of untrustworthiness set, the
1516 * level will remain unchanged.
1517 *
1518 * @param string $type
1519 * @param int $level ResourceLoaderModule class constant
1520 */
1521 public function reduceAllowedModules( $type, $level ) {
1522 $this->mAllowedModules[$type] = min( $this->getAllowedModules( $type ), $level );
1523 }
1524
1525 /**
1526 * Prepend $text to the body HTML
1527 *
1528 * @param string $text HTML
1529 */
1530 public function prependHTML( $text ) {
1531 $this->mBodytext = $text . $this->mBodytext;
1532 }
1533
1534 /**
1535 * Append $text to the body HTML
1536 *
1537 * @param string $text HTML
1538 */
1539 public function addHTML( $text ) {
1540 $this->mBodytext .= $text;
1541 }
1542
1543 /**
1544 * Shortcut for adding an Html::element via addHTML.
1545 *
1546 * @since 1.19
1547 *
1548 * @param string $element
1549 * @param array $attribs
1550 * @param string $contents
1551 */
1552 public function addElement( $element, array $attribs = [], $contents = '' ) {
1553 $this->addHTML( Html::element( $element, $attribs, $contents ) );
1554 }
1555
1556 /**
1557 * Clear the body HTML
1558 */
1559 public function clearHTML() {
1560 $this->mBodytext = '';
1561 }
1562
1563 /**
1564 * Get the body HTML
1565 *
1566 * @return string HTML
1567 */
1568 public function getHTML() {
1569 return $this->mBodytext;
1570 }
1571
1572 /**
1573 * Get/set the ParserOptions object to use for wikitext parsing
1574 *
1575 * @param ParserOptions|null $options Either the ParserOption to use or null to only get the
1576 * current ParserOption object. This parameter is deprecated since 1.31.
1577 * @return ParserOptions
1578 */
1579 public function parserOptions( $options = null ) {
1580 if ( $options !== null ) {
1581 wfDeprecated( __METHOD__ . ' with non-null $options', '1.31' );
1582 }
1583
1584 if ( $options !== null && !empty( $options->isBogus ) ) {
1585 // Someone is trying to set a bogus pre-$wgUser PO. Check if it has
1586 // been changed somehow, and keep it if so.
1587 $anonPO = ParserOptions::newFromAnon();
1588 $anonPO->setEditSection( false );
1589 $anonPO->setAllowUnsafeRawHtml( false );
1590 if ( !$options->matches( $anonPO ) ) {
1591 wfLogWarning( __METHOD__ . ': Setting a changed bogus ParserOptions: ' . wfGetAllCallers( 5 ) );
1592 $options->isBogus = false;
1593 }
1594 }
1595
1596 if ( !$this->mParserOptions ) {
1597 if ( !$this->getContext()->getUser()->isSafeToLoad() ) {
1598 // $wgUser isn't unstubbable yet, so don't try to get a
1599 // ParserOptions for it. And don't cache this ParserOptions
1600 // either.
1601 $po = ParserOptions::newFromAnon();
1602 $po->setEditSection( false );
1603 $po->setAllowUnsafeRawHtml( false );
1604 $po->isBogus = true;
1605 if ( $options !== null ) {
1606 $this->mParserOptions = empty( $options->isBogus ) ? $options : null;
1607 }
1608 return $po;
1609 }
1610
1611 $this->mParserOptions = ParserOptions::newFromContext( $this->getContext() );
1612 $this->mParserOptions->setEditSection( false );
1613 $this->mParserOptions->setAllowUnsafeRawHtml( false );
1614 }
1615
1616 if ( $options !== null && !empty( $options->isBogus ) ) {
1617 // They're trying to restore the bogus pre-$wgUser PO. Do the right
1618 // thing.
1619 return wfSetVar( $this->mParserOptions, null, true );
1620 } else {
1621 return wfSetVar( $this->mParserOptions, $options );
1622 }
1623 }
1624
1625 /**
1626 * Set the revision ID which will be seen by the wiki text parser
1627 * for things such as embedded {{REVISIONID}} variable use.
1628 *
1629 * @param int|null $revid An positive integer, or null
1630 * @return mixed Previous value
1631 */
1632 public function setRevisionId( $revid ) {
1633 $val = is_null( $revid ) ? null : intval( $revid );
1634 return wfSetVar( $this->mRevisionId, $val );
1635 }
1636
1637 /**
1638 * Get the displayed revision ID
1639 *
1640 * @return int
1641 */
1642 public function getRevisionId() {
1643 return $this->mRevisionId;
1644 }
1645
1646 /**
1647 * Set the timestamp of the revision which will be displayed. This is used
1648 * to avoid a extra DB call in Skin::lastModified().
1649 *
1650 * @param string|null $timestamp
1651 * @return mixed Previous value
1652 */
1653 public function setRevisionTimestamp( $timestamp ) {
1654 return wfSetVar( $this->mRevisionTimestamp, $timestamp );
1655 }
1656
1657 /**
1658 * Get the timestamp of displayed revision.
1659 * This will be null if not filled by setRevisionTimestamp().
1660 *
1661 * @return string|null
1662 */
1663 public function getRevisionTimestamp() {
1664 return $this->mRevisionTimestamp;
1665 }
1666
1667 /**
1668 * Set the displayed file version
1669 *
1670 * @param File|bool $file
1671 * @return mixed Previous value
1672 */
1673 public function setFileVersion( $file ) {
1674 $val = null;
1675 if ( $file instanceof File && $file->exists() ) {
1676 $val = [ 'time' => $file->getTimestamp(), 'sha1' => $file->getSha1() ];
1677 }
1678 return wfSetVar( $this->mFileVersion, $val, true );
1679 }
1680
1681 /**
1682 * Get the displayed file version
1683 *
1684 * @return array|null ('time' => MW timestamp, 'sha1' => sha1)
1685 */
1686 public function getFileVersion() {
1687 return $this->mFileVersion;
1688 }
1689
1690 /**
1691 * Get the templates used on this page
1692 *
1693 * @return array (namespace => dbKey => revId)
1694 * @since 1.18
1695 */
1696 public function getTemplateIds() {
1697 return $this->mTemplateIds;
1698 }
1699
1700 /**
1701 * Get the files used on this page
1702 *
1703 * @return array (dbKey => array('time' => MW timestamp or null, 'sha1' => sha1 or ''))
1704 * @since 1.18
1705 */
1706 public function getFileSearchOptions() {
1707 return $this->mImageTimeKeys;
1708 }
1709
1710 /**
1711 * Convert wikitext to HTML and add it to the buffer
1712 * Default assumes that the current page title will be used.
1713 *
1714 * @param string $text
1715 * @param bool $linestart Is this the start of a line?
1716 * @param bool $interface Is this text in the user interface language?
1717 * @throws MWException
1718 */
1719 public function addWikiText( $text, $linestart = true, $interface = true ) {
1720 $title = $this->getTitle(); // Work around E_STRICT
1721 if ( !$title ) {
1722 throw new MWException( 'Title is null' );
1723 }
1724 $this->addWikiTextTitle( $text, $title, $linestart, /*tidy*/false, $interface );
1725 }
1726
1727 /**
1728 * Add wikitext with a custom Title object
1729 *
1730 * @param string $text Wikitext
1731 * @param Title &$title
1732 * @param bool $linestart Is this the start of a line?
1733 */
1734 public function addWikiTextWithTitle( $text, &$title, $linestart = true ) {
1735 $this->addWikiTextTitle( $text, $title, $linestart );
1736 }
1737
1738 /**
1739 * Add wikitext with a custom Title object and tidy enabled.
1740 *
1741 * @param string $text Wikitext
1742 * @param Title &$title
1743 * @param bool $linestart Is this the start of a line?
1744 */
1745 function addWikiTextTitleTidy( $text, &$title, $linestart = true ) {
1746 $this->addWikiTextTitle( $text, $title, $linestart, true );
1747 }
1748
1749 /**
1750 * Add wikitext with tidy enabled
1751 *
1752 * @param string $text Wikitext
1753 * @param bool $linestart Is this the start of a line?
1754 */
1755 public function addWikiTextTidy( $text, $linestart = true ) {
1756 $title = $this->getTitle();
1757 $this->addWikiTextTitleTidy( $text, $title, $linestart );
1758 }
1759
1760 /**
1761 * Add wikitext with a custom Title object
1762 *
1763 * @param string $text Wikitext
1764 * @param Title $title
1765 * @param bool $linestart Is this the start of a line?
1766 * @param bool $tidy Whether to use tidy
1767 * @param bool $interface Whether it is an interface message
1768 * (for example disables conversion)
1769 */
1770 public function addWikiTextTitle( $text, Title $title, $linestart,
1771 $tidy = false, $interface = false
1772 ) {
1773 global $wgParser;
1774
1775 $popts = $this->parserOptions();
1776 $oldTidy = $popts->setTidy( $tidy );
1777 $popts->setInterfaceMessage( (bool)$interface );
1778
1779 $parserOutput = $wgParser->getFreshParser()->parse(
1780 $text, $title, $popts,
1781 $linestart, true, $this->mRevisionId
1782 );
1783
1784 $popts->setTidy( $oldTidy );
1785
1786 $this->addParserOutput( $parserOutput );
1787 }
1788
1789 /**
1790 * Add all metadata associated with a ParserOutput object, but without the actual HTML. This
1791 * includes categories, language links, ResourceLoader modules, effects of certain magic words,
1792 * and so on.
1793 *
1794 * @since 1.24
1795 * @param ParserOutput $parserOutput
1796 */
1797 public function addParserOutputMetadata( $parserOutput ) {
1798 $this->mLanguageLinks += $parserOutput->getLanguageLinks();
1799 $this->addCategoryLinks( $parserOutput->getCategories() );
1800 $this->setIndicators( $parserOutput->getIndicators() );
1801 $this->mNewSectionLink = $parserOutput->getNewSection();
1802 $this->mHideNewSectionLink = $parserOutput->getHideNewSection();
1803
1804 if ( !$parserOutput->isCacheable() ) {
1805 $this->enableClientCache( false );
1806 }
1807 $this->mNoGallery = $parserOutput->getNoGallery();
1808 $this->mHeadItems = array_merge( $this->mHeadItems, $parserOutput->getHeadItems() );
1809 $this->addModules( $parserOutput->getModules() );
1810 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1811 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1812 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1813 $this->mPreventClickjacking = $this->mPreventClickjacking
1814 || $parserOutput->preventClickjacking();
1815
1816 // Template versioning...
1817 foreach ( (array)$parserOutput->getTemplateIds() as $ns => $dbks ) {
1818 if ( isset( $this->mTemplateIds[$ns] ) ) {
1819 $this->mTemplateIds[$ns] = $dbks + $this->mTemplateIds[$ns];
1820 } else {
1821 $this->mTemplateIds[$ns] = $dbks;
1822 }
1823 }
1824 // File versioning...
1825 foreach ( (array)$parserOutput->getFileSearchOptions() as $dbk => $data ) {
1826 $this->mImageTimeKeys[$dbk] = $data;
1827 }
1828
1829 // Hooks registered in the object
1830 $parserOutputHooks = $this->getConfig()->get( 'ParserOutputHooks' );
1831 foreach ( $parserOutput->getOutputHooks() as $hookInfo ) {
1832 list( $hookName, $data ) = $hookInfo;
1833 if ( isset( $parserOutputHooks[$hookName] ) ) {
1834 call_user_func( $parserOutputHooks[$hookName], $this, $parserOutput, $data );
1835 }
1836 }
1837
1838 // Enable OOUI if requested via ParserOutput
1839 if ( $parserOutput->getEnableOOUI() ) {
1840 $this->enableOOUI();
1841 }
1842
1843 // Include parser limit report
1844 if ( !$this->limitReportJSData ) {
1845 $this->limitReportJSData = $parserOutput->getLimitReportJSData();
1846 }
1847
1848 // Link flags are ignored for now, but may in the future be
1849 // used to mark individual language links.
1850 $linkFlags = [];
1851 // Avoid PHP 7.1 warning of passing $this by reference
1852 $outputPage = $this;
1853 Hooks::run( 'LanguageLinks', [ $this->getTitle(), &$this->mLanguageLinks, &$linkFlags ] );
1854 Hooks::runWithoutAbort( 'OutputPageParserOutput', [ &$outputPage, $parserOutput ] );
1855
1856 // This check must be after 'OutputPageParserOutput' runs in addParserOutputMetadata
1857 // so that extensions may modify ParserOutput to toggle TOC.
1858 // This cannot be moved to addParserOutputText because that is not
1859 // called by EditPage for Preview.
1860 if ( $parserOutput->getTOCEnabled() && $parserOutput->getTOCHTML() ) {
1861 $this->mEnableTOC = true;
1862 }
1863 }
1864
1865 /**
1866 * Add the HTML and enhancements for it (like ResourceLoader modules) associated with a
1867 * ParserOutput object, without any other metadata.
1868 *
1869 * @since 1.24
1870 * @param ParserOutput $parserOutput
1871 */
1872 public function addParserOutputContent( $parserOutput ) {
1873 $this->addParserOutputText( $parserOutput );
1874
1875 $this->addModules( $parserOutput->getModules() );
1876 $this->addModuleScripts( $parserOutput->getModuleScripts() );
1877 $this->addModuleStyles( $parserOutput->getModuleStyles() );
1878
1879 $this->addJsConfigVars( $parserOutput->getJsConfigVars() );
1880 }
1881
1882 /**
1883 * Add the HTML associated with a ParserOutput object, without any metadata.
1884 *
1885 * @since 1.24
1886 * @param ParserOutput $parserOutput
1887 */
1888 public function addParserOutputText( $parserOutput ) {
1889 $text = $parserOutput->getText();
1890 // Avoid PHP 7.1 warning of passing $this by reference
1891 $outputPage = $this;
1892 Hooks::runWithoutAbort( 'OutputPageBeforeHTML', [ &$outputPage, &$text ] );
1893 $this->addHTML( $text );
1894 }
1895
1896 /**
1897 * Add everything from a ParserOutput object.
1898 *
1899 * @param ParserOutput $parserOutput
1900 */
1901 function addParserOutput( $parserOutput ) {
1902 $this->addParserOutputMetadata( $parserOutput );
1903
1904 // Touch section edit links only if not previously disabled
1905 if ( $parserOutput->getEditSectionTokens() ) {
1906 $parserOutput->setEditSectionTokens( $this->mEnableSectionEditLinks );
1907 }
1908
1909 $this->addParserOutputText( $parserOutput );
1910 }
1911
1912 /**
1913 * Add the output of a QuickTemplate to the output buffer
1914 *
1915 * @param QuickTemplate &$template
1916 */
1917 public function addTemplate( &$template ) {
1918 $this->addHTML( $template->getHTML() );
1919 }
1920
1921 /**
1922 * Parse wikitext and return the HTML.
1923 *
1924 * @param string $text
1925 * @param bool $linestart Is this the start of a line?
1926 * @param bool $interface Use interface language ($wgLang instead of
1927 * $wgContLang) while parsing language sensitive magic words like GRAMMAR and PLURAL.
1928 * This also disables LanguageConverter.
1929 * @param Language $language Target language object, will override $interface
1930 * @throws MWException
1931 * @return string HTML
1932 */
1933 public function parse( $text, $linestart = true, $interface = false, $language = null ) {
1934 global $wgParser;
1935
1936 if ( is_null( $this->getTitle() ) ) {
1937 throw new MWException( 'Empty $mTitle in ' . __METHOD__ );
1938 }
1939
1940 $popts = $this->parserOptions();
1941 if ( $interface ) {
1942 $popts->setInterfaceMessage( true );
1943 }
1944 if ( $language !== null ) {
1945 $oldLang = $popts->setTargetLanguage( $language );
1946 }
1947
1948 $parserOutput = $wgParser->getFreshParser()->parse(
1949 $text, $this->getTitle(), $popts,
1950 $linestart, true, $this->mRevisionId
1951 );
1952
1953 if ( $interface ) {
1954 $popts->setInterfaceMessage( false );
1955 }
1956 if ( $language !== null ) {
1957 $popts->setTargetLanguage( $oldLang );
1958 }
1959
1960 return $parserOutput->getText();
1961 }
1962
1963 /**
1964 * Parse wikitext, strip paragraphs, and return the HTML.
1965 *
1966 * @param string $text
1967 * @param bool $linestart Is this the start of a line?
1968 * @param bool $interface Use interface language ($wgLang instead of
1969 * $wgContLang) while parsing language sensitive magic
1970 * words like GRAMMAR and PLURAL
1971 * @return string HTML
1972 */
1973 public function parseInline( $text, $linestart = true, $interface = false ) {
1974 $parsed = $this->parse( $text, $linestart, $interface );
1975 return Parser::stripOuterParagraph( $parsed );
1976 }
1977
1978 /**
1979 * @param int $maxage
1980 * @deprecated since 1.27 Use setCdnMaxage() instead
1981 */
1982 public function setSquidMaxage( $maxage ) {
1983 wfDeprecated( __METHOD__, '1.27' );
1984 $this->setCdnMaxage( $maxage );
1985 }
1986
1987 /**
1988 * Set the value of the "s-maxage" part of the "Cache-control" HTTP header
1989 *
1990 * @param int $maxage Maximum cache time on the CDN, in seconds.
1991 */
1992 public function setCdnMaxage( $maxage ) {
1993 $this->mCdnMaxage = min( $maxage, $this->mCdnMaxageLimit );
1994 }
1995
1996 /**
1997 * Lower the value of the "s-maxage" part of the "Cache-control" HTTP header
1998 *
1999 * @param int $maxage Maximum cache time on the CDN, in seconds
2000 * @since 1.27
2001 */
2002 public function lowerCdnMaxage( $maxage ) {
2003 $this->mCdnMaxageLimit = min( $maxage, $this->mCdnMaxageLimit );
2004 $this->setCdnMaxage( $this->mCdnMaxage );
2005 }
2006
2007 /**
2008 * Get TTL in [$minTTL,$maxTTL] in pass it to lowerCdnMaxage()
2009 *
2010 * This sets and returns $minTTL if $mtime is false or null. Otherwise,
2011 * the TTL is higher the older the $mtime timestamp is. Essentially, the
2012 * TTL is 90% of the age of the object, subject to the min and max.
2013 *
2014 * @param string|int|float|bool|null $mtime Last-Modified timestamp
2015 * @param int $minTTL Mimimum TTL in seconds [default: 1 minute]
2016 * @param int $maxTTL Maximum TTL in seconds [default: $wgSquidMaxage]
2017 * @return int TTL in seconds
2018 * @since 1.28
2019 */
2020 public function adaptCdnTTL( $mtime, $minTTL = 0, $maxTTL = 0 ) {
2021 $minTTL = $minTTL ?: IExpiringStore::TTL_MINUTE;
2022 $maxTTL = $maxTTL ?: $this->getConfig()->get( 'SquidMaxage' );
2023
2024 if ( $mtime === null || $mtime === false ) {
2025 return $minTTL; // entity does not exist
2026 }
2027
2028 $age = time() - wfTimestamp( TS_UNIX, $mtime );
2029 $adaptiveTTL = max( 0.9 * $age, $minTTL );
2030 $adaptiveTTL = min( $adaptiveTTL, $maxTTL );
2031
2032 $this->lowerCdnMaxage( (int)$adaptiveTTL );
2033
2034 return $adaptiveTTL;
2035 }
2036
2037 /**
2038 * Use enableClientCache(false) to force it to send nocache headers
2039 *
2040 * @param bool $state
2041 *
2042 * @return bool
2043 */
2044 public function enableClientCache( $state ) {
2045 return wfSetVar( $this->mEnableClientCache, $state );
2046 }
2047
2048 /**
2049 * Get the list of cookies that will influence on the cache
2050 *
2051 * @return array
2052 */
2053 function getCacheVaryCookies() {
2054 static $cookies;
2055 if ( $cookies === null ) {
2056 $config = $this->getConfig();
2057 $cookies = array_merge(
2058 SessionManager::singleton()->getVaryCookies(),
2059 [
2060 'forceHTTPS',
2061 ],
2062 $config->get( 'CacheVaryCookies' )
2063 );
2064 Hooks::run( 'GetCacheVaryCookies', [ $this, &$cookies ] );
2065 }
2066 return $cookies;
2067 }
2068
2069 /**
2070 * Check if the request has a cache-varying cookie header
2071 * If it does, it's very important that we don't allow public caching
2072 *
2073 * @return bool
2074 */
2075 function haveCacheVaryCookies() {
2076 $request = $this->getRequest();
2077 foreach ( $this->getCacheVaryCookies() as $cookieName ) {
2078 if ( $request->getCookie( $cookieName, '', '' ) !== '' ) {
2079 wfDebug( __METHOD__ . ": found $cookieName\n" );
2080 return true;
2081 }
2082 }
2083 wfDebug( __METHOD__ . ": no cache-varying cookies found\n" );
2084 return false;
2085 }
2086
2087 /**
2088 * Add an HTTP header that will influence on the cache
2089 *
2090 * @param string $header Header name
2091 * @param string[]|null $option Options for the Key header. See
2092 * https://datatracker.ietf.org/doc/draft-fielding-http-key/
2093 * for the list of valid options.
2094 */
2095 public function addVaryHeader( $header, array $option = null ) {
2096 if ( !array_key_exists( $header, $this->mVaryHeader ) ) {
2097 $this->mVaryHeader[$header] = [];
2098 }
2099 if ( !is_array( $option ) ) {
2100 $option = [];
2101 }
2102 $this->mVaryHeader[$header] = array_unique( array_merge( $this->mVaryHeader[$header], $option ) );
2103 }
2104
2105 /**
2106 * Return a Vary: header on which to vary caches. Based on the keys of $mVaryHeader,
2107 * such as Accept-Encoding or Cookie
2108 *
2109 * @return string
2110 */
2111 public function getVaryHeader() {
2112 // If we vary on cookies, let's make sure it's always included here too.
2113 if ( $this->getCacheVaryCookies() ) {
2114 $this->addVaryHeader( 'Cookie' );
2115 }
2116
2117 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2118 $this->addVaryHeader( $header, $options );
2119 }
2120 return 'Vary: ' . implode( ', ', array_keys( $this->mVaryHeader ) );
2121 }
2122
2123 /**
2124 * Add an HTTP Link: header
2125 *
2126 * @param string $header Header value
2127 */
2128 public function addLinkHeader( $header ) {
2129 $this->mLinkHeader[] = $header;
2130 }
2131
2132 /**
2133 * Return a Link: header. Based on the values of $mLinkHeader.
2134 *
2135 * @return string
2136 */
2137 public function getLinkHeader() {
2138 if ( !$this->mLinkHeader ) {
2139 return false;
2140 }
2141
2142 return 'Link: ' . implode( ',', $this->mLinkHeader );
2143 }
2144
2145 /**
2146 * Get a complete Key header
2147 *
2148 * @return string
2149 */
2150 public function getKeyHeader() {
2151 $cvCookies = $this->getCacheVaryCookies();
2152
2153 $cookiesOption = [];
2154 foreach ( $cvCookies as $cookieName ) {
2155 $cookiesOption[] = 'param=' . $cookieName;
2156 }
2157 $this->addVaryHeader( 'Cookie', $cookiesOption );
2158
2159 foreach ( SessionManager::singleton()->getVaryHeaders() as $header => $options ) {
2160 $this->addVaryHeader( $header, $options );
2161 }
2162
2163 $headers = [];
2164 foreach ( $this->mVaryHeader as $header => $option ) {
2165 $newheader = $header;
2166 if ( is_array( $option ) && count( $option ) > 0 ) {
2167 $newheader .= ';' . implode( ';', $option );
2168 }
2169 $headers[] = $newheader;
2170 }
2171 $key = 'Key: ' . implode( ',', $headers );
2172
2173 return $key;
2174 }
2175
2176 /**
2177 * T23672: Add Accept-Language to Vary and Key headers
2178 * if there's no 'variant' parameter existed in GET.
2179 *
2180 * For example:
2181 * /w/index.php?title=Main_page should always be served; but
2182 * /w/index.php?title=Main_page&variant=zh-cn should never be served.
2183 */
2184 function addAcceptLanguage() {
2185 $title = $this->getTitle();
2186 if ( !$title instanceof Title ) {
2187 return;
2188 }
2189
2190 $lang = $title->getPageLanguage();
2191 if ( !$this->getRequest()->getCheck( 'variant' ) && $lang->hasVariants() ) {
2192 $variants = $lang->getVariants();
2193 $aloption = [];
2194 foreach ( $variants as $variant ) {
2195 if ( $variant === $lang->getCode() ) {
2196 continue;
2197 } else {
2198 $aloption[] = 'substr=' . $variant;
2199
2200 // IE and some other browsers use BCP 47 standards in
2201 // their Accept-Language header, like "zh-CN" or "zh-Hant".
2202 // We should handle these too.
2203 $variantBCP47 = LanguageCode::bcp47( $variant );
2204 if ( $variantBCP47 !== $variant ) {
2205 $aloption[] = 'substr=' . $variantBCP47;
2206 }
2207 }
2208 }
2209 $this->addVaryHeader( 'Accept-Language', $aloption );
2210 }
2211 }
2212
2213 /**
2214 * Set a flag which will cause an X-Frame-Options header appropriate for
2215 * edit pages to be sent. The header value is controlled by
2216 * $wgEditPageFrameOptions.
2217 *
2218 * This is the default for special pages. If you display a CSRF-protected
2219 * form on an ordinary view page, then you need to call this function.
2220 *
2221 * @param bool $enable
2222 */
2223 public function preventClickjacking( $enable = true ) {
2224 $this->mPreventClickjacking = $enable;
2225 }
2226
2227 /**
2228 * Turn off frame-breaking. Alias for $this->preventClickjacking(false).
2229 * This can be called from pages which do not contain any CSRF-protected
2230 * HTML form.
2231 */
2232 public function allowClickjacking() {
2233 $this->mPreventClickjacking = false;
2234 }
2235
2236 /**
2237 * Get the prevent-clickjacking flag
2238 *
2239 * @since 1.24
2240 * @return bool
2241 */
2242 public function getPreventClickjacking() {
2243 return $this->mPreventClickjacking;
2244 }
2245
2246 /**
2247 * Get the X-Frame-Options header value (without the name part), or false
2248 * if there isn't one. This is used by Skin to determine whether to enable
2249 * JavaScript frame-breaking, for clients that don't support X-Frame-Options.
2250 *
2251 * @return string|false
2252 */
2253 public function getFrameOptions() {
2254 $config = $this->getConfig();
2255 if ( $config->get( 'BreakFrames' ) ) {
2256 return 'DENY';
2257 } elseif ( $this->mPreventClickjacking && $config->get( 'EditPageFrameOptions' ) ) {
2258 return $config->get( 'EditPageFrameOptions' );
2259 }
2260 return false;
2261 }
2262
2263 /**
2264 * Send cache control HTTP headers
2265 */
2266 public function sendCacheControl() {
2267 $response = $this->getRequest()->response();
2268 $config = $this->getConfig();
2269
2270 $this->addVaryHeader( 'Cookie' );
2271 $this->addAcceptLanguage();
2272
2273 # don't serve compressed data to clients who can't handle it
2274 # maintain different caches for logged-in users and non-logged in ones
2275 $response->header( $this->getVaryHeader() );
2276
2277 if ( $config->get( 'UseKeyHeader' ) ) {
2278 $response->header( $this->getKeyHeader() );
2279 }
2280
2281 if ( $this->mEnableClientCache ) {
2282 if (
2283 $config->get( 'UseSquid' ) &&
2284 !$response->hasCookies() &&
2285 !SessionManager::getGlobalSession()->isPersistent() &&
2286 !$this->isPrintable() &&
2287 $this->mCdnMaxage != 0 &&
2288 !$this->haveCacheVaryCookies()
2289 ) {
2290 if ( $config->get( 'UseESI' ) ) {
2291 # We'll purge the proxy cache explicitly, but require end user agents
2292 # to revalidate against the proxy on each visit.
2293 # Surrogate-Control controls our CDN, Cache-Control downstream caches
2294 wfDebug( __METHOD__ .
2295 ": proxy caching with ESI; {$this->mLastModified} **", 'private' );
2296 # start with a shorter timeout for initial testing
2297 # header( 'Surrogate-Control: max-age=2678400+2678400, content="ESI/1.0"');
2298 $response->header(
2299 "Surrogate-Control: max-age={$config->get( 'SquidMaxage' )}" .
2300 "+{$this->mCdnMaxage}, content=\"ESI/1.0\""
2301 );
2302 $response->header( 'Cache-Control: s-maxage=0, must-revalidate, max-age=0' );
2303 } else {
2304 # We'll purge the proxy cache for anons explicitly, but require end user agents
2305 # to revalidate against the proxy on each visit.
2306 # IMPORTANT! The CDN needs to replace the Cache-Control header with
2307 # Cache-Control: s-maxage=0, must-revalidate, max-age=0
2308 wfDebug( __METHOD__ .
2309 ": local proxy caching; {$this->mLastModified} **", 'private' );
2310 # start with a shorter timeout for initial testing
2311 # header( "Cache-Control: s-maxage=2678400, must-revalidate, max-age=0" );
2312 $response->header( "Cache-Control: " .
2313 "s-maxage={$this->mCdnMaxage}, must-revalidate, max-age=0" );
2314 }
2315 } else {
2316 # We do want clients to cache if they can, but they *must* check for updates
2317 # on revisiting the page.
2318 wfDebug( __METHOD__ . ": private caching; {$this->mLastModified} **", 'private' );
2319 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2320 $response->header( "Cache-Control: private, must-revalidate, max-age=0" );
2321 }
2322 if ( $this->mLastModified ) {
2323 $response->header( "Last-Modified: {$this->mLastModified}" );
2324 }
2325 } else {
2326 wfDebug( __METHOD__ . ": no caching **", 'private' );
2327
2328 # In general, the absence of a last modified header should be enough to prevent
2329 # the client from using its cache. We send a few other things just to make sure.
2330 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
2331 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
2332 $response->header( 'Pragma: no-cache' );
2333 }
2334 }
2335
2336 /**
2337 * Finally, all the text has been munged and accumulated into
2338 * the object, let's actually output it:
2339 *
2340 * @param bool $return Set to true to get the result as a string rather than sending it
2341 * @return string|null
2342 * @throws Exception
2343 * @throws FatalError
2344 * @throws MWException
2345 */
2346 public function output( $return = false ) {
2347 global $wgContLang;
2348
2349 if ( $this->mDoNothing ) {
2350 return $return ? '' : null;
2351 }
2352
2353 $response = $this->getRequest()->response();
2354 $config = $this->getConfig();
2355
2356 if ( $this->mRedirect != '' ) {
2357 # Standards require redirect URLs to be absolute
2358 $this->mRedirect = wfExpandUrl( $this->mRedirect, PROTO_CURRENT );
2359
2360 $redirect = $this->mRedirect;
2361 $code = $this->mRedirectCode;
2362
2363 if ( Hooks::run( "BeforePageRedirect", [ $this, &$redirect, &$code ] ) ) {
2364 if ( $code == '301' || $code == '303' ) {
2365 if ( !$config->get( 'DebugRedirects' ) ) {
2366 $response->statusHeader( $code );
2367 }
2368 $this->mLastModified = wfTimestamp( TS_RFC2822 );
2369 }
2370 if ( $config->get( 'VaryOnXFP' ) ) {
2371 $this->addVaryHeader( 'X-Forwarded-Proto' );
2372 }
2373 $this->sendCacheControl();
2374
2375 $response->header( "Content-Type: text/html; charset=utf-8" );
2376 if ( $config->get( 'DebugRedirects' ) ) {
2377 $url = htmlspecialchars( $redirect );
2378 print "<!DOCTYPE html>\n<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n";
2379 print "<p>Location: <a href=\"$url\">$url</a></p>\n";
2380 print "</body>\n</html>\n";
2381 } else {
2382 $response->header( 'Location: ' . $redirect );
2383 }
2384 }
2385
2386 return $return ? '' : null;
2387 } elseif ( $this->mStatusCode ) {
2388 $response->statusHeader( $this->mStatusCode );
2389 }
2390
2391 # Buffer output; final headers may depend on later processing
2392 ob_start();
2393
2394 $response->header( 'Content-type: ' . $config->get( 'MimeType' ) . '; charset=UTF-8' );
2395 $response->header( 'Content-language: ' . $wgContLang->getHtmlCode() );
2396
2397 // Avoid Internet Explorer "compatibility view" in IE 8-10, so that
2398 // jQuery etc. can work correctly.
2399 $response->header( 'X-UA-Compatible: IE=Edge' );
2400
2401 if ( !$this->mArticleBodyOnly ) {
2402 $sk = $this->getSkin();
2403
2404 if ( $sk->shouldPreloadLogo() ) {
2405 $this->addLogoPreloadLinkHeaders();
2406 }
2407 }
2408
2409 $linkHeader = $this->getLinkHeader();
2410 if ( $linkHeader ) {
2411 $response->header( $linkHeader );
2412 }
2413
2414 // Prevent framing, if requested
2415 $frameOptions = $this->getFrameOptions();
2416 if ( $frameOptions ) {
2417 $response->header( "X-Frame-Options: $frameOptions" );
2418 }
2419
2420 if ( $this->mArticleBodyOnly ) {
2421 echo $this->mBodytext;
2422 } else {
2423 // Enable safe mode if requested
2424 if ( $this->getRequest()->getBool( 'safemode' ) ) {
2425 $this->disallowUserJs();
2426 }
2427
2428 $sk = $this->getSkin();
2429 foreach ( $sk->getDefaultModules() as $group ) {
2430 $this->addModules( $group );
2431 }
2432
2433 MWDebug::addModules( $this );
2434
2435 // Avoid PHP 7.1 warning of passing $this by reference
2436 $outputPage = $this;
2437 // Hook that allows last minute changes to the output page, e.g.
2438 // adding of CSS or Javascript by extensions.
2439 Hooks::runWithoutAbort( 'BeforePageDisplay', [ &$outputPage, &$sk ] );
2440
2441 try {
2442 $sk->outputPage();
2443 } catch ( Exception $e ) {
2444 ob_end_clean(); // bug T129657
2445 throw $e;
2446 }
2447 }
2448
2449 try {
2450 // This hook allows last minute changes to final overall output by modifying output buffer
2451 Hooks::runWithoutAbort( 'AfterFinalPageOutput', [ $this ] );
2452 } catch ( Exception $e ) {
2453 ob_end_clean(); // bug T129657
2454 throw $e;
2455 }
2456
2457 $this->sendCacheControl();
2458
2459 if ( $return ) {
2460 return ob_get_clean();
2461 } else {
2462 ob_end_flush();
2463 return null;
2464 }
2465 }
2466
2467 /**
2468 * Prepare this object to display an error page; disable caching and
2469 * indexing, clear the current text and redirect, set the page's title
2470 * and optionally an custom HTML title (content of the "<title>" tag).
2471 *
2472 * @param string|Message $pageTitle Will be passed directly to setPageTitle()
2473 * @param string|Message $htmlTitle Will be passed directly to setHTMLTitle();
2474 * optional, if not passed the "<title>" attribute will be
2475 * based on $pageTitle
2476 */
2477 public function prepareErrorPage( $pageTitle, $htmlTitle = false ) {
2478 $this->setPageTitle( $pageTitle );
2479 if ( $htmlTitle !== false ) {
2480 $this->setHTMLTitle( $htmlTitle );
2481 }
2482 $this->setRobotPolicy( 'noindex,nofollow' );
2483 $this->setArticleRelated( false );
2484 $this->enableClientCache( false );
2485 $this->mRedirect = '';
2486 $this->clearSubtitle();
2487 $this->clearHTML();
2488 }
2489
2490 /**
2491 * Output a standard error page
2492 *
2493 * showErrorPage( 'titlemsg', 'pagetextmsg' );
2494 * showErrorPage( 'titlemsg', 'pagetextmsg', [ 'param1', 'param2' ] );
2495 * showErrorPage( 'titlemsg', $messageObject );
2496 * showErrorPage( $titleMessageObject, $messageObject );
2497 *
2498 * @param string|Message $title Message key (string) for page title, or a Message object
2499 * @param string|Message $msg Message key (string) for page text, or a Message object
2500 * @param array $params Message parameters; ignored if $msg is a Message object
2501 */
2502 public function showErrorPage( $title, $msg, $params = [] ) {
2503 if ( !$title instanceof Message ) {
2504 $title = $this->msg( $title );
2505 }
2506
2507 $this->prepareErrorPage( $title );
2508
2509 if ( $msg instanceof Message ) {
2510 if ( $params !== [] ) {
2511 trigger_error( 'Argument ignored: $params. The message parameters argument '
2512 . 'is discarded when the $msg argument is a Message object instead of '
2513 . 'a string.', E_USER_NOTICE );
2514 }
2515 $this->addHTML( $msg->parseAsBlock() );
2516 } else {
2517 $this->addWikiMsgArray( $msg, $params );
2518 }
2519
2520 $this->returnToMain();
2521 }
2522
2523 /**
2524 * Output a standard permission error page
2525 *
2526 * @param array $errors Error message keys or [key, param...] arrays
2527 * @param string $action Action that was denied or null if unknown
2528 */
2529 public function showPermissionsErrorPage( array $errors, $action = null ) {
2530 foreach ( $errors as $key => $error ) {
2531 $errors[$key] = (array)$error;
2532 }
2533
2534 // For some action (read, edit, create and upload), display a "login to do this action"
2535 // error if all of the following conditions are met:
2536 // 1. the user is not logged in
2537 // 2. the only error is insufficient permissions (i.e. no block or something else)
2538 // 3. the error can be avoided simply by logging in
2539 if ( in_array( $action, [ 'read', 'edit', 'createpage', 'createtalk', 'upload' ] )
2540 && $this->getUser()->isAnon() && count( $errors ) == 1 && isset( $errors[0][0] )
2541 && ( $errors[0][0] == 'badaccess-groups' || $errors[0][0] == 'badaccess-group0' )
2542 && ( User::groupHasPermission( 'user', $action )
2543 || User::groupHasPermission( 'autoconfirmed', $action ) )
2544 ) {
2545 $displayReturnto = null;
2546
2547 # Due to T34276, if a user does not have read permissions,
2548 # $this->getTitle() will just give Special:Badtitle, which is
2549 # not especially useful as a returnto parameter. Use the title
2550 # from the request instead, if there was one.
2551 $request = $this->getRequest();
2552 $returnto = Title::newFromText( $request->getVal( 'title', '' ) );
2553 if ( $action == 'edit' ) {
2554 $msg = 'whitelistedittext';
2555 $displayReturnto = $returnto;
2556 } elseif ( $action == 'createpage' || $action == 'createtalk' ) {
2557 $msg = 'nocreatetext';
2558 } elseif ( $action == 'upload' ) {
2559 $msg = 'uploadnologintext';
2560 } else { # Read
2561 $msg = 'loginreqpagetext';
2562 $displayReturnto = Title::newMainPage();
2563 }
2564
2565 $query = [];
2566
2567 if ( $returnto ) {
2568 $query['returnto'] = $returnto->getPrefixedText();
2569
2570 if ( !$request->wasPosted() ) {
2571 $returntoquery = $request->getValues();
2572 unset( $returntoquery['title'] );
2573 unset( $returntoquery['returnto'] );
2574 unset( $returntoquery['returntoquery'] );
2575 $query['returntoquery'] = wfArrayToCgi( $returntoquery );
2576 }
2577 }
2578 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
2579 $loginLink = $linkRenderer->makeKnownLink(
2580 SpecialPage::getTitleFor( 'Userlogin' ),
2581 $this->msg( 'loginreqlink' )->text(),
2582 [],
2583 $query
2584 );
2585
2586 $this->prepareErrorPage( $this->msg( 'loginreqtitle' ) );
2587 $this->addHTML( $this->msg( $msg )->rawParams( $loginLink )->parse() );
2588
2589 # Don't return to a page the user can't read otherwise
2590 # we'll end up in a pointless loop
2591 if ( $displayReturnto && $displayReturnto->userCan( 'read', $this->getUser() ) ) {
2592 $this->returnToMain( null, $displayReturnto );
2593 }
2594 } else {
2595 $this->prepareErrorPage( $this->msg( 'permissionserrors' ) );
2596 $this->addWikiText( $this->formatPermissionsErrorMessage( $errors, $action ) );
2597 }
2598 }
2599
2600 /**
2601 * Display an error page indicating that a given version of MediaWiki is
2602 * required to use it
2603 *
2604 * @param mixed $version The version of MediaWiki needed to use the page
2605 */
2606 public function versionRequired( $version ) {
2607 $this->prepareErrorPage( $this->msg( 'versionrequired', $version ) );
2608
2609 $this->addWikiMsg( 'versionrequiredtext', $version );
2610 $this->returnToMain();
2611 }
2612
2613 /**
2614 * Format a list of error messages
2615 *
2616 * @param array $errors Array of arrays returned by Title::getUserPermissionsErrors
2617 * @param string $action Action that was denied or null if unknown
2618 * @return string The wikitext error-messages, formatted into a list.
2619 */
2620 public function formatPermissionsErrorMessage( array $errors, $action = null ) {
2621 if ( $action == null ) {
2622 $text = $this->msg( 'permissionserrorstext', count( $errors ) )->plain() . "\n\n";
2623 } else {
2624 $action_desc = $this->msg( "action-$action" )->plain();
2625 $text = $this->msg(
2626 'permissionserrorstext-withaction',
2627 count( $errors ),
2628 $action_desc
2629 )->plain() . "\n\n";
2630 }
2631
2632 if ( count( $errors ) > 1 ) {
2633 $text .= '<ul class="permissions-errors">' . "\n";
2634
2635 foreach ( $errors as $error ) {
2636 $text .= '<li>';
2637 $text .= call_user_func_array( [ $this, 'msg' ], $error )->plain();
2638 $text .= "</li>\n";
2639 }
2640 $text .= '</ul>';
2641 } else {
2642 $text .= "<div class=\"permissions-errors\">\n" .
2643 call_user_func_array( [ $this, 'msg' ], reset( $errors ) )->plain() .
2644 "\n</div>";
2645 }
2646
2647 return $text;
2648 }
2649
2650 /**
2651 * Display a page stating that the Wiki is in read-only mode.
2652 * Should only be called after wfReadOnly() has returned true.
2653 *
2654 * Historically, this function was used to show the source of the page that the user
2655 * was trying to edit and _also_ permissions error messages. The relevant code was
2656 * moved into EditPage in 1.19 (r102024 / d83c2a431c2a) and removed here in 1.25.
2657 *
2658 * @deprecated since 1.25; throw the exception directly
2659 * @throws ReadOnlyError
2660 */
2661 public function readOnlyPage() {
2662 if ( func_num_args() > 0 ) {
2663 throw new MWException( __METHOD__ . ' no longer accepts arguments since 1.25.' );
2664 }
2665
2666 throw new ReadOnlyError;
2667 }
2668
2669 /**
2670 * Turn off regular page output and return an error response
2671 * for when rate limiting has triggered.
2672 *
2673 * @deprecated since 1.25; throw the exception directly
2674 */
2675 public function rateLimited() {
2676 wfDeprecated( __METHOD__, '1.25' );
2677 throw new ThrottledError;
2678 }
2679
2680 /**
2681 * Show a warning about replica DB lag
2682 *
2683 * If the lag is higher than $wgSlaveLagCritical seconds,
2684 * then the warning is a bit more obvious. If the lag is
2685 * lower than $wgSlaveLagWarning, then no warning is shown.
2686 *
2687 * @param int $lag Slave lag
2688 */
2689 public function showLagWarning( $lag ) {
2690 $config = $this->getConfig();
2691 if ( $lag >= $config->get( 'SlaveLagWarning' ) ) {
2692 $lag = floor( $lag ); // floor to avoid nano seconds to display
2693 $message = $lag < $config->get( 'SlaveLagCritical' )
2694 ? 'lag-warn-normal'
2695 : 'lag-warn-high';
2696 $wrap = Html::rawElement( 'div', [ 'class' => "mw-{$message}" ], "\n$1\n" );
2697 $this->wrapWikiMsg( "$wrap\n", [ $message, $this->getLanguage()->formatNum( $lag ) ] );
2698 }
2699 }
2700
2701 public function showFatalError( $message ) {
2702 $this->prepareErrorPage( $this->msg( 'internalerror' ) );
2703
2704 $this->addHTML( $message );
2705 }
2706
2707 public function showUnexpectedValueError( $name, $val ) {
2708 $this->showFatalError( $this->msg( 'unexpected', $name, $val )->text() );
2709 }
2710
2711 public function showFileCopyError( $old, $new ) {
2712 $this->showFatalError( $this->msg( 'filecopyerror', $old, $new )->text() );
2713 }
2714
2715 public function showFileRenameError( $old, $new ) {
2716 $this->showFatalError( $this->msg( 'filerenameerror', $old, $new )->text() );
2717 }
2718
2719 public function showFileDeleteError( $name ) {
2720 $this->showFatalError( $this->msg( 'filedeleteerror', $name )->text() );
2721 }
2722
2723 public function showFileNotFoundError( $name ) {
2724 $this->showFatalError( $this->msg( 'filenotfound', $name )->text() );
2725 }
2726
2727 /**
2728 * Add a "return to" link pointing to a specified title
2729 *
2730 * @param Title $title Title to link
2731 * @param array $query Query string parameters
2732 * @param string $text Text of the link (input is not escaped)
2733 * @param array $options Options array to pass to Linker
2734 */
2735 public function addReturnTo( $title, array $query = [], $text = null, $options = [] ) {
2736 $linkRenderer = MediaWikiServices::getInstance()
2737 ->getLinkRendererFactory()->createFromLegacyOptions( $options );
2738 $link = $this->msg( 'returnto' )->rawParams(
2739 $linkRenderer->makeLink( $title, $text, [], $query ) )->escaped();
2740 $this->addHTML( "<p id=\"mw-returnto\">{$link}</p>\n" );
2741 }
2742
2743 /**
2744 * Add a "return to" link pointing to a specified title,
2745 * or the title indicated in the request, or else the main page
2746 *
2747 * @param mixed $unused
2748 * @param Title|string $returnto Title or String to return to
2749 * @param string $returntoquery Query string for the return to link
2750 */
2751 public function returnToMain( $unused = null, $returnto = null, $returntoquery = null ) {
2752 if ( $returnto == null ) {
2753 $returnto = $this->getRequest()->getText( 'returnto' );
2754 }
2755
2756 if ( $returntoquery == null ) {
2757 $returntoquery = $this->getRequest()->getText( 'returntoquery' );
2758 }
2759
2760 if ( $returnto === '' ) {
2761 $returnto = Title::newMainPage();
2762 }
2763
2764 if ( is_object( $returnto ) ) {
2765 $titleObj = $returnto;
2766 } else {
2767 $titleObj = Title::newFromText( $returnto );
2768 }
2769 // We don't want people to return to external interwiki. That
2770 // might potentially be used as part of a phishing scheme
2771 if ( !is_object( $titleObj ) || $titleObj->isExternal() ) {
2772 $titleObj = Title::newMainPage();
2773 }
2774
2775 $this->addReturnTo( $titleObj, wfCgiToArray( $returntoquery ) );
2776 }
2777
2778 private function getRlClientContext() {
2779 if ( !$this->rlClientContext ) {
2780 $query = ResourceLoader::makeLoaderQuery(
2781 [], // modules; not relevant
2782 $this->getLanguage()->getCode(),
2783 $this->getSkin()->getSkinName(),
2784 $this->getUser()->isLoggedIn() ? $this->getUser()->getName() : null,
2785 null, // version; not relevant
2786 ResourceLoader::inDebugMode(),
2787 null, // only; not relevant
2788 $this->isPrintable(),
2789 $this->getRequest()->getBool( 'handheld' )
2790 );
2791 $this->rlClientContext = new ResourceLoaderContext(
2792 $this->getResourceLoader(),
2793 new FauxRequest( $query )
2794 );
2795 }
2796 return $this->rlClientContext;
2797 }
2798
2799 /**
2800 * Call this to freeze the module queue and JS config and create a formatter.
2801 *
2802 * Depending on the Skin, this may get lazy-initialised in either headElement() or
2803 * getBottomScripts(). See SkinTemplate::prepareQuickTemplate(). Calling this too early may
2804 * cause unexpected side-effects since disallowUserJs() may be called at any time to change
2805 * the module filters retroactively. Skins and extension hooks may also add modules until very
2806 * late in the request lifecycle.
2807 *
2808 * @return ResourceLoaderClientHtml
2809 */
2810 public function getRlClient() {
2811 if ( !$this->rlClient ) {
2812 $context = $this->getRlClientContext();
2813 $rl = $this->getResourceLoader();
2814 $this->addModules( [
2815 'user.options',
2816 'user.tokens',
2817 ] );
2818 $this->addModuleStyles( [
2819 'site.styles',
2820 'noscript',
2821 'user.styles',
2822 ] );
2823 $this->getSkin()->setupSkinUserCss( $this );
2824
2825 // Prepare exempt modules for buildExemptModules()
2826 $exemptGroups = [ 'site' => [], 'noscript' => [], 'private' => [], 'user' => [] ];
2827 $exemptStates = [];
2828 $moduleStyles = $this->getModuleStyles( /*filter*/ true );
2829
2830 // Preload getTitleInfo for isKnownEmpty calls below and in ResourceLoaderClientHtml
2831 // Separate user-specific batch for improved cache-hit ratio.
2832 $userBatch = [ 'user.styles', 'user' ];
2833 $siteBatch = array_diff( $moduleStyles, $userBatch );
2834 $dbr = wfGetDB( DB_REPLICA );
2835 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $siteBatch );
2836 ResourceLoaderWikiModule::preloadTitleInfo( $context, $dbr, $userBatch );
2837
2838 // Filter out modules handled by buildExemptModules()
2839 $moduleStyles = array_filter( $moduleStyles,
2840 function ( $name ) use ( $rl, $context, &$exemptGroups, &$exemptStates ) {
2841 $module = $rl->getModule( $name );
2842 if ( $module ) {
2843 if ( $name === 'user.styles' && $this->isUserCssPreview() ) {
2844 $exemptStates[$name] = 'ready';
2845 // Special case in buildExemptModules()
2846 return false;
2847 }
2848 $group = $module->getGroup();
2849 if ( isset( $exemptGroups[$group] ) ) {
2850 $exemptStates[$name] = 'ready';
2851 if ( !$module->isKnownEmpty( $context ) ) {
2852 // E.g. Don't output empty <styles>
2853 $exemptGroups[$group][] = $name;
2854 }
2855 return false;
2856 }
2857 }
2858 return true;
2859 }
2860 );
2861 $this->rlExemptStyleModules = $exemptGroups;
2862
2863 $isUserModuleFiltered = !$this->filterModules( [ 'user' ] );
2864 // If this page filters out 'user', makeResourceLoaderLink will drop it.
2865 // Avoid indefinite "loading" state or untrue "ready" state (T145368).
2866 if ( !$isUserModuleFiltered ) {
2867 // Manually handled by getBottomScripts()
2868 $userModule = $rl->getModule( 'user' );
2869 $userState = $userModule->isKnownEmpty( $context ) && !$this->isUserJsPreview()
2870 ? 'ready'
2871 : 'loading';
2872 $this->rlUserModuleState = $exemptStates['user'] = $userState;
2873 }
2874
2875 $rlClient = new ResourceLoaderClientHtml( $context, $this->getTarget() );
2876 $rlClient->setConfig( $this->getJSVars() );
2877 $rlClient->setModules( $this->getModules( /*filter*/ true ) );
2878 $rlClient->setModuleStyles( $moduleStyles );
2879 $rlClient->setModuleScripts( $this->getModuleScripts( /*filter*/ true ) );
2880 $rlClient->setExemptStates( $exemptStates );
2881 $this->rlClient = $rlClient;
2882 }
2883 return $this->rlClient;
2884 }
2885
2886 /**
2887 * @param Skin $sk The given Skin
2888 * @param bool $includeStyle Unused
2889 * @return string The doctype, opening "<html>", and head element.
2890 */
2891 public function headElement( Skin $sk, $includeStyle = true ) {
2892 global $wgContLang;
2893
2894 $userdir = $this->getLanguage()->getDir();
2895 $sitedir = $wgContLang->getDir();
2896
2897 $pieces = [];
2898 $pieces[] = Html::htmlHeader( Sanitizer::mergeAttributes(
2899 $this->getRlClient()->getDocumentAttributes(),
2900 $sk->getHtmlElementAttributes()
2901 ) );
2902 $pieces[] = Html::openElement( 'head' );
2903
2904 if ( $this->getHTMLTitle() == '' ) {
2905 $this->setHTMLTitle( $this->msg( 'pagetitle', $this->getPageTitle() )->inContentLanguage() );
2906 }
2907
2908 if ( !Html::isXmlMimeType( $this->getConfig()->get( 'MimeType' ) ) ) {
2909 // Add <meta charset="UTF-8">
2910 // This should be before <title> since it defines the charset used by
2911 // text including the text inside <title>.
2912 // The spec recommends defining XHTML5's charset using the XML declaration
2913 // instead of meta.
2914 // Our XML declaration is output by Html::htmlHeader.
2915 // https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-type
2916 // https://html.spec.whatwg.org/multipage/semantics.html#charset
2917 $pieces[] = Html::element( 'meta', [ 'charset' => 'UTF-8' ] );
2918 }
2919
2920 $pieces[] = Html::element( 'title', null, $this->getHTMLTitle() );
2921 $pieces[] = $this->getRlClient()->getHeadHtml();
2922 $pieces[] = $this->buildExemptModules();
2923 $pieces = array_merge( $pieces, array_values( $this->getHeadLinksArray() ) );
2924 $pieces = array_merge( $pieces, array_values( $this->mHeadItems ) );
2925
2926 // Use an IE conditional comment to serve the script only to old IE
2927 $pieces[] = '<!--[if lt IE 9]>' .
2928 ResourceLoaderClientHtml::makeLoad(
2929 ResourceLoaderContext::newDummyContext(),
2930 [ 'html5shiv' ],
2931 ResourceLoaderModule::TYPE_SCRIPTS,
2932 [ 'sync' => true ]
2933 ) .
2934 '<![endif]-->';
2935
2936 $pieces[] = Html::closeElement( 'head' );
2937
2938 $bodyClasses = $this->mAdditionalBodyClasses;
2939 $bodyClasses[] = 'mediawiki';
2940
2941 # Classes for LTR/RTL directionality support
2942 $bodyClasses[] = $userdir;
2943 $bodyClasses[] = "sitedir-$sitedir";
2944
2945 $underline = $this->getUser()->getOption( 'underline' );
2946 if ( $underline < 2 ) {
2947 // The following classes can be used here:
2948 // * mw-underline-always
2949 // * mw-underline-never
2950 $bodyClasses[] = 'mw-underline-' . ( $underline ? 'always' : 'never' );
2951 }
2952
2953 if ( $this->getLanguage()->capitalizeAllNouns() ) {
2954 # A <body> class is probably not the best way to do this . . .
2955 $bodyClasses[] = 'capitalize-all-nouns';
2956 }
2957
2958 // Parser feature migration class
2959 // The idea is that this will eventually be removed, after the wikitext
2960 // which requires it is cleaned up.
2961 $bodyClasses[] = 'mw-hide-empty-elt';
2962
2963 $bodyClasses[] = $sk->getPageClasses( $this->getTitle() );
2964 $bodyClasses[] = 'skin-' . Sanitizer::escapeClass( $sk->getSkinName() );
2965 $bodyClasses[] =
2966 'action-' . Sanitizer::escapeClass( Action::getActionName( $this->getContext() ) );
2967
2968 $bodyAttrs = [];
2969 // While the implode() is not strictly needed, it's used for backwards compatibility
2970 // (this used to be built as a string and hooks likely still expect that).
2971 $bodyAttrs['class'] = implode( ' ', $bodyClasses );
2972
2973 // Allow skins and extensions to add body attributes they need
2974 $sk->addToBodyAttributes( $this, $bodyAttrs );
2975 Hooks::run( 'OutputPageBodyAttributes', [ $this, $sk, &$bodyAttrs ] );
2976
2977 $pieces[] = Html::openElement( 'body', $bodyAttrs );
2978
2979 return self::combineWrappedStrings( $pieces );
2980 }
2981
2982 /**
2983 * Get a ResourceLoader object associated with this OutputPage
2984 *
2985 * @return ResourceLoader
2986 */
2987 public function getResourceLoader() {
2988 if ( is_null( $this->mResourceLoader ) ) {
2989 $this->mResourceLoader = new ResourceLoader(
2990 $this->getConfig(),
2991 LoggerFactory::getInstance( 'resourceloader' )
2992 );
2993 }
2994 return $this->mResourceLoader;
2995 }
2996
2997 /**
2998 * Explicily load or embed modules on a page.
2999 *
3000 * @param array|string $modules One or more module names
3001 * @param string $only ResourceLoaderModule TYPE_ class constant
3002 * @param array $extraQuery [optional] Array with extra query parameters for the request
3003 * @return string|WrappedStringList HTML
3004 */
3005 public function makeResourceLoaderLink( $modules, $only, array $extraQuery = [] ) {
3006 // Apply 'target' and 'origin' filters
3007 $modules = $this->filterModules( (array)$modules, null, $only );
3008
3009 return ResourceLoaderClientHtml::makeLoad(
3010 $this->getRlClientContext(),
3011 $modules,
3012 $only,
3013 $extraQuery
3014 );
3015 }
3016
3017 /**
3018 * Combine WrappedString chunks and filter out empty ones
3019 *
3020 * @param array $chunks
3021 * @return string|WrappedStringList HTML
3022 */
3023 protected static function combineWrappedStrings( array $chunks ) {
3024 // Filter out empty values
3025 $chunks = array_filter( $chunks, 'strlen' );
3026 return WrappedString::join( "\n", $chunks );
3027 }
3028
3029 private function isUserJsPreview() {
3030 return $this->getConfig()->get( 'AllowUserJs' )
3031 && $this->getTitle()
3032 && $this->getTitle()->isJsSubpage()
3033 && $this->userCanPreview();
3034 }
3035
3036 protected function isUserCssPreview() {
3037 return $this->getConfig()->get( 'AllowUserCss' )
3038 && $this->getTitle()
3039 && $this->getTitle()->isCssSubpage()
3040 && $this->userCanPreview();
3041 }
3042
3043 /**
3044 * JS stuff to put at the bottom of the `<body>`. These are modules with position 'bottom',
3045 * legacy scripts ($this->mScripts), and user JS.
3046 *
3047 * @return string|WrappedStringList HTML
3048 */
3049 public function getBottomScripts() {
3050 $chunks = [];
3051 $chunks[] = $this->getRlClient()->getBodyHtml();
3052
3053 // Legacy non-ResourceLoader scripts
3054 $chunks[] = $this->mScripts;
3055
3056 // Exempt 'user' module
3057 // - May need excludepages for live preview. (T28283)
3058 // - Must use TYPE_COMBINED so its response is handled by mw.loader.implement() which
3059 // ensures execution is scheduled after the "site" module.
3060 // - Don't load if module state is already resolved as "ready".
3061 if ( $this->rlUserModuleState === 'loading' ) {
3062 if ( $this->isUserJsPreview() ) {
3063 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED,
3064 [ 'excludepage' => $this->getTitle()->getPrefixedDBkey() ]
3065 );
3066 $chunks[] = ResourceLoader::makeInlineScript(
3067 Xml::encodeJsCall( 'mw.loader.using', [
3068 [ 'user', 'site' ],
3069 new XmlJsCode(
3070 'function () {'
3071 . Xml::encodeJsCall( '$.globalEval', [
3072 $this->getRequest()->getText( 'wpTextbox1' )
3073 ] )
3074 . '}'
3075 )
3076 ] )
3077 );
3078 // FIXME: If the user is previewing, say, ./vector.js, his ./common.js will be loaded
3079 // asynchronously and may arrive *after* the inline script here. So the previewed code
3080 // may execute before ./common.js runs. Normally, ./common.js runs before ./vector.js.
3081 // Similarly, when previewing ./common.js and the user module does arrive first,
3082 // it will arrive without common.js and the inline script runs after.
3083 // Thus running common after the excluded subpage.
3084 } else {
3085 // Load normally
3086 $chunks[] = $this->makeResourceLoaderLink( 'user', ResourceLoaderModule::TYPE_COMBINED );
3087 }
3088 }
3089
3090 if ( $this->limitReportJSData ) {
3091 $chunks[] = ResourceLoader::makeInlineScript(
3092 ResourceLoader::makeConfigSetScript(
3093 [ 'wgPageParseReport' => $this->limitReportJSData ]
3094 )
3095 );
3096 }
3097
3098 return self::combineWrappedStrings( $chunks );
3099 }
3100
3101 /**
3102 * Get the javascript config vars to include on this page
3103 *
3104 * @return array Array of javascript config vars
3105 * @since 1.23
3106 */
3107 public function getJsConfigVars() {
3108 return $this->mJsConfigVars;
3109 }
3110
3111 /**
3112 * Add one or more variables to be set in mw.config in JavaScript
3113 *
3114 * @param string|array $keys Key or array of key/value pairs
3115 * @param mixed $value [optional] Value of the configuration variable
3116 */
3117 public function addJsConfigVars( $keys, $value = null ) {
3118 if ( is_array( $keys ) ) {
3119 foreach ( $keys as $key => $value ) {
3120 $this->mJsConfigVars[$key] = $value;
3121 }
3122 return;
3123 }
3124
3125 $this->mJsConfigVars[$keys] = $value;
3126 }
3127
3128 /**
3129 * Get an array containing the variables to be set in mw.config in JavaScript.
3130 *
3131 * Do not add things here which can be evaluated in ResourceLoaderStartUpModule
3132 * - in other words, page-independent/site-wide variables (without state).
3133 * You will only be adding bloat to the html page and causing page caches to
3134 * have to be purged on configuration changes.
3135 * @return array
3136 */
3137 public function getJSVars() {
3138 global $wgContLang;
3139
3140 $curRevisionId = 0;
3141 $articleId = 0;
3142 $canonicalSpecialPageName = false; # T23115
3143
3144 $title = $this->getTitle();
3145 $ns = $title->getNamespace();
3146 $canonicalNamespace = MWNamespace::exists( $ns )
3147 ? MWNamespace::getCanonicalName( $ns )
3148 : $title->getNsText();
3149
3150 $sk = $this->getSkin();
3151 // Get the relevant title so that AJAX features can use the correct page name
3152 // when making API requests from certain special pages (T36972).
3153 $relevantTitle = $sk->getRelevantTitle();
3154 $relevantUser = $sk->getRelevantUser();
3155
3156 if ( $ns == NS_SPECIAL ) {
3157 list( $canonicalSpecialPageName, /*...*/ ) =
3158 SpecialPageFactory::resolveAlias( $title->getDBkey() );
3159 } elseif ( $this->canUseWikiPage() ) {
3160 $wikiPage = $this->getWikiPage();
3161 $curRevisionId = $wikiPage->getLatest();
3162 $articleId = $wikiPage->getId();
3163 }
3164
3165 $lang = $title->getPageViewLanguage();
3166
3167 // Pre-process information
3168 $separatorTransTable = $lang->separatorTransformTable();
3169 $separatorTransTable = $separatorTransTable ? $separatorTransTable : [];
3170 $compactSeparatorTransTable = [
3171 implode( "\t", array_keys( $separatorTransTable ) ),
3172 implode( "\t", $separatorTransTable ),
3173 ];
3174 $digitTransTable = $lang->digitTransformTable();
3175 $digitTransTable = $digitTransTable ? $digitTransTable : [];
3176 $compactDigitTransTable = [
3177 implode( "\t", array_keys( $digitTransTable ) ),
3178 implode( "\t", $digitTransTable ),
3179 ];
3180
3181 $user = $this->getUser();
3182
3183 $vars = [
3184 'wgCanonicalNamespace' => $canonicalNamespace,
3185 'wgCanonicalSpecialPageName' => $canonicalSpecialPageName,
3186 'wgNamespaceNumber' => $title->getNamespace(),
3187 'wgPageName' => $title->getPrefixedDBkey(),
3188 'wgTitle' => $title->getText(),
3189 'wgCurRevisionId' => $curRevisionId,
3190 'wgRevisionId' => (int)$this->getRevisionId(),
3191 'wgArticleId' => $articleId,
3192 'wgIsArticle' => $this->isArticle(),
3193 'wgIsRedirect' => $title->isRedirect(),
3194 'wgAction' => Action::getActionName( $this->getContext() ),
3195 'wgUserName' => $user->isAnon() ? null : $user->getName(),
3196 'wgUserGroups' => $user->getEffectiveGroups(),
3197 'wgCategories' => $this->getCategories(),
3198 'wgBreakFrames' => $this->getFrameOptions() == 'DENY',
3199 'wgPageContentLanguage' => $lang->getCode(),
3200 'wgPageContentModel' => $title->getContentModel(),
3201 'wgSeparatorTransformTable' => $compactSeparatorTransTable,
3202 'wgDigitTransformTable' => $compactDigitTransTable,
3203 'wgDefaultDateFormat' => $lang->getDefaultDateFormat(),
3204 'wgMonthNames' => $lang->getMonthNamesArray(),
3205 'wgMonthNamesShort' => $lang->getMonthAbbreviationsArray(),
3206 'wgRelevantPageName' => $relevantTitle->getPrefixedDBkey(),
3207 'wgRelevantArticleId' => $relevantTitle->getArticleID(),
3208 'wgRequestId' => WebRequest::getRequestId(),
3209 ];
3210
3211 if ( $user->isLoggedIn() ) {
3212 $vars['wgUserId'] = $user->getId();
3213 $vars['wgUserEditCount'] = $user->getEditCount();
3214 $userReg = $user->getRegistration();
3215 $vars['wgUserRegistration'] = $userReg ? wfTimestamp( TS_UNIX, $userReg ) * 1000 : null;
3216 // Get the revision ID of the oldest new message on the user's talk
3217 // page. This can be used for constructing new message alerts on
3218 // the client side.
3219 $vars['wgUserNewMsgRevisionId'] = $user->getNewMessageRevisionId();
3220 }
3221
3222 if ( $wgContLang->hasVariants() ) {
3223 $vars['wgUserVariant'] = $wgContLang->getPreferredVariant();
3224 }
3225 // Same test as SkinTemplate
3226 $vars['wgIsProbablyEditable'] = $title->quickUserCan( 'edit', $user )
3227 && ( $title->exists() || $title->quickUserCan( 'create', $user ) );
3228
3229 $vars['wgRelevantPageIsProbablyEditable'] = $relevantTitle
3230 && $relevantTitle->quickUserCan( 'edit', $user )
3231 && ( $relevantTitle->exists() || $relevantTitle->quickUserCan( 'create', $user ) );
3232
3233 foreach ( $title->getRestrictionTypes() as $type ) {
3234 $vars['wgRestriction' . ucfirst( $type )] = $title->getRestrictions( $type );
3235 }
3236
3237 if ( $title->isMainPage() ) {
3238 $vars['wgIsMainPage'] = true;
3239 }
3240
3241 if ( $this->mRedirectedFrom ) {
3242 $vars['wgRedirectedFrom'] = $this->mRedirectedFrom->getPrefixedDBkey();
3243 }
3244
3245 if ( $relevantUser ) {
3246 $vars['wgRelevantUserName'] = $relevantUser->getName();
3247 }
3248
3249 // Allow extensions to add their custom variables to the mw.config map.
3250 // Use the 'ResourceLoaderGetConfigVars' hook if the variable is not
3251 // page-dependant but site-wide (without state).
3252 // Alternatively, you may want to use OutputPage->addJsConfigVars() instead.
3253 Hooks::run( 'MakeGlobalVariablesScript', [ &$vars, $this ] );
3254
3255 // Merge in variables from addJsConfigVars last
3256 return array_merge( $vars, $this->getJsConfigVars() );
3257 }
3258
3259 /**
3260 * To make it harder for someone to slip a user a fake
3261 * user-JavaScript or user-CSS preview, a random token
3262 * is associated with the login session. If it's not
3263 * passed back with the preview request, we won't render
3264 * the code.
3265 *
3266 * @return bool
3267 */
3268 public function userCanPreview() {
3269 $request = $this->getRequest();
3270 if (
3271 $request->getVal( 'action' ) !== 'submit' ||
3272 !$request->getCheck( 'wpPreview' ) ||
3273 !$request->wasPosted()
3274 ) {
3275 return false;
3276 }
3277
3278 $user = $this->getUser();
3279
3280 if ( !$user->isLoggedIn() ) {
3281 // Anons have predictable edit tokens
3282 return false;
3283 }
3284 if ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ) ) ) {
3285 return false;
3286 }
3287
3288 $title = $this->getTitle();
3289 if ( !$title->isJsSubpage() && !$title->isCssSubpage() ) {
3290 return false;
3291 }
3292 if ( !$title->isSubpageOf( $user->getUserPage() ) ) {
3293 // Don't execute another user's CSS or JS on preview (T85855)
3294 return false;
3295 }
3296
3297 $errors = $title->getUserPermissionsErrors( 'edit', $user );
3298 if ( count( $errors ) !== 0 ) {
3299 return false;
3300 }
3301
3302 return true;
3303 }
3304
3305 /**
3306 * @return array Array in format "link name or number => 'link html'".
3307 */
3308 public function getHeadLinksArray() {
3309 global $wgVersion;
3310
3311 $tags = [];
3312 $config = $this->getConfig();
3313
3314 $canonicalUrl = $this->mCanonicalUrl;
3315
3316 $tags['meta-generator'] = Html::element( 'meta', [
3317 'name' => 'generator',
3318 'content' => "MediaWiki $wgVersion",
3319 ] );
3320
3321 if ( $config->get( 'ReferrerPolicy' ) !== false ) {
3322 $tags['meta-referrer'] = Html::element( 'meta', [
3323 'name' => 'referrer',
3324 'content' => $config->get( 'ReferrerPolicy' )
3325 ] );
3326 }
3327
3328 $p = "{$this->mIndexPolicy},{$this->mFollowPolicy}";
3329 if ( $p !== 'index,follow' ) {
3330 // http://www.robotstxt.org/wc/meta-user.html
3331 // Only show if it's different from the default robots policy
3332 $tags['meta-robots'] = Html::element( 'meta', [
3333 'name' => 'robots',
3334 'content' => $p,
3335 ] );
3336 }
3337
3338 foreach ( $this->mMetatags as $tag ) {
3339 if ( strncasecmp( $tag[0], 'http:', 5 ) === 0 ) {
3340 $a = 'http-equiv';
3341 $tag[0] = substr( $tag[0], 5 );
3342 } elseif ( strncasecmp( $tag[0], 'og:', 3 ) === 0 ) {
3343 $a = 'property';
3344 } else {
3345 $a = 'name';
3346 }
3347 $tagName = "meta-{$tag[0]}";
3348 if ( isset( $tags[$tagName] ) ) {
3349 $tagName .= $tag[1];
3350 }
3351 $tags[$tagName] = Html::element( 'meta',
3352 [
3353 $a => $tag[0],
3354 'content' => $tag[1]
3355 ]
3356 );
3357 }
3358
3359 foreach ( $this->mLinktags as $tag ) {
3360 $tags[] = Html::element( 'link', $tag );
3361 }
3362
3363 # Universal edit button
3364 if ( $config->get( 'UniversalEditButton' ) && $this->isArticleRelated() ) {
3365 $user = $this->getUser();
3366 if ( $this->getTitle()->quickUserCan( 'edit', $user )
3367 && ( $this->getTitle()->exists() ||
3368 $this->getTitle()->quickUserCan( 'create', $user ) )
3369 ) {
3370 // Original UniversalEditButton
3371 $msg = $this->msg( 'edit' )->text();
3372 $tags['universal-edit-button'] = Html::element( 'link', [
3373 'rel' => 'alternate',
3374 'type' => 'application/x-wiki',
3375 'title' => $msg,
3376 'href' => $this->getTitle()->getEditURL(),
3377 ] );
3378 // Alternate edit link
3379 $tags['alternative-edit'] = Html::element( 'link', [
3380 'rel' => 'edit',
3381 'title' => $msg,
3382 'href' => $this->getTitle()->getEditURL(),
3383 ] );
3384 }
3385 }
3386
3387 # Generally the order of the favicon and apple-touch-icon links
3388 # should not matter, but Konqueror (3.5.9 at least) incorrectly
3389 # uses whichever one appears later in the HTML source. Make sure
3390 # apple-touch-icon is specified first to avoid this.
3391 if ( $config->get( 'AppleTouchIcon' ) !== false ) {
3392 $tags['apple-touch-icon'] = Html::element( 'link', [
3393 'rel' => 'apple-touch-icon',
3394 'href' => $config->get( 'AppleTouchIcon' )
3395 ] );
3396 }
3397
3398 if ( $config->get( 'Favicon' ) !== false ) {
3399 $tags['favicon'] = Html::element( 'link', [
3400 'rel' => 'shortcut icon',
3401 'href' => $config->get( 'Favicon' )
3402 ] );
3403 }
3404
3405 # OpenSearch description link
3406 $tags['opensearch'] = Html::element( 'link', [
3407 'rel' => 'search',
3408 'type' => 'application/opensearchdescription+xml',
3409 'href' => wfScript( 'opensearch_desc' ),
3410 'title' => $this->msg( 'opensearch-desc' )->inContentLanguage()->text(),
3411 ] );
3412
3413 if ( $config->get( 'EnableAPI' ) ) {
3414 # Real Simple Discovery link, provides auto-discovery information
3415 # for the MediaWiki API (and potentially additional custom API
3416 # support such as WordPress or Twitter-compatible APIs for a
3417 # blogging extension, etc)
3418 $tags['rsd'] = Html::element( 'link', [
3419 'rel' => 'EditURI',
3420 'type' => 'application/rsd+xml',
3421 // Output a protocol-relative URL here if $wgServer is protocol-relative.
3422 // Whether RSD accepts relative or protocol-relative URLs is completely
3423 // undocumented, though.
3424 'href' => wfExpandUrl( wfAppendQuery(
3425 wfScript( 'api' ),
3426 [ 'action' => 'rsd' ] ),
3427 PROTO_RELATIVE
3428 ),
3429 ] );
3430 }
3431
3432 # Language variants
3433 if ( !$config->get( 'DisableLangConversion' ) ) {
3434 $lang = $this->getTitle()->getPageLanguage();
3435 if ( $lang->hasVariants() ) {
3436 $variants = $lang->getVariants();
3437 foreach ( $variants as $variant ) {
3438 $tags["variant-$variant"] = Html::element( 'link', [
3439 'rel' => 'alternate',
3440 'hreflang' => LanguageCode::bcp47( $variant ),
3441 'href' => $this->getTitle()->getLocalURL(
3442 [ 'variant' => $variant ] )
3443 ]
3444 );
3445 }
3446 # x-default link per https://support.google.com/webmasters/answer/189077?hl=en
3447 $tags["variant-x-default"] = Html::element( 'link', [
3448 'rel' => 'alternate',
3449 'hreflang' => 'x-default',
3450 'href' => $this->getTitle()->getLocalURL() ] );
3451 }
3452 }
3453
3454 # Copyright
3455 if ( $this->copyrightUrl !== null ) {
3456 $copyright = $this->copyrightUrl;
3457 } else {
3458 $copyright = '';
3459 if ( $config->get( 'RightsPage' ) ) {
3460 $copy = Title::newFromText( $config->get( 'RightsPage' ) );
3461
3462 if ( $copy ) {
3463 $copyright = $copy->getLocalURL();
3464 }
3465 }
3466
3467 if ( !$copyright && $config->get( 'RightsUrl' ) ) {
3468 $copyright = $config->get( 'RightsUrl' );
3469 }
3470 }
3471
3472 if ( $copyright ) {
3473 $tags['copyright'] = Html::element( 'link', [
3474 'rel' => 'license',
3475 'href' => $copyright ]
3476 );
3477 }
3478
3479 # Feeds
3480 if ( $config->get( 'Feed' ) ) {
3481 $feedLinks = [];
3482
3483 foreach ( $this->getSyndicationLinks() as $format => $link ) {
3484 # Use the page name for the title. In principle, this could
3485 # lead to issues with having the same name for different feeds
3486 # corresponding to the same page, but we can't avoid that at
3487 # this low a level.
3488
3489 $feedLinks[] = $this->feedLink(
3490 $format,
3491 $link,
3492 # Used messages: 'page-rss-feed' and 'page-atom-feed' (for an easier grep)
3493 $this->msg(
3494 "page-{$format}-feed", $this->getTitle()->getPrefixedText()
3495 )->text()
3496 );
3497 }
3498
3499 # Recent changes feed should appear on every page (except recentchanges,
3500 # that would be redundant). Put it after the per-page feed to avoid
3501 # changing existing behavior. It's still available, probably via a
3502 # menu in your browser. Some sites might have a different feed they'd
3503 # like to promote instead of the RC feed (maybe like a "Recent New Articles"
3504 # or "Breaking news" one). For this, we see if $wgOverrideSiteFeed is defined.
3505 # If so, use it instead.
3506 $sitename = $config->get( 'Sitename' );
3507 if ( $config->get( 'OverrideSiteFeed' ) ) {
3508 foreach ( $config->get( 'OverrideSiteFeed' ) as $type => $feedUrl ) {
3509 // Note, this->feedLink escapes the url.
3510 $feedLinks[] = $this->feedLink(
3511 $type,
3512 $feedUrl,
3513 $this->msg( "site-{$type}-feed", $sitename )->text()
3514 );
3515 }
3516 } elseif ( !$this->getTitle()->isSpecial( 'Recentchanges' ) ) {
3517 $rctitle = SpecialPage::getTitleFor( 'Recentchanges' );
3518 foreach ( $config->get( 'AdvertisedFeedTypes' ) as $format ) {
3519 $feedLinks[] = $this->feedLink(
3520 $format,
3521 $rctitle->getLocalURL( [ 'feed' => $format ] ),
3522 # For grep: 'site-rss-feed', 'site-atom-feed'
3523 $this->